Initial commit
This commit is contained in:
@@ -0,0 +1,56 @@
|
||||
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<Cell, short>[] GetNeighborField(IEnumerable<Cell> world)
|
||||
{
|
||||
var neighbors = new List<Cell>();
|
||||
|
||||
Parallel.ForEach(
|
||||
world,
|
||||
() => new List<Cell>(),
|
||||
(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<Cell, short>[] GetNeighborField_Serial(IEnumerable<Cell> world)
|
||||
{
|
||||
var neighborCount = new Dictionary<Cell, short>();
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user