Skip to content

Instantly share code, notes, and snippets.

@YanLobat
Last active February 10, 2018 20:03
Show Gist options
  • Save YanLobat/90b3a8a027b99ab975b43e7e1a2e8324 to your computer and use it in GitHub Desktop.
Save YanLobat/90b3a8a027b99ab975b43e7e1a2e8324 to your computer and use it in GitHub Desktop.
function checkWord( board, word ) {
const graph = board.map((row, rowNumber) => {
return row.map((letter, position) => {
return {
name: letter,
neighbours: getNeighbours(rowNumber, position, board),
index: rowNumber * board.length + position
};
});
});
let res = false;
for (let i = 0; i < graph.length; i++) {
for (let j = 0; j < graph[i].length; j++) {
if (graph[i][j].name === word[0]) {
if (word[1] === undefined) {
res = true;
break;
}
res = searchNext(word, 1, graph[i][j], graph, [graph[i][j]['index']]);
if (res) {
break;
}
}
}
}
return res;
}
function searchNext(word, index, point, graph, been) {
let status = false;
const candidates = checkNeighbours(point, word[index], graph, been);
candidates.forEach(candidate => {
if (status) {
return;
}
if (index === word.length - 1) {
if (candidate.name === word[index]) {
status = true;
}
} else {
const beenCopy = been.map(el => el);
beenCopy.push(candidate.index);
if (searchNext(word, index +1, candidate, graph, beenCopy)) {
status = true;
}
}
});
return status;
}
function checkNeighbours(point, letter, graph, been) {
let row;
let index;
return point.neighbours
.filter(globalIndex => {
row = Math.floor(globalIndex/graph.length);
index = globalIndex % graph.length;
if ((letter === graph[row][index]['name']) && (!been.includes(globalIndex))) {
return true;
}
})
.map(globalIndex => {
row = Math.floor(globalIndex/graph.length);
index = globalIndex % graph.length;
return graph[row][index];
});
}
function getNeighbours(row, index, board) {
const neighbours = [];
for (let i = row-1; i <= row+1; i++) {
if (board[i] === undefined) {
continue;
}
for (let j = index-1; j <= index+1; j++) {
if ((i === row) && (j === index)) j++;
if (board[i][j] !== undefined) {
neighbours.push(i*board.length+j);
}
}
}
return neighbours;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment