-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGameOfLife.cs
74 lines (62 loc) · 1.91 KB
/
GameOfLife.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using System;
using System.Linq;
namespace GameOfLife;
public class GameOfLife
{
private int width;
private int height;
private string[] rows;
private string[] output;
public string Process(string input)
{
rows = input.Split("\n", StringSplitOptions.RemoveEmptyEntries);
output = rows.ToArray();
width = rows[0].Length;
height = rows.Length;
for (var x = 0; x < width; x++)
for (var y = 0; y < height; y++)
{
var aliveNeighbors = CountAliveNeighbors(x, y);
if (IsAlive(x, y) && aliveNeighbors is < 2 or > 3)
Kill(x, y);
else if (aliveNeighbors == 3)
Revive(x, y);
}
return string.Join('\n', output) + "\n";
}
private bool IsAlive(int x, int y) =>
rows[y][x] == '*';
private void Revive(int x, int y) =>
output[y] = output[y].Remove(x, 1).Insert(x, "*");
private void Kill(int x, int y) =>
output[y] = output[y].Remove(x, 1).Insert(x, ".");
private int CountAliveNeighbors(int x, int y)
{
var aliveNeighbors = 0;
if (IsCellAlive(x - 1, y - 1))
aliveNeighbors++;
if (IsCellAlive(x, y - 1))
aliveNeighbors++;
if (IsCellAlive(x + 1, y - 1))
aliveNeighbors++;
if (IsCellAlive(x - 1, y))
aliveNeighbors++;
if (IsCellAlive(x + 1, y))
aliveNeighbors++;
if (IsCellAlive(x - 1, y + 1))
aliveNeighbors++;
if (IsCellAlive(x, y + 1))
aliveNeighbors++;
if (IsCellAlive(x + 1, y + 1))
aliveNeighbors++;
return aliveNeighbors;
}
private bool IsCellAlive(int x, int y)
{
if (x < 0) return false;
if (x >= width) return false;
if (y < 0) return false;
if (y >= height) return false;
return rows[y][x] == '*';
}
}