Skip to content

Commit c0f32ef

Browse files
authored
Create 2018-check-if-word-can-be-placed-in-crossword.js
1 parent 9f9fb42 commit c0f32ef

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
/**
2+
* @param {character[][]} board
3+
* @param {string} word
4+
* @return {boolean}
5+
*/
6+
const placeWordInCrossword = function(board, word) {
7+
for (let state of [board, getRotated(board)])
8+
for (let chars of state)
9+
for (let token of chars.join('').split("#"))
10+
for (let letters of [word, word.split('').reverse().join('')])
11+
if (letters.length == token.length)
12+
if (canFit(letters, token))
13+
return true;
14+
return false;
15+
}
16+
17+
function getRotated(board) {
18+
const m = board.length;
19+
const n = board[0].length;
20+
21+
const rotated = Array.from({length: n}, () => Array(m));
22+
for (let i = 0; i < m; ++i)
23+
for (let j = 0; j < n; ++j)
24+
rotated[j][i] = board[i][j];
25+
return rotated;
26+
}
27+
28+
function canFit(letters, token) {
29+
for (let i = 0; i < letters.length; ++i)
30+
if (token.charAt(i) != ' ' && token.charAt(i) != letters.charAt(i))
31+
return false;
32+
return true;
33+
}

0 commit comments

Comments
 (0)