Skip to content

Instantly share code, notes, and snippets.

@remi-bruguier
Created June 7, 2020 18:08
Show Gist options
  • Save remi-bruguier/18d9eb6ce2811247f0d82304644c9128 to your computer and use it in GitHub Desktop.
Save remi-bruguier/18d9eb6ce2811247f0d82304644c9128 to your computer and use it in GitHub Desktop.
You are given a 2D array of characters, and a target string. Return whether or not the target word exists in the matrix. Unlike a standard word search, the word must be either going left-to-right, or top-to-bottom in the matrix.
const word_search = (arr:string[][], word: string) : boolean => {
if(word.length > arr.length) return false;
let horizontal = '';
let vertical:{ [key: string]: string } = {};
for(let i=0; i<arr.length;i++){
for(let j=0; j<arr[i].length;j++){
horizontal+= arr[i][j];
if(!vertical[j]) vertical[j] = '';
vertical[j] += arr[i][j];
}
}
return horizontal.includes(word) || Object.values(vertical).join().includes(word);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment