Guest User

Untitled

a guest
Feb 23rd, 2018
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. function checkWord( board, word ) {
  2. const graph = board.map((row, rowNumber) => {
  3. return row.map((letter, position) => {
  4. return {
  5. name: letter,
  6. neighbours: getNeighbours(rowNumber, position, board),
  7. index: rowNumber * board.length + position
  8. };
  9. });
  10. });
  11. let res = false;
  12. for (let i = 0; i < graph.length; i++) {
  13. for (let j = 0; j < graph[i].length; j++) {
  14. if (graph[i][j].name === word[0]) {
  15. if (word[1] === undefined) {
  16. res = true;
  17. break;
  18. }
  19. res = searchNext(word, 1, graph[i][j], graph, [graph[i][j]['index']]);
  20. if (res) {
  21. break;
  22. }
  23. }
  24. }
  25. }
  26. return res;
  27. }
  28.  
  29. function searchNext(word, index, point, graph, been) {
  30. let status = false;
  31. const candidates = checkNeighbours(point, word[index], graph, been);
  32. candidates.forEach(candidate => {
  33. if (status) {
  34. return;
  35. }
  36. if (index === word.length - 1) {
  37. if (candidate.name === word[index]) {
  38. status = true;
  39. }
  40. } else {
  41. const beenCopy = been.map(el => el);
  42. beenCopy.push(candidate.index);
  43. if (searchNext(word, index +1, candidate, graph, beenCopy)) {
  44. status = true;
  45. }
  46. }
  47. });
  48. return status;
  49. }
  50.  
  51. function checkNeighbours(point, letter, graph, been) {
  52. let row;
  53. let index;
  54. return point.neighbours
  55. .filter(globalIndex => {
  56. row = Math.floor(globalIndex/graph.length);
  57. index = globalIndex % graph.length;
  58. if ((letter === graph[row][index]['name']) && (!been.includes(globalIndex))) {
  59. return true;
  60. }
  61. })
  62. .map(globalIndex => {
  63. row = Math.floor(globalIndex/graph.length);
  64. index = globalIndex % graph.length;
  65. return graph[row][index];
  66. });
  67. }
  68.  
  69. function getNeighbours(row, index, board) {
  70. const neighbours = [];
  71. for (let i = row-1; i <= row+1; i++) {
  72. if (board[i] === undefined) {
  73. continue;
  74. }
  75. for (let j = index-1; j <= index+1; j++) {
  76. if ((i === row) && (j === index)) j++;
  77. if (board[i][j] !== undefined) {
  78. neighbours.push(i*board.length+j);
  79. }
  80. }
  81. }
  82. return neighbours;
  83. }
Add Comment
Please, Sign In to add comment