Skip to content

Instantly share code, notes, and snippets.

@stianeikeland
Last active April 14, 2020 22:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stianeikeland/2735aab3d25cf1027a4b0fe4b178d280 to your computer and use it in GitHub Desktop.
Save stianeikeland/2735aab3d25cf1027a4b0fe4b178d280 to your computer and use it in GitHub Desktop.
Conway Reason
type cell = (int, int);
module CellSet =
Set.Make({
type t = cell;
let compare = compare;
});
let neighbours = ((x, y): cell) =>
CellSet.of_list(
{
let offset = [(-1), 0, 1];
List.map(x1 => List.map(y1 => (x + x1, y + y1), offset), offset)
->List.flatten
->List.filter(cell => cell != (x, y), _);
},
);
let getCandidates = alive =>
CellSet.elements(alive)
->List.map(neighbours, _)
->List.fold_left(CellSet.union, CellSet.empty, _)
->CellSet.union(alive);
let lives = (aliveSet, c) => {
let isAlive = CellSet.mem(c, aliveSet);
let numNeighbours =
neighbours(c)->CellSet.inter(aliveSet, _)->CellSet.cardinal;
switch (isAlive, numNeighbours) {
| (true, 2) => true
| (_, 3) => true
| (_, _) => false
};
};
let nextGen = alive => CellSet.filter(lives(alive), getCandidates(alive));
// ###############################################################################################
// Util:
let printList = (name, lst) => Js.log2(name, Array.of_list(lst));
let printSet = (name, set) => printList(name, CellSet.elements(set));
let isSameSet = (a, b) => CellSet.diff(a, b) == CellSet.empty;
// Lifes:
let block = CellSet.of_list([(0, 0), (0, 1), (1, 0), (1, 1)]);
let tub = CellSet.of_list([((-1), 0), (0, (-1)), (0, 1), (1, 0)]);
let boat = CellSet.add(((-1), (-1)), tub);
let blinker1 = CellSet.of_list([(0, 0), (0, 1), (0, 2)]);
let blinker2 = CellSet.of_list([((-1), 1), (0, 1), (1, 1)]);
let glider =
CellSet.of_list([(0, (-1)), (1, 0), ((-1), 1), (0, 1), (1, 1)]);
printSet("glider1", glider);
printSet("glider2", glider->nextGen);
printSet("glider3", glider->nextGen->nextGen);
printSet("glider4", glider->nextGen->nextGen->nextGen);
printSet("glider5", glider->nextGen->nextGen->nextGen->nextGen);
// Tests:
assert(block == nextGen(block));
assert(isSameSet(tub, nextGen(tub)));
assert(isSameSet(boat, nextGen(boat)));
assert(isSameSet(nextGen(blinker1), blinker2));
assert(isSameSet(blinker1->nextGen->nextGen, blinker1));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment