-
Notifications
You must be signed in to change notification settings - Fork 0
/
wordBoggle.js
82 lines (67 loc) · 2.31 KB
/
wordBoggle.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
function wordBoggle(board, words) {
let foundWords = new Set();
for (let word of words) {
const startingLetters = init(word);
if (startingLetters.length > 0) {
for (let startingLetter of startingLetters) {
const string = scan(startingLetter, word);
// console.log("String: ", string);
if (string === word) {
foundWords.add(word);
break;
}
}
}
}
return [...foundWords].sort((a, b) => a.localeCompare(b));
function init(word) {
let startingLetters = [], letter = word[0];
for (let row in board) {
for (let char in board[row]) {
if (board[row][char] === letter) {
startingLetters.push([row, char])
}
}
}
return startingLetters;
}
function scan(startingLetter, word) {
startingLetter[0] = parseInt(startingLetter[0]);
startingLetter[1] = parseInt(startingLetter[1]);
let i = 1,
string = word[0],
checked = [startingLetter],
boardClone = board.map((row) => row.slice()),
area = [startingLetter[0] - 1, startingLetter[0] + 2, startingLetter[1] - 1, startingLetter[1] + 2];
boardClone[startingLetter[0]][startingLetter[1]] = "--";
while (checked.length > 0 && checked.length < word.length) {
i = parseInt(i);
let found = false;
rowLoop:
for (let n = area[0]; n < area[1]; n++) {
for (let x = area[2]; x < area[3]; x++) {
if (word[i] && boardClone[n] && boardClone[n][x] && boardClone[n][x].toLowerCase() === word[i].toLowerCase()) {
boardClone[n][x] = "--";
checked.push([n, x]);
area = [n - 1, n + 2, x - 1, x + 2];
string += word[i];
found = true;
i++;
break rowLoop;
}
}
}
if (!found) {
checked.pop();
string = string.substring(0, string.length - 1);
if (checked[checked.length - 1]) {
const c = checked[checked.length - 1];
area = [c[0] - 1, c[0] + 2, c[1] - 1, c[1] + 2];
i--;
}
}
// console.log(checked);
}
return string;
}
}