using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using GameOfLife.Entities; namespace GameOfLife { public static class Neighborhood { public static Tuple[] GetNeighborField(IEnumerable world) { var neighbors = new List(); Parallel.ForEach( world, () => new List(), (cell, loop, localNeighbors) => { localNeighbors.AddRange(cell.NeighborCells); return localNeighbors; }, globalNeighbors => { lock(neighbors) neighbors.AddRange(globalNeighbors); }); var neighborCount = neighbors .GroupBy(n => n) .Select(n => Tuple.Create(n.Key, (short)n.Count())) .ToArray(); return neighborCount; } public static Tuple[] GetNeighborField_Serial(IEnumerable world) { var neighborCount = new Dictionary(); foreach (var cell in world) { foreach (var neighbor in cell.NeighborCells) { if (!neighborCount.ContainsKey(neighbor)) neighborCount[neighbor] = 1; else neighborCount[neighbor] += 1; } } return neighborCount.Select(pair => Tuple.Create(pair.Key, pair.Value)).ToArray(); } } }