Last active
December 8, 2017 13:30
-
-
Save mizchi/2050db7d8b5da9b5fd89ccb578992a65 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type point = (int, int); | |
type game_of_life = { | |
width: int, | |
height: int, | |
field: list(bool) | |
}; | |
let search_dirs: list(point) = | |
List.map((i) => List.map((j) => (i, j), [(-1), 0, 1]), [(-1), 0, 1]) | |
|> List.flatten | |
|> List.filter(((x, y)) => ! (x == 0 && y == 0)); | |
let hit_test: (game_of_life, int, int, int, int) => bool = | |
(state, x, y, dx, dy) => { | |
let {width, height} = state; | |
/* in range */ | |
if (x == 0 && dx == (-1)) { | |
false | |
} else if (x == width - 1 && dx == 1) { | |
false | |
} else if (y == 0 && dy == (-1)) { | |
false | |
} else if (y == height - 1 && dy == 1) { | |
false | |
} else { | |
List.nth(state.field, x + y * width) | |
} | |
}; | |
let count_hit: (game_of_life, int) => int = | |
(state, cur) => { | |
let {width, height} = state; | |
let x = cur mod width; | |
let y = cur / width; | |
search_dirs | |
|> List.map(((dx, dy)) => hit_test(state, x, y, dx, dy)) | |
|> List.filter((t) => t) | |
|> List.length | |
}; | |
let step: game_of_life => game_of_life = | |
(prev) => { | |
let next = | |
List.mapi( | |
(index, state) => { | |
let n = count_hit(prev, index); | |
if (state) { | |
2 <= n && n <= 3 | |
} else { | |
n == 3 | |
} | |
}, | |
prev.field | |
); | |
{...prev, field: next} | |
}; | |
let rec range = (i, j) => | |
if (i > j) { | |
[] | |
} else { | |
List.concat([[i], range(i + 1, j)]) | |
}; | |
let create_blank: (int, int) => game_of_life = | |
(w, h) => { | |
width: w, | |
height: h, | |
field: range(0, w * h) |> List.map((_i) => false) | |
}; | |
let randomize: game_of_life => game_of_life = | |
(state) => { | |
...state, | |
field: state.field |> List.map((i) => Random.int(2) == 0) | |
}; | |
let main = () => { | |
let initial = create_blank(3, 3) |> randomize; | |
let next = inital |> step |> step |> step; | |
let jsonArray = | |
next.field | |
|> List.map(Js.Boolean.to_js_boolean) | |
|> Array.of_list | |
|> Js.Json.booleanArray; | |
Js.log(jsonArray) | |
}; | |
main(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment