Created
May 7, 2012 20:52
-
-
Save kiwidev/2630345 to your computer and use it in GitHub Desktop.
One line game of life
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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