var isWordOnTheBoard = function(board, word) {
var passedTest = true;
var previousLetterCoordinates;
//written as a loop; rewrite to use recursion
for (let letter of word) {
// console.log('current letter is ' + letter);
var letterCoordinates = getCoordinatesOnTheBoard(board, letter);
if(!letterCoordinates){
passedTest = false;
console.log('letter ' + letter + ' is not on the board');
break;
}
if(previousLetterCoordinates && !areNeighbors(previousLetterCoordinates, letterCoordinates)){
passedTest = false;
console.log('letter ' + letter + ' is not a neighbor to the previous letter');
break;
}
previousLetterCoordinates = letterCoordinates;
}
return passedTest;
};
//assumes letters on the board are unique with no repeated letters
var getCoordinatesOnTheBoard = function(board, letter) {
//undefined means letter is not on the board
var coordinates;
var firstRowIndex = board[0].indexOf(letter);
if(firstRowIndex >= 0){
coordinates = {
row: 0,
column: firstRowIndex
};
}
var secondRowIndex = board[1].indexOf(letter);
if(secondRowIndex >= 0){
coordinates = {
row: 1,
column: secondRowIndex
};
}
return coordinates;
}
//neighbors of a:
// | NW | N | NE |
// | W | a | E |
// | SW | S | SE |
// where NW is North West, N is North, NE is North East and so on
var areNeighbors = function(a, b) {
var nw_of_a = {
row: a.row - 1,
column: a.column - 1
}
if (JSON.stringify(b) === JSON.stringify(nw_of_a)){return true}
var n_of_a = {
row: a.row - 1,
column: a.column
}
if (JSON.stringify(b) === JSON.stringify(n_of_a)){return true}
var ne_of_a = {
row: a.row - 1,
column: a.column + 1
}
if (JSON.stringify(b) === JSON.stringify(ne_of_a)){return true}
var e_of_a = {
row: a.row,
column: a.column + 1
}
if (JSON.stringify(b) === JSON.stringify(e_of_a)){return true}
var se_of_a = {
row: a.row + 1,
column: a.column + 1
}
if (JSON.stringify(b) === JSON.stringify(se_of_a)){return true}
var s_of_a = {
row: a.row + 1,
column: a.column
}
if (JSON.stringify(b) === JSON.stringify(s_of_a)){return true}
var sw_of_a = {
row: a.row + 1,
column: a.column - 1
}
if (JSON.stringify(b) === JSON.stringify(sw_of_a)){return true}
var w_of_a = {
row: a.row,
column: a.column - 1
}
if (JSON.stringify(b) === JSON.stringify(w_of_a)){return true}
return false;
}
var omraw_nlet = [
['O','M','R','A','W'],
['N','L','E','T']
];
var watermelon = ['W', 'A', 'T', 'E', 'R', 'M', 'E', 'L', 'O', 'N'];
var lemon = ['L', 'E', 'M', 'O', 'N'];
console.log(isWordOnTheBoard(omraw_nlet, watermelon)); //true
console.log(isWordOnTheBoard(omraw_nlet, ['W', 'A', 'R'])); //true
console.log(isWordOnTheBoard(omraw_nlet, lemon)); //true
console.log(isWordOnTheBoard(omraw_nlet, lemon.concat(['S']))); //false
console.log(isWordOnTheBoard(omraw_nlet, ['T', 'E', 'N'])); //false