Linear Recursion reverse the array - c++

Can not figure out why my recursion function does not work?
#include <iostream>
using namespace std;
int ReverseArray(int* A, int i, int j);
int main()
{
int j = 10;
int i = 0;
int *b = new int[j];
for (int i = 0; i <= 10; i++)
b[i] = i;
for (int i = 0; i <= 10; i++) //just to compare the old and new array
cout << b[i] << endl; //just to compare the
for(int i = 0; i <= j; i++)
cout << ReverseArray(b,i,j) << endl;
system("pause");
return 0;
}
int ReverseArray(int* A, int i, int j)
{
if (i <= j)
{
swap(A[i], A[j]);
ReverseArray(A, i + 1, j - 1);
}
return A[i];
This should return
10,9,8....
but it returns
10,0,9,1...
I don't get why its happening

You have a double loop, once here:
for(int i = 0; i <= j; i++)
cout << ReverseArray(b,i,j) << endl;
and once here:
ReverseArray(A, i + 1, j - 1);
Calling a function recursively is equivalent to looping over it. To reverse a list, you only need to loop over it once, and what you've done is the equivalent of a doubly-nested loop. So let's get rid of
for(int i = 0; i <= j; i++)
and change
cout << ReverseArray(b,i,j) << endl;
to just
ReverseArray(b,i,j);
Then you are only reversing b, nothing else. To print, just loop from 0 to 10 and print each element.
Also, unrelated, but keep in mind that the code as you have it right now touches memory that has not been allocated to the heap.
int *b = new int[j];
creates j (here, 10) ints, at the physical memory locations b, b + 1, b + 2, ..., b + 9. b[i] then gets the memory held at b + i, that is, it gets *(b + i). Several of your loops try to do things with b[10], and there has not been enough memory allocated for it. This will result in undefined behaviour (i.e. many different things can happen depending on your compiler and the state of your computer). With 'system("pause");' removed (which shouldn't affect code execution) on my machine, this gave me a memory allocation for that reason.
Solution here is to either have
int *b = new int[j+1];
or replace all your <= signs with <.

Related

Generating all R-digit numbers among N digits in C++ (combinations, iterative)?

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.

Fibonacci numbers - dynamic array

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)

Segmentation fault while passing multidimensional arrays, c++

I'm pretty new to coding in c++ so I apologize if this question has a very apparent simple answer. I'm trying to create a matrix of random numbers from -1 to 1. These are the two functions I am using:
#include <iostream>
#include "matrix_fill_random.cpp"
using namespace std;
int main(int argc, int argv[]){
int n1, n2, n3;
if (argc != 4) {
cerr << "This program requires 3 argument!" <<endl;
return 1;
}
else{
n1 = argv[1];
n2 = argv[2];
n3 = argv[3];
double** a;
matrix_fill_random(n1, n2, a);
return 0;
}
}
and
#include <iostream>
using namespace std;
int matrix_fill_random(int n1, int n2, double** a){
for (int i=0; i<n1; i++){
for (int j=0; j<n2; j++){
double num = rand() % 2 - 1;
a[i][j]=num;
}
}
return 0;
}
Ultimately I'm trying to create two matrices and then multiply them together so n1, n2, and n3 represent the rows and columns of two matrices, but that isn't all too important right now. I think the error might be in how I declare my variables or pass them to other functions but I'm not entirely sure.
I feel like if I can understand the principle of creating one of the matrices then that would translate to the other functions I need to use.
double** a;
You haven't allocated memory for the pointer, so you're getting Undefined Behavior each time you dereference it using operator [].
You should allocate a once before passing it through the function...
double** a = new double*[n1];
and once more inside the for loop of the function:
for (int i = 0; i < n1; i++)
{
a[i] = new double[n2];
for (int j = 0; j < n2; j++)
{
double num = rand() % 2 - 1;
a[i][j] = num;
}
}
But don't forget to delete[] the pointer once you're done using it. You should delete the other pointers allocated inside the for loop as well.
Of course, this can all be avoided by using std::vector. Here is your program fitted with the Standard Library:
std::vector<std::vector<double>> a(n1, std::vector<double>(n2));
int matrix_fill_random(std::vector<std::vector<double>> a)
{
for (int i = 0; i < a.size(); ++i)
{
for (int j = 0; j < a[i].size(); ++j)
{
double num = rand() % 2 - 1;
a[i][j] = num;
}
}
return 0;
}
Allocate the memory for a. You haven't allocate the memory for a. Chane the statement double** a; to
double** a = new double[n1];
and change the loop as follows
for (int i = 0; i < n1; i++)
{
//Every row will be of size = number of columns.
a[i] = new double[n2];
for (int j = 0; j < n2; j++)
{
double num = rand() % 2 - 1;
a[i][j] = num;
}
}
double** a;
matrix_fill_random(n1, n2, a);
passes uninitialized pointer a to the function, which tries to initialize elements of two-dimensional array:
a[i][j]=num;
which invokes an undefined behavior. The simplest solution would be to allocate a single block of memory that will be big enough to hold the matrix:
double* a = new double[rows * cols];
matrix_fill_random(n1, n2, a);
delete[] a;
a = NULL;
...
// accessing element a[i][j] in the function's body:
a[i*cols + j] = num;
but most reasonable solution would be using std::vector instead of C-style arrays.
You need to allocate memory to a before passing it to matrix_fill_random().
double** a = new double[n1];
Since you're using C++ though, you should consider using a vector or other template container.

Simple array not stepping through

int i;
int b = 0;
int a[20];
for (i = 0; i < 20; i++){
a[i] = b+1;
cout << a[i];}
}
//I know this is a simple program but it is not giving the expected output and does not step through the program or print out the result
Your loop keeps assigning a[i] without changing b. Since b stays at zero, all as are going to be 1 (because b is zero, b+1 is 1).
If you would like to assign sequential values, either use the loop index i, or change b in the body of the loop:
for (i = 0; i < 20; i++) {
a[i] = i+1;
}
or
for (i = 0; i < 20; i++) {
a[i] = ++b; // Adds 1 to b, and changes b for the next iteration.
}
You are printing out the wrong variable. This should work:
int i;
int a[20];
for (i = 0; i < 20; i++){
a[i] = i+1;
cout << a[i];}
You can do it like this if you want it assign through b :
int i;
int b = 1;
int a[20];
for (i = 0; i < 20; i++){
a[i] = b;
cout << a[i];
b++;}

