-
Notifications
You must be signed in to change notification settings - Fork 0
/
majority_vote.dart
47 lines (39 loc) · 1.6 KB
/
majority_vote.dart
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
/// Implementation of a Majority voting CA
library cellular_automata.rules.majority_vote;
import 'dart:math' as math;
import 'package:cellular_automata/src/rules/_ca_rules.dart';
import 'package:cellular_automata/cellular_automata.dart';
class MajorityVote extends CARules<bool> {
@override
CellGrid<bool> gridActivity(CellGrid grid) {
final o = new CellGrid<bool>(grid.width, grid.height, false);
// scan each cell in each row for a different neighbor to right
// then mark these two cells as active and the 4 directly above and below
for (int y = 0; y < grid.height; y++)
for (int x = 0; x < grid.width; x++)
if (grid.get(x, y) != grid.get(x + 1, y, wrap, defaultState))
o
..set(x, y, true, wrap)
..set(x + 1, y - 1, true, wrap)
..set(x, y, true, wrap)
..set(x + 1, y, true, wrap)
..set(x, y + 1, true, wrap)
..set(x + 1, y + 1, true, wrap);
return o;
}
@override
bool calculateState(int x, int y, CellGrid grid) {
// Distribution: {STATE, COUNT}
final Map<bool, int> distribution = {true: 0, false: 0};
final List<bool> neighborhood =
grid.getNeighborhood(x, y, wrap, defaultState);
for (int i = 0, l = neighborhood.length; i < l; i++)
distribution[neighborhood[i]]++;
// At the moment Majority Vote is type bool so we won't itterate
// in the future we may want to have have more than 2 states
if (distribution[false] == distribution[true])
return new math.Random().nextInt(2) == 1;
else
return (distribution[true] > distribution[false]);
}
}