-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsolution.js
99 lines (92 loc) · 2.21 KB
/
solution.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
"use strict";
function isValid(numRows, numColums, i, j) {
return i < numRows && j < numColums;
}
/**
*
* @param {string[][]} matrix
* @param {number} i
* @param {number} j
* @param {string} letter
*/
function matches(matrix, i, j, letter) {
const numRows = matrix.length;
const numColums = matrix[0].length;
return isValid(numRows, numColums, i, j) && matrix[i][j] === letter;
}
/**
*
* @param {string[][]} matrix
* @param {number} startI
* @param {number} startJ
* @param {string[]} letters
*/
function checkRow(matrix, startI, startJ, letters) {
let numMatches = 0;
let currentLetter = 0;
while (
currentLetter < letters.length &&
matches(
matrix,
startI + currentLetter,
startJ,
letters[currentLetter++]
)
) {
numMatches++;
}
return numMatches === letters.length;
}
/**
*
* @param {string[][]} matrix
* @param {number} startI
* @param {number} startJ
* @param {string[]} letters
*/
function checkColumn(matrix, startI, startJ, letters) {
let numMatches = 0;
let currentLetter = 0;
while (
currentLetter < letters.length &&
matches(
matrix,
startI,
startJ + currentLetter,
letters[currentLetter++]
)
) {
numMatches++;
}
return numMatches === letters.length;
}
/**
*
* @param {string[][]} matrix
* @param {string} text
*/
function hasText(matrix, text) {
const letters = text.split("");
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix.length; j++) {
if (
checkColumn(matrix, i, j, letters) ||
checkRow(matrix, i, j, letters)
)
return true;
}
}
return false;
}
const testMatrix = [
["F", "A", "C", "I"],
["O", "B", "Q", "P"],
["A", "N", "O", "B"],
["M", "A", "S", "S"]
];
console.log(hasText(testMatrix, "MASS")); // true
console.log(hasText(testMatrix, "ABNA")); // true
console.log(hasText(testMatrix, "CI")); // true
console.log(hasText(testMatrix, "ACJ")); // false
console.log(hasText(testMatrix, "PK")); // false
console.log(hasText(testMatrix, "ZI")); // false