Dictionary <Coord, bool> RunSimulation(Dictionary <Coord, bool> cubes, int dimensions) { var result = new Dictionary <Coord, bool>(cubes); var minW = cubes.Keys.Min(c => c.W) - 1; var maxW = cubes.Keys.Max(c => c.W) + 1; var minZ = cubes.Keys.Min(c => c.Z) - 1; var maxZ = cubes.Keys.Max(c => c.Z) + 1; var minY = cubes.Keys.Min(c => c.Y) - 1; var maxY = cubes.Keys.Max(c => c.Y) + 1; var minX = cubes.Keys.Min(c => c.X) - 1; var maxX = cubes.Keys.Max(c => c.X) + 1; if (dimensions == 3) { minW = maxW = 0; } for (var w = minW; w <= maxW; w++) { for (var z = minZ; z <= maxZ; z++) { for (var y = minY; y <= maxY; y++) { for (var x = minX; x <= maxX; x++) { var currentCube = new Coord(x, y, z, w); var isActive = cubes.TryGetValue(currentCube, out var active) && active; var activeNeighbours = currentCube.Adjacent(dimensions).Count(c => cubes.TryGetValue(c, out var ac) && ac); if (isActive && activeNeighbours != 2 && activeNeighbours != 3) { result[currentCube] = false; continue; } if (!isActive && activeNeighbours == 3) { result[currentCube] = true; } } } } } return(result); }