Heap corruption on delete[]

I've been getting heap corruption error on delete[] instruction. Project is worked on in VC++ 2008, its requirement (so please don't focus on that). Whole building process is working OK, but in run-time I get error: (prs_2013 is name of my project)
Windows has triggered a breakpoint in prs_2013.exe.
This may be due to a corruption of the heap, which indicates a bug in prs_2013.exe or any of the DLLs it has loaded.
This may also be due to the user pressing F12 while prs_2013.exe has focus.
The output window may have more diagnostic information.
This is code where error occurs, its just a fraction of whole project, but error is confined in this area:
// Function used for swapping row of matrix with new values
void Main::swap(double* matrix, double* row, unsigned index, unsigned size){
double temp = 0;
for(unsigned i = 0; i < size; i++){
temp = matrix[i*size + index];
matrix[i*size + index] = row[i];
row[i] = temp;
}
}
// Function that do some calculations, not really relevant for this problem
// but still used in code
double Main::determinat(double* matrix, unsigned size){
double ud = 0, du = 0;
for(unsigned j = 0; j < size; j++){
double ude = 1, due = 1;
for(unsigned i = 0; i < size; i++){
ude *= matrix[i*size + (i+j)%size];
due *= matrix[(size-i)*size + (i + j)%size];
}
ud += ude;
du += due;
}
return ud - du;
}
// Function in which error occurs
double* Main::get_x(double* matrix, unsigned size){
// error checking
if(size == 1){return NULL;}
double *x = new double[size];
x[0] = 1;
unsigned const temp_size = size-1;
double *temp = new double[temp_size * temp_size]; // temporary matrica
double *x0_coef = new double[temp_size]; // variable on which error occures
for(unsigned i = 0; i < temp_size; i++)
x0_coef[i] = matrix[i*size + 0] / s[0]; // s is class member, init in constructor s[0] != 0
for(unsigned i = 1; i < size; i++)
for(unsigned j = 1; j < size; j++)
if(i == j)
temp[(i-1)*size + j-1] = (matrix[i*size + j] - 1) / s[i];
else
temp[(i-1)*size + j-1] = matrix[i*size + j] / s[i];
double deltaS = determinat(temp, temp_size); // delta of system
for(unsigned i = 0; i < temp_size; i++){ // delta of vars
swap(temp, x0_coef, i, temp_size);
x[i+1] = determinat(temp, temp_size) / deltaS;
swap(temp, x0_coef, i, temp_size);
}
delete[] x0_coef; // place where error occures
delete[] temp;
return x;
}
But same thing happens if I switch delete[] x0_coef; with delete[] temp;, error occurs on temp;
As you can see in code I'm not using char, ie. making String so adding '\0' is useless because 0 is still valid value.
But now interesting part, I've tested swap function with this code:
#include <iostream>
using namespace std;
void swap(double* a, double* b, unsigned size){
double temp = 0;
for(unsigned i=0; i < size; i++){
temp = a[i];
a[i] = b[i];
b[i] = temp;
}
}
void main(){
double *a = new double[5],
*b = new double[5];
for(unsigned i=0; i < 5; i++){
a[i] = i;
b[i] = i*i;
}
swap(a, b, 5);
for(unsigned i=0; i < 5; i++)
std::cout << "a: " << a[i] << " b: " << b[i] << endl;
delete[] a;
delete[] b;
system("PAUSE");
}
And everything worked.
To be honest I'm at end of my wits, just spent 2-3 days trying to find out what is that I'm missing. But most of other topics are related on making char array, String, and general miss calculation of arrays length. And as is it shown in code I always carry arrays length to other functions.
I'm sure that there are better codes to do what I have to do, but this is solo-required project so I'm not looking in better functionality just to help me see what I'm doing wrong with arrays.
Your code corrupts memory when it writes into an out-of-bounds index of array temp. And when the heap is corrupted, anything can happen (like a crash on delete[] call).
Your temp array contains (size-1)*(size-1) items, while it is treated it as a size*(size-1) array inside the double loop: temp[(i-1)*size + j-1] = ... (because you multiply "the first index" by size).
I guess replacing it with temp[(i-1)*temp_size + j-1] will solve the problem.