Skip to content

Instantly share code, notes, and snippets.

@kiwidev
Created May 7, 2012 20:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kiwidev/2630345 to your computer and use it in GitHub Desktop.
Save kiwidev/2630345 to your computer and use it in GitHub Desktop.
One line game of life
[TestMethod]
public void OneLiner()
{
Func<bool[], int, bool[]> gameOfLife =
(cells, width) =>
cells.Select((cell, index) =>
// Neighbours
new
{
IsAlive = cell,
AliveNeighbours =
(from dx in new[] { -1, 0, 1}
from dy in new[] { -1, 0, 1}
where !(dx == 0 && dy == 0)
select new { X = index % width + dx, Y = index / width + dy}
).Where(n => n.X >= 0 && n.Y >= 0 && n.X < width && n.Y < cells.Length/width)
.Count(n => cells[n.Y*width + n.X])
})
// Gameloop
.Select(cell => (cell.AliveNeighbours == 3) || (cell.IsAlive && cell.AliveNeighbours == 2))
.ToArray();
var newboard = gameOfLife(new[] {false, false, false, true, true, true, false, false, false}, 3);
CollectionAssert.AreEqual(new[] { false, true, false, false, true, false, false, true, false}, newboard);
newboard = gameOfLife(newboard, 3);
CollectionAssert.AreEqual(new[] {false, false, false, true, true, true, false, false, false}, newboard);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment