I have a program, where I have to generate all R-digit numbers among N digits in C++, for example for N=3 (all digits from 1 to N inclusive) and R=2 the program should generate 12 13 21 23 31 32. I tried to do this with arrays as follows, but it does not seem to work correctly.
#define nmax 20
#include <iostream>
using namespace std;
int n, r;
void print(int[]);
int main()
{
cin >> n;
cin >> r;
int a[nmax];
int b[nmax];
int used[nmax];
for (int p = 1; p <= n; p++) {
//Filling the a[] array with numbers from 1 to n
a[p] = n;
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < r; j++) {
b[j] = a[i];
used[j] = 1;
if (used[j]) {
b[j] = a[i + 1];
}
used[j] = 0;
}
print(b);
}
return 0;
}
void print(int k[]) {
for (int i = 0; i < r; i++) {
cout << k[i];
}
}
If I understand your question correctly, you can explore this website where it explains the problem and suggests the solution thoroughly.
Here is a slightly altered code:
Pay attention that time is an issue for bigger N values.
#define N 5 // number of elements to permute. Let N > 2
#include <iostream>
using namespace std;
// NOTICE: Original Copyright 1991-2010, Phillip Paul Fuchs
void PrintPerm(unsigned int *a, unsigned int j, unsigned int i){
for(unsigned int x = 0; x < N; x++)
cout << " " << a[x];
cout << " swapped( " << j << " , " << i << " )\n";
}
void QuickPerm(void){
unsigned int a[N], p[N+1];
register unsigned int i, j, PermCounter = 1; // Upper Index i; Lower Index j
for(i = 0; i < N; i++){ // initialize arrays; a[N] can be any type
a[i] = i + 1; // a[i] value is not revealed and can be arbitrary
p[i] = i;
}
p[N] = N; // p[N] > 0 controls iteration and the index boundary for i
PrintPerm(a, 0, 0); // remove comment to PrintPerm array a[]
i = 1; // setup first swap points to be 1 and 0 respectively (i & j)
while(i < N){
p[i]--; // decrease index "weight" for i by one
j = i % 2 * p[i]; // IF i is odd then j = p[i] otherwise j = 0
swap(a[i], a[j]); // swap(a[j], a[i])
PrintPerm(a, j, i); // remove comment to PrintPerm target array a[]
PermCounter++;
i = 1; // reset index i to 1 (assumed)
while (!p[i]) { // while (p[i] == 0)
p[i] = i; // reset p[i] zero value
i++; // set new index value for i (increase by one)
} // while(!p[i])
} // while(i < N)
cout << "\n\n ---> " << PermCounter << " permutations. \n\n\n";
} // QuickPerm()
int main(){
QuickPerm();
} //main
Here is a list of the modified items from the original code.
N defined to be 5 instead of 12.
A Counter has been added for more informative result.
The original swap instructions reduced by using c++ standard libraries' swap() function.
The getch() has been removed.
The 'Display()' function has been renamed to be 'PrintPerm()'.
The printf() function has been replaced by cout.
Printing number of permutation has been added.
Related
I am trying to implement the Sieve of Eratosthenes algorithm but it giving a runtime error.
didn't get any output though. after providing the input,
#include<iostream>
using namespace std;
//Sieve Approach - Generate an array containing prime Numbers
void prime_sieve(int *p) {
//first mark all odd number's prime
for (int i = 3; i <= 10000; i += 2) {
p[i] = 1;
}
// Sieve
for (long long int i = 3; i <= 10000; i += 2) {
//if the current number is not marked (it is prime)
if (p[i] == 1) {
//mark all the multiples of i as not prime
for (long long int j = i * i; j <= 10000; j = j + i ) {
p[j] = 0;
}
}
}
//special case
p[2] = 1;
p[1] = p[0] = 0;
}
int main() {
int n;
cin >> n;
int p[10000] = {0};
prime_sieve(p);
//lets print primes upto range n
for (int i = 0; i <= n; i++) {
if (p[i] == 1) {
cout << i << " ";
}
}
return 0;
}
compiler didn't throwing any error also it is not providing the output also
program freezes for some seconds and then terminates
As mentioned in the comments, you are going out of bound.
There is also some confusion about the meaning of p[].
In addition, you are not using the value of n in the function, which leads to unnecessary calculations.
Here is a tested programme (up to n = 10000):
#include <iostream>
#include <vector>
#include <cmath>
//Sieve Approach - Generate an array containing prime Numbers less than n
void prime_sieve(std::vector<int> &p, long long int n) {
//first mark all odd number's prime
for (long long int i = 4; i <= n; i += 2) {
p[i] = 0;
}
// Sieve
for (long long int i = 3; i <= sqrt(n); i += 2) {
//if the current number is not marked (it is prime)
if (p[i] == 1) {
//mark all the multiples of i as not prime
for (long long int j = i * i; j <= n; j = j + i ) {
p[j] = 0;
}
}
}
//special cases
p[1] = p[0] = 0;
}
int main() {
long long int n;
std::cout << "Enter n: ";
std::cin >> n;
std::vector<int> p (n+1, 1);
prime_sieve(p, n);
//lets print primes upto range n
for (long long int i = 0; i <= n; i++) {
if (p[i] == 1) {
std::cout << i << " ";
}
}
return 0;
}
so I've got integers m and n in my program, once you input the values it should create an array with values from m to n (for example m = 1 and n = 10, it creates array q with values from 1 to 10). Then it looks in the array if there are any numbers that are equal to any two number summ that are squared (for example, in the array, number 5 is equal to 1 squared + 2 squared). The problem is when I try to input the first value it crashes, pretty sure the problem is in the function but can't seem to figure it out. Thanks
#include <iostream>
using namespace std;
int squared (int a, int b, int q[]){
while (a<=0 || b<=0){
cout <<"You can't input an integer that is 0 or below: ";
cin >>a;
cin >>b;
if (a>0 || b>0) break;
}
for (int p=0; p<b; p++){
for (int i=a ; i<b; i++){
q[p] = a;
}
}
for (int z=0; z<b; z++){
for (int x=0; x<b; x++){
for (int c=0; c<b; c++){
if (q[z] == (q[x] * q[x]) + (q[c] * q[c])){
int result= (q[x] * q[x]) + (q[c] * q[c]);
return result;
}
}
}
}
}
int main () {
int m,n;
int M[100];
cout <<"Input integers m un n: ";
cin >>m,n;
cout <<squared(m,n,M);
return 0;
}
Most likely it crashes because of this: cin >>m,n;, it should be cin >> m >> n;, else you use n uninitialized on the next line, thus getting undefined behaviour, e.g. crash.
What compiler are you using and with what flags, since this would trigger some warnings/errors at compile normally.
cin >> m, n; is incorrect which inputs only m which can be interpreted as:
(cin >> m), n; which means: cin, n; to correct it:
cin >> m >> n;
if(a > 0 || b > 0) break; is redundant because you check for this condition twice: once in while condition second inside while loop thus checking for the same condition is redundant because while breaks automatically if the condition succeeds (a or b is equal or smaller than 0).
you passed an array without passing its size, you are lucky if you set the first element 1 the any second value is equal to the size of array eg:
m = 1; n = 10; then the size is ten which is correct.
what about:
m = 7; n = 10; // now is size 10? it's only 3
to correct it pass the size eg:
m = 4; n = 8;
int size = 8 - 4;
cout << Squared(m, n, M, size);
also:
for (int p = 0; p < b; p++)
{
for (int i = a ; i < b; i++)
{
q[p] = a;
}
}
you are assigning the same value a to all elements of array and iterating doing the same thing in the nested-loop!!! it's likely to write:
int x = 0; x = 0;
so the condition of result inside squared will never succeed because the same value is never equal to its square. 4 = 4 * 4 is never reached
here is what you search for:
#include <iostream>
using namespace std;
// I only make squared search for the result not inputing m and n lik e in yours
int squared (int m, int n, int* M)
{
int result;
for(int i(0); i < n; i++)
for(int j(0); j < n; j++)
for(int k(0); k < n; k++)
if( (M[i] == ( (M[j] * M[j]) + (M[k] * M[k]) )) && j != k) // here to avoid comparing with the same index
{
cout << M[i] << " = (" << M[j] << "*" << M[j] << ") + (" << M[k] << "*" << M[k] << ")" << endl;
result = ( (M[j] * M[j]) + (M[k] * M[k]) );
cout << result << endl;
return result; // if success we return result
}
return -1; // otherwise we return -1 as a sign of error (no square yields in negative value)
}
int main ()
{
int n, m, size;
do
{
cout <<"m: ";
cin >> m;
cout << "n: ";
cin >> n;
if(n <= 0 || m <= 0)
cout <<"You can't input an integer that is 0 or below: ";
// also it's very important to check whether n is greater than m or not because if m == n or m > n then size will be negative and as you know no array has a negative nor 0 size
if(m >= n)
cout << "n must be greater than m!" << endl;
}while (m <= 0 || n <= 0 || m >= n);
size = n - m; // getting size of array assuming m can be any value
int* M = new int[n - m]; // allocating dynamic array
// inputting array as you asked
for(int i(0), j = m; i < size; i++, j++)
M[i] = j;
// checking the values of array elements
for(int i = 0; i < size; i++)
cout << M[i] << ", " ;
cout << endl;
// getting the result
cout << squared(m, n, M) << endl;
// cleaning
delete[] M;
return 0;
}
I have implemented the normal Radix Sort:
#include <iostream>
using namespace std;
void print(int arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int findMax(int arr[], int n) {
int mx = 0;
for (int i = 0; i < n; i++) {
if (arr[i] > mx)
mx = arr[i];
}
return mx;
}
void countingSort(int arr[], int n, int exp) {
int output[n];
const int m = findMax(arr, n) + 1;
int C[m];
for (int i = 0; i < m; i++) {
C[i] = 0;
}
for (int i = 0; i < n; i++)
C[(arr[i] / exp) % 10]++;
for (int i = 1; i < 10; i++)
C[i] += C[i - 1];
for (int i = n - 1; i >= 0; i--) {
output[C[(arr[i] / exp) % 10] - 1] = arr[i];
C[(arr[i] / exp) % 10]--;
}
for (int i = 0; i < n; i++)
arr[i] = output[i];
}
void radixSotr(int arr[], int n) {
int m = findMax(arr, n);
for (int exp = 1; m / exp > 0; exp *= 10) {
countingSort(arr, n, exp);
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter the elements of the array: ";
for (int i = 0; i < n; i++) {
cin >> arr[i];
}
cout << endl;
cout << "Unsorted version of the array: " << endl;
print(arr, n);
cout << endl;
cout << "Sorted version of the array: " << endl;
radixSotr(arr, n);
print(arr, n);
return 0;
}
Now I am trying to implement Hollerith's version of Radix Sort, where the Radix Sort starts with the most significant bit and propagates iteratively to the least significant bit. Could you give me any ideas how to modify my code, because I am stuck.
Your countingSort function has a problem:
you should use an array of 10 indexes for counting instead of finding the largest element and declaring int C[m]. Your current code allocates a potentially huge array in automatic storage, invoking undefined behavior.
Here is a corrected version:
void countingSort(int arr[], int n, int exp) {
int output[n];
int C[10] = { 0 };
for (int i = 0; i < n; i++)
C[(arr[i] / exp) % 10]++;
for (int i = 1; i < 10; i++)
C[i] += C[i - 1];
for (int i = n - 1; i >= 0; i--) {
output[--C[(arr[i] / exp) % 10]] = arr[i];
C[(arr[i] / exp) % 10]--;
}
for (int i = 0; i < n; i++)
arr[i] = output[i];
}
Note that this algorithm cannot sort an array with negative numbers.
The Hollerith algorithm uses least significant digit to most significant digit. It was invented for sorting US Census data tabulated on punched cards using tabulating machines. This is a very early example of computing for data processing that goes back to 1887. Punch cards used 2 different character encoding schemes named H-code and T-code all the way to the end of the 20th century, H standing for Herman Hollerith, inventor of these sorting machines, who died in 1929. (see http://ed-thelen.org/comp-hist/Knuth-Sort.html )
For the most significant bit down to the least significant bit, you need recursion, not an iterative method like the one you have:
Find the maximum value, hence the maximum exponent to get the most significant digit.
Sort the array according to the current digit
For each bucket of elements with the same digit at the current position:
if the bucket is empty or has only one element, it is sorted
otherwise, recurse on the bucket for the next lesser digit, using exp/10.
You can do this with any base >= 2.
#include <iostream>
using namespace std;
// Selection Sort function.
// Parameter 'a' is the size of the array.
void ss(int AR[] , int a) {
int small;
for (int i = 0 ; i <a ; i++) {
small = AR[i];
for (int j = i+1 ; j <a ; j++) {
if (AR[j]< small) {
int k = AR[j];
AR[j] = AR[i];
AR[i] = k;
}
}
}
}
int main() {
cout << "Enter the size of Your Aray";
int a;
cin >> a;
int AR[a];
cout << endl;
for (int i = 0; i < a; i++) {
cin >> AR[i];
cout << endl;
}
ss(AR, a);
cout << "The Sorted Array is";
for (int i=0; i < a; i++) {
cout << AR[i] << " ";
cout << endl;
}
}
When I enter the following:
15
6
13
22
23
52
2
The result returned is:
2
13
6
15
22
23
52
What is the bug preventing the list from being sorted numerically as expected?
The function can look like
void ss ( int a[], size_t n )
{
for ( size_t i = 0 ; i < n ; i++ )
{
size _t small = i;
for ( size_t j = i + 1; j < n ; j++ )
{
if ( a[j] < a[small] ) small = j;
}
if ( i != small )
{
int tmp = a[small];
a[small] = a[i];
a[i] = tmp;
}
}
}
It doesn't seem to be the SelectionSort I know. in the algorithm I know during every loop I look for the smallest element in the right subarray and than exchange it with the "pivot" element of the loop. Here's the algorithm
void selectionSort(int* a, int dim)
{
int posMin , aux;
for(int i = 0; i < dim - 1; ++i)
{
posMin = i;
for(int j = i + 1; j < dim; ++j)
{
if(a[j] < a[posMin])
posMin = j;
}
aux = a[i];
a[i] = a[posMin];
a[posMin] = aux;
}
}
and it seems that you change every smaller element you find, but also change the position of the "pivot". I hope the answer is clear.
Everything is ok in the original function, only that the small variable need to be refreshed when two vector elements will be switched.
Also in if statement set the small variable to the new value of AR[i].
I want to write Fibonacci number program, using dynamic array in function. If I want to initialize array in the function, where I must delete this array? Here is code:
#include <iostream>
using namespace std;
int* fibo(int);
int main()
{
int *fibonacci, n;
cout << "Enter how many fibonacci numbers you want to print: ";
cin >> n;
fibonacci = fibo(n);
for (int i = 0; i<n; i++)
cout << fibonacci[i] << " ";
//for (int i = 0; i < n; i++)
//delete w_fibo[i];
//delete[] w_fibo;
return 0;
}
int* fibo(int n)
{
int* w_fibo = new int[n];
if (n >= 0)
w_fibo[0] = 1;
if (n >= 1)
w_fibo[1] = 1;
for (int i = 1; i < n; i++)
w_fibo[i + 1] = w_fibo[i] + w_fibo[i - 1];
return w_fibo;
}
You don't have to initialize the array! a better dynamic Fibonacci presentation could be like this:
int fib2 (int n) {
int i = 1, j = 0;
for (int k = 0; k < n; k++) { // The loop begins to work real after one loop (k == 1). Sounds interesting!
j += i; // Adds the produced number to the last member of the sequence and makes a new sentence.
i = j - i; // Produces the number that should be added to the sequence.
}
return j;
}
and you can get the n-th fib number using this method. It's O(log(n)) so it's so efficient.`
int fib3 (int n) {
int i = 1, j = 0, k = 0, h = 1, t=0;
while (n > 0) {
if (n % 2) { // |
t = j * h; // |
j = i * h + j * k + t;
i = i * k + t;
}
t = h * h;
h = 2 * k * h + t;
k = k * k + t;
n /= 2;
}
return j;
}
If you allocate a std::vector<int> inside fibo() and reserve enough memory, and then return it by value, the memory allocation is taken care for you by the compiler:
#include <iostream>
#include <vector>
using namespace std;
std::vector<int> fibo(int n)
{
std::vector<int> w_fibo;
w_fibo.reserve(n);
if (n >= 0)
w_fibo[0] = 1;
if (n >= 1)
w_fibo[1] = 1;
for (int i = 1; i < n; i++)
w_fibo[i + 1] = w_fibo[i] + w_fibo[i - 1];
return w_fibo;
}
int main()
{
int n = 10;
std::vector<int> fibonacci = fibo(n);
for (int i = 0; i<n; i++)
cout << fibonacci[i] << " ";
}
Live Example.
NOTE: This is guaranteed to avoid needlessly copying in C++11 (move semantics) and is likely to do so in C++98 (copy-elision using the return-value-optimization).
This is an old question, but just in case someone happens to pass by this might be helpful.
If you need a efficient method to get the nth Fibonacci number, we have a O(1) time complexity procedure.
It is based on Binet's formula, which I think our friends over at math.se will be better at proving, so feel free to follow that link.
The formula itself is, given a=1.618 and b=-0.618 (these are approximate values)
the n-th term is (a^n - b^n)/2.236. A good way to round that off(since we are using approximate values) would be adding 0.5 and taking the floor function.
math.floor(((math.pow(1.618,n)-math.pow(-0.618,n))/2.236 + 0.5)