-
Notifications
You must be signed in to change notification settings - Fork 1
/
CellularAutomataAlgorithm.cs
106 lines (89 loc) · 2.65 KB
/
CellularAutomataAlgorithm.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Diagnostics;
namespace grain_growth
{
public class CellularAutomataAlgorithm : AlgorithmBase
{
/// <summary>
/// Add grains in random positions
/// </summary>
public void AddRandomGrains(int number)
{
int[] notUsedIds = this.GetNotUsedIds();
for (int i = 0; i < number; ++i)
{
if (i < notUsedIds.Length)
{
Cell c;
// Look for empty cell
do
{
c = this.grid.GetCell(RandomHelper.Next(this.Width), RandomHelper.Next(this.Height));
} while (c.ID != 0 || c.Selected);
c.ID = notUsedIds[i];
}
else
{
// No more id
break;
}
}
}
/// <summary>
/// Step of growth
/// </summary>
/// <returns>true if any changes made</returns>
public bool Step()
{
int changes = 0;
this.grid.ResetCurrentCellPosition();
// Iterate cells line by line
do
{
// Grain can grwoth only on empty cell
if (this.grid.CurrentCell.ID == 0)
{
if (this.Moore(this.grid.CurrentCell))
{
++changes;
}
}
} while (this.grid.Next());
if (changes > 0)
{
// Copy values
this.grid.CopyNewIDtoID();
return true;
}
return false;
}
/// <summary>
/// Change current cell with Moore rules
/// </summary>
/// <returns></returns>
protected bool Moore(Cell c)
{
CounterReturn cr = this.MooreMostCommonCell(c);
if (cr != null)
{
this.grid.CurrentCell.NewID = cr.ID;
return true;
}
return false;
}
/// <summary>
/// Look for most common cell of current cell Moore neighborhood
/// </summary>
/// <returns>Most common cell with count or null</returns>
protected CounterReturn MooreMostCommonCell(Cell c)
{
Counter counter = new Counter();
counter.AddCells(c.MoorNeighborhood);
return counter.MostCommonID;
}
}
}