Click to See Complete Forum and Search --> : [RESOLVED] 2D arrays help (involves copying elements)


evapisces
March 5th, 2008, 10:47 AM
Hello:
I am new to the forum. I am doing an assignment involving 2D arrays called the Game of Life. I have to create a 2D array that is initialized with specific values of 0 or 1. Then I have to check each element to determine if it will stay a zero or one, or if it will become a one (based on certain rules). After I determine this, I have to create a new array and store the results into it. I have already created this array. However, when I print the new array, it gives me the same configuration as the first array. I'm not sure what I'm doing wrong.

Here's the original array's initialization:

int life[12][12] = { {0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,1,0,1,0,1,0,0,0},
{0,0,0,1,0,1,0,1,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,1,0,1,0,1,0,0,0},
{0,0,0,1,0,1,0,1,0,0,0,0},
{0,1,1,1,1,1,1,1,1,1,1,0},
{0,0,0,0,1,1,1,1,0,0,0,0},
{0,0,0,0,1,0,1,0,1,0,0,0},
{0,0,0,1,0,1,0,1,0,0,0,0},
{0,0,0,0,1,0,1,0,1,0,0,0},
{0,0,0,0,0,0,0,0,0,0,0,0} };


Here's the code that I have so far:

void neighbors(const int array[][12])
{

int count = 0,
row,
col,
a,
b,
newLife[12][12] = {};

for (row = 1; row < 11; row++)
{
for (col = 1; col < 11; col++)
{
for (a = -1; a < 2; a++)
{
for (b = -1; b < 2; b++)
{
if (array[row + a][col + b] == 1)
count++;
}
}

if (array[row][col] == 1)
count--;

if (array[row][col] == 0 && count == 3)
newLife[row][col] == 1;
else if (count >= 4 || count == 1 || count == 0)
newLife[row][col] == 0;
else
newLife[row][col] == 1;

count = 0;
}
}

for (row = 0; row < 12; row++)
{
for (col = 0; col < 12; col++)
{
cout << setw(3) << newLife[row][col];

if (((col + 1) % 12) == 0)
cout << endl;
}
}

}

Please help because I can't see what I'm obviously doing wrong.
If you need more info, just let me know.

Thanks in advance :)

7stud
March 5th, 2008, 10:52 AM
No help until you put code tags around your code.

evapisces
March 5th, 2008, 03:10 PM
No help until you put code tags around your code.

Sorry about that. Code tags have been added. :)

potatoCode
March 5th, 2008, 05:18 PM
Hello evapisces,

It would help alot if you could comment just a little since you have many nests.
Just by looking at your code I think I may see the problem (not sure tho..)

row, col, a, b, these variables are declared but undefined. Yes you did defined them in for the loop which makes them local to the {}.
if (array[row + a][col + b] == 1)
count++; and the assignment operator is used before these variables were defined. The value of count will always be zero, or rather in your case, more likely undefined and you're basing your calculation on the variable 'count'. and if you compare this logic with the original array you'd get nothing but zeroes.

I think... not sure tho.