Skip to content

Instantly share code, notes, and snippets.

@sylvainpolletvillard
Created March 5, 2020 12:18
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 sylvainpolletvillard/e687ab8087e68a0e28a69a037977ccec to your computer and use it in GitHub Desktop.
Save sylvainpolletvillard/e687ab8087e68a0e28a69a037977ccec to your computer and use it in GitHub Desktop.
quick langton ant
const parseGrid = ([str]) => str
.split('\n')
.map(row => row.trim())
.filter(row => row.length > 0)
.map(row => row.split('').map(char => char !== '.'))
const formatGrid = (rows, ant) => rows
.map((row, y) => row.map((cell, x) => {
if (ant.x === x && ant.y === y) {
return '8'
}
return cell ? '#' : '.'
}).join(''))
.join('\n')
const calcNextGridState = (grid, ant) => {
const antCell = grid[ant.y][ant.x];
if (antCell) {
// case blanche
ant.dir = (ant.dir + 3) % 4
} else {
// case noire
ant.dir = (ant.dir + 1) % 4
}
switch (ant.dir) {
case directions.UP: ant.y -= 1; break;
case directions.RIGHT: ant.x += 1; break;
case directions.DOWN: ant.y += 1; break;
case directions.LEFT: ant.x -= 1; break;
}
if (ant.y in grid && ant.x in grid[ant.y]) {
grid[ant.y][ant.x] = !grid[ant.y][ant.x]
}
}
const directions = {
UP: 0,
RIGHT: 1,
DOWN: 2,
LEFT: 3
};
(function loop(grid, ant, t = 1) {
const out = formatGrid(grid, ant)
console.log(`Turn ${t}\n${out}`)
if (t < 100 && out.includes('#')) setTimeout(() => {
calcNextGridState(grid, ant)
loop(grid, ant, ++t)
}, 300)
})(parseGrid`
....................
....................
....................
.....#..............
....................
....................
....................
....................
....................
....................
`, {
x: 10,
y: 5,
dir: directions.UP
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment