Created
May 4, 2016 21:56
-
-
Save jonahwilliams/a3cdef8fa6cbabfe664c02f31ebb8878 to your computer and use it in GitHub Desktop.
the board problem
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
'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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
output is