Skip to content

Instantly share code, notes, and snippets.

@jonahwilliams
Created May 4, 2016 21:56
Show Gist options
  • Save jonahwilliams/a3cdef8fa6cbabfe664c02f31ebb8878 to your computer and use it in GitHub Desktop.
Save jonahwilliams/a3cdef8fa6cbabfe664c02f31ebb8878 to your computer and use it in GitHub Desktop.
the board problem
'use strict';
const example = [
['a', 'c', 'l', 'b'],
['r', 'e', 'b', 'u'],
['i', 'n', 'g', 's'],
['l', 'm', 'n', 'o']
];
console.log(contains(example, 'caring'));
//contains :: [[Char]] -> [Char] -> Bool
function contains(board, string) {
let xs = string;
let queue = initial(board, xs);
if (queue.length === 0) return false;
while (queue.length > 0) {
const item = queue.shift();
if (item[3].length === 0) {
console.log(item[2]);
return true
}
let ns = neighbor(board, item[0], item[1]).filter(d => {
return !item[2].has(`${d[0]}-${d[1]}`) && item[3][0] === board[d[0]][d[1]];
});
for (let i = 0; i < ns.length; i++) {
let newItem = [ns[i][0], ns[i][1], new Set([`${ns[i][0]}-${ns[i][1]}`, ...item[2]]), item[3].slice(1)];
queue.push(newItem);
}
}
return false;
}
// neighbor :: [[Char]] -> Int -> Int -> [[Int, Int]]
function neighbor(board, i, j) {
const res = [
[i - 1, j],
[i + 1, j],
[i, j - 1],
[i, j + 1],
[i - 1, j - 1],
[i + 1, j + 1],
[i - 1, j + 1],
[i + 1, j - i]
].filter(d => {
return d[0] > -1 && d[0] < board.length && d[1] > -1 && d[1] < board[0].length;
});
console.log(res);
return res;
}
// initial :: [[Char]] -> Char -> [[Int, Int]]
function initial(board, xs) {
const result = [];
for (let i = 0; i < board.length; i++) {
for (let j = 0; j < board[0].length; j++) {
if (board[i][j] === xs[0]) {
result.push([i, j, new Set([`${i}-${j}`]), xs.slice(1)]);
}
}
}
return result;
}
@jonahwilliams
Copy link
Author

output is

[ [ 1, 1 ], [ 0, 0 ], [ 0, 2 ], [ 1, 2 ], [ 1, 1 ] ]
[ [ 1, 0 ], [ 0, 1 ], [ 1, 1 ], [ 1, 0 ] ]
[ [ 0, 0 ], [ 2, 0 ], [ 1, 1 ], [ 2, 1 ], [ 0, 1 ] ]
[ [ 0, 0 ], [ 2, 0 ], [ 1, 1 ], [ 2, 1 ], [ 0, 1 ] ]
[ [ 1, 0 ], [ 3, 0 ], [ 2, 1 ], [ 3, 1 ], [ 1, 1 ] ]
[ [ 1, 0 ], [ 3, 0 ], [ 2, 1 ], [ 3, 1 ], [ 1, 1 ] ]
[ [ 1, 1 ],
  [ 3, 1 ],
  [ 2, 0 ],
  [ 2, 2 ],
  [ 1, 0 ],
  [ 3, 2 ],
  [ 1, 2 ] ]
[ [ 1, 1 ],
  [ 3, 1 ],
  [ 2, 0 ],
  [ 2, 2 ],
  [ 1, 0 ],
  [ 3, 2 ],
  [ 1, 2 ] ]
Set { '2-2', '2-1', '2-0', '1-0', '0-0', '0-1' }
true

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment