Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class ConwayLife
- {
- /* Please note that the htmlize function for C# currently isn't working
- properly. I tested it on rextester.com and the code worked as expected,
- but for some reason on codewars it isn't. When I find a solution to
- the issue I will update the function. */
- public static int[,] GetGeneration(int[,] cells, int generation)
- {
- for (int i = 0; i < generation; i++)
- {
- cells = progressConwayLife(enlargeCanvas(cells));
- cells = adjustframe(cells);
- }
- return cells;
- }
- private static int[,] enlargeCanvas(int[,] cells)
- {
- int[,] frame = new int[cells.GetUpperBound(0) + 3, cells.GetUpperBound(1) + 3];
- for (int i = 0; i <= cells.GetUpperBound(0); i++)
- {
- for (int j = 0; j <= cells.GetUpperBound(1); j++)
- {
- frame[i + 1, j + 1] = cells[i, j];
- }
- }
- return frame;
- }
- private static int[,] adjustframe(int[,] cells)
- {
- int firstHorizontal = 0;
- int firstVertical = cells.GetUpperBound(1);
- bool firstSet = false;
- for (int i = 0; i <= cells.GetUpperBound(0); i++)
- {
- for (int j = 0; j <= cells.GetUpperBound(1); j++)
- {
- if (cells[i, j] > 0)
- {
- if (!firstSet)
- firstHorizontal = i;
- firstSet = true;
- if (j < firstVertical)
- {
- firstVertical = j;
- }
- }
- }
- }
- if(!firstSet)
- return new int[0,0];
- firstSet = false;
- int lastHorizontal = cells.GetUpperBound(0);
- int lastVertical = 0;
- for (int i = cells.GetUpperBound(0); i >= 0; i--)
- {
- for (int j = cells.GetUpperBound(1); j >= 0; j--)
- {
- if (cells[i, j] > 0)
- {
- if (!firstSet)
- lastHorizontal = i;
- firstSet = true;
- if (j > lastVertical)
- lastVertical = j;
- }
- }
- }
- int[,] frame = new int[(lastHorizontal - firstHorizontal)+1, (lastVertical - firstVertical)+1];
- for (int i = firstHorizontal; i <= lastHorizontal; i++)
- {
- for (int j = firstVertical; j <= lastVertical; j++)
- {
- frame[i-firstHorizontal, j-firstVertical] = cells[i, j];
- }
- }
- return frame;
- }
- private static int[,] progressConwayLife(int[,] cells)
- {
- int[,] result = new int[cells.GetUpperBound(0)+1, cells.GetUpperBound(1)+1];
- for (int i = 0; i <= cells.GetUpperBound(0); i++)
- {
- for (int j = 0; j <= cells.GetUpperBound(1); j++)
- {
- result[i, j] = getNewAlive(cells, i, j);
- }
- }
- return result;
- }
- private static int getNewAlive(int[,] cells, int k, int l)
- {
- int value = 0;
- for (int i = -1; i < 2; i++)
- {
- for (int j = -1; j < 2; j++)
- {
- if (!(i == 0 && j == 0))
- {
- if (i + k >= 0 && l + j >= 0 && i+k <= cells.GetUpperBound(0) && l+j <= cells.GetUpperBound(1))
- {
- value += cells[i + k, j + l];
- }
- }
- }
- }
- if (value < 2 || value > 3)
- return 0;
- else if ((cells[k, l] != 0) || (cells[k,l] == 0 && value == 3))
- return 1;
- else
- return 0;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement