using array members

Jun 2, 2013 at 8:15pm
Hi.
i have the code below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int dynamicbinomial(int n, int k)
{
	int* b = new int[n,k];
	for(int i=0; i<= n; i++)
	{
		for(int j=0; j<= min(i,k); j++)
		{
			if(j==0 || j==i)
				b[i,j] = 1;
			else if(j==1 || j==i-1)
				b[i,j] = i;
			else
			        b[i,j] = b[i-1,j-1] + b[i-1,j];			
		}
	}
	return b[n,k];
}


it works correctly but in the last line:
 
b[i,j] = b[i-1,j-1] + b[i-1,j];


when it reaches that line it does like it:
b[i,j] = b[0,j-1] + b[1,j-1] + b[2,j-1] + b[3,j-1] + ... + b[i-1,j] ;

it shows the sum of all numbers in line (i-1) form 0 to j

if you enter 5 as n and 3 as k you must have a matrix as below:
1
2
3
4
5
6
1
1  1
1  2  1
1  3  3  
1  4  6  
1  5  10 


but it makes a matrix like it:
1
2
3
4
5
6
1
1  1
1  2  1
1  3  3  
1  4  7
1  5  12


traced it this way:

1- i= 0 j= 0 k= 3 min( i,k )= 0 b[i,j]= b[0,0]= 1
2- i= 1 j= 0 k= 3 min( i,k )= 1 b[i,j]= b[1,0]= 1

3- i= 1 j= 1 k= 3 min( i,k )= 1 b[i,j]= b[1,1]= 1

4- i= 2 j= 0 k= 3 min( i,k )= 2 b[i,j]= b[2,0]= 1

5- i= 2 j= 1 k= 3 min( i,k )= 2 b[i,j]= b[2,1]= 2

6- i= 2 j= 2 k= 3 min( i,k )= 2 b[i,j]= b[2,2]= 1

7- i= 3 j= 0 k= 3 min( i,k )= 3 b[i,j]= b[3,0]= 1

8- i= 3 j= 1 k= 3 min( i,k )= 3 b[i,j]= b[3,1]= 3

9- i= 3 j= 2 k= 3 min( i,k )= 3 b[i,j]= b[3,2]= 3

10- i= 3 j= 3 k= 3 min( i,k )= 3 b[i,j]= b[3,3]= 1

11- i= 4 j= 0 k= 3 min( i,k )= 3 b[i,j]= b[4,0]= 1

12- i= 4 j= 1 k= 3 min( i,k )= 3 b[i,j]= b[4,1]= 4

13- i= 4 j= 2 k= 3 min( i,k )= 3 b[i,j]= b[4,2]= 7

14- i= 4 j= 3 k= 3 min( i,k )= 3 b[i,j]= b[4,3]= 4

15- i= 5 j= 0 k= 3 min( i,k )= 3 b[i,j]= b[5,0]= 1

16- i= 5 j= 1 k= 3 min( i,k )= 3 b[i,j]= b[5,1]= 5

17- i= 5 j= 2 k= 3 min( i,k )= 3 b[i,j]= b[5,2]= 12

see line 13 ?
Jun 3, 2013 at 12:43pm
In line 3 is it a C++ bidimensional array of int? Please read here http://www.cplusplus.com/doc/tutorial/arrays/

A dynamic 2D array is basically an array of pointers to arrays. You should initialize it using a loop:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
int **dynamicArray, ROWS,  COLUMNS ;

// input: ROWS and COLUMNS 
...............................................
// memory allocated for elements of rows.
dynamicArray = new int *[ROWS] ;

// memory allocated for  elements of each column.
for( int i = 0 ; i < ROWS ; i++ )
dynamicArray[i] = new int[COLUMNS];

.....................code...................

// at end free the allocated memory
for( int i = 0 ; i < ROWS ; i++ )
delete [] dynamicArray[i] ;
delete [] dynamicArray ;
Last edited on Jun 4, 2013 at 12:59am
Jun 3, 2013 at 12:59pm
See also the comma operator
http://www.cplusplus.com/doc/tutorial/operators/

The result of (n,k) is just k.
Jun 5, 2013 at 8:27am
i solved it this way:

int **b = new int*[n];
for(int i = 0; i < n; ++i) {
b[i] = new int[k];
}

then used the array this way:

b[i][j];

it worked.

thank you,
Jun 5, 2013 at 10:30am
ok mrm40, you're welcome!
Topic archived. No new replies allowed.