SHARE
TWEET

Untitled

a guest Feb 19th, 2019 61 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var exist = function(board, word) {
  2.     var seen = [];
  3.     var targetCharIdx = 0;
  4.     var result = {
  5.         found: false
  6.     };
  7.     existHelper(board, word, seen, result);
  8.     return result.found;
  9. };
  10.  
  11. var existHelper = function(board, word, seen, result) {
  12.  
  13.     if (word.length === seen.length) {
  14.         if (wordMatches(word, seen, board)) {
  15.             if (cellsAreUnique(seen)) {
  16.                 if (cellsAreAdjacent(seen)) {
  17.                     result.found = true;
  18.                 }
  19.             }
  20.         }
  21.     } else {
  22.         for (var i = 0; i < board.length; i++) {
  23.             for (var j = 0; j < board[0].length; j++) {
  24.                 seen.push([i, j])
  25.                 existHelper(board, word, seen, result)
  26.                 seen.pop();
  27.             }
  28.         }
  29.     }
  30. };
  31.  
  32. var cellsAreAdjacent = function(seen) {
  33.     var i = 0;
  34.     var j = 1;
  35.     var cellOne;
  36.     var cellTwo;
  37.  
  38.     while (j < seen.length) {
  39.         cellOne = seen[i];
  40.         cellTwo = seen[j];
  41.         var diffOne = Math.abs(cellOne[0] - cellTwo[0]);
  42.         var diffTwo = Math.abs(cellOne[1] - cellTwo[1]);
  43.         if (!xor(diffOne === 1, diffTwo === 1)) {
  44.             return false;
  45.         }
  46.         j += 1;
  47.         i += 1;
  48.     }
  49.     return true;
  50. };
  51.  
  52. var xor = function(option1, option2) {
  53.     return ((option1 || option2) && !(option1 && option2));
  54. };
  55.  
  56. var cellsAreUnique = function(seen) {
  57.     var usedCoordinates = {};
  58.     var lookup = '';
  59.  
  60.     for (var i = 0; i < seen.length; i++) {
  61.         lookup = seen[i][0].toString() + seen[i][1].toString();
  62.  
  63.         if (usedCoordinates[lookup]) {
  64.             return false;
  65.         }
  66.         usedCoordinates[lookup] = true;
  67.  
  68.     }
  69.     return true;
  70. };
  71.  
  72. var wordMatches = function(word, seen, board) {
  73.     var constructedWord = '';
  74.  
  75.     seen.forEach(function(coordinate) {
  76.         constructedWord += board[coordinate[0]][coordinate[1]];
  77.  
  78.     });
  79.  
  80.     return constructedWord === word;
  81. };
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top