JSFiddle - React, Tailwind, and code Playground
by asemahle
JavaScript
var timeout = (new Date()).setTime((new Date()).getTime() + 5000);
let rules = {
3: { x: 5, y: 2 },
6: { x: 0, y: 4 },
10: { x: 5, y: 1 },
18: { x: 1, y: 3 },
27: { x: 5, y: 0 }
}
let map = [];
for (let i=0; i<5; i++) {
map.push([]);
for (let j=0; j<6; j++) {
map[i].push(false);
}
}
function findPaths(x, y, map, rules, turn) {
if (new Date() > timeout) {
console.log('TIMED OUT');
return false;
}
let mapCopy = [];
let numEmpty = 0;
for (let row of map) {
let rowCopy = [];
for (let cell of row) {
rowCopy.push(cell);
if (!cell) numEmpty++;
}
mapCopy.push(rowCopy);
}
if (numEmpty == 1) return [[{x: x, y: y}]];
map = mapCopy;
map[y][x] = true; //mark that we have been to this spot
let moves = [
{ x: x+1, y: y+2 },
{ x: x+1, y: y-2 },
{ x: x-1, y: y+2 },
{ x: x-1, y: y-2 },
{ x: x+2, y: y+1 },
{ x: x+2, y: y-1 },
{ x: x-2, y: y+1 },
{ x: x-2, y: y-1 }
];
let paths = [];
let r = rules[turn+1];
let madeMove = false;
for (let m of moves) {
if (m.x >= 0 && m.x < 6 && m.y >= 0 && m.y < 5 && // move is in bounds
(!r || (r.x == m.x && r.y == m.y)) && // move matches the "rule" for this turn
!map[m.y][m.x] // move is not a spot we have already been
){
newPaths = findPaths(m.x, m.y, map, rules, turn + 1);
if (newPaths) {
paths = paths.concat(newPaths);
madeMove = true;
}
}
}
if (madeMove) {
for (let path of paths) {
path.push({x: x, y: y });
}
return paths;
}
return false;
}
let sol = findPaths(0, 0, map, rules, 0);
console.log(sol);