Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
- }
Add Comment
Please, Sign In to add comment