So I'm trying to build the game of life program and I am fairly fresh to java/coding in general and I am having issues wrapping my head around wrap around in 2D arrays. I have a constructor and methods that will build me an array and place "cells" where I want them but I dont understand how I can see how many neighbors a cell has.
To sum it up:
I can make a 2D array of whatever type.
I can place "cells" at different elements in the array
Now how do I see is the spaces next to my cell being checked has neighbors on all side( I use a nested for loop to go through each cell)?
KEEP IN MIND! Wrap around is in effect here.
UPDATE: This is what I have but when I test it it returns 1 less neighbor than there should be. UPDATE 2: I removed the first if statement because I don't think it makes sense with it. But now I cant get c to go up 1.
public int neighborCount(int row, int col) {
int count = 0;
for (int r = 0; r < society.length; r++) {
for (int c = 0; c < society[0].length; c++) {
// up and left
if ((society[(r - 1 + row) % row][(c - 1 + col) % col]) == cell) {
count++;
}
// up
if ((society[(r - 1 + row) % row][c]) == cell) {
count++;
}
// up and right
if ((society[(r - 1 + row) % row][(c + 1 + col) % col]) == cell) {
count++;
}
// left
if ((society[r][(c - 1 + col) % col]) == cell) {
count++;
}
// right
if ((society[r][(c + 1 + col) % col]) == cell) {
count++;
}
// down and left
if ((society[(r + 1 + row) % row][(c - 1 + col) % col]) == cell) {
count++;
}
// down
if ((society[(r + 1 + row) % row][c]) == cell) {
count++;
}
// down and right
if ((society[(r + 1 + row) % row][(c + 1 + col) % col]) == cell) {
count++;
}
}
}
return count;
}
My test:
@Test
public void testNeighborsWrapping() {
GameOfLife society = new GameOfLife(10, 16);
society.growCellAt(3, 3);
society.growCellAt(3, 4);
society.growCellAt(3, 5);
assertEquals(0, society.neighborCount(2, 1));
assertEquals(1, society.neighborCount(2, 2));
assertEquals(2, society.neighborCount(2, 3));
assertEquals(3, society.neighborCount(2, 4));
}
}