I have a matrix of characters arranged in such a way that they form meaningful words. Additionally, I also have an array of words with their respective starting and ending positions on the matrix. My goal is to extract an array of strings by combining all the characters at the specified positions. Below is the code snippet:
function findWords(words, matrix) {
const foundWords = [];
for (let i = 0; i < words.length; i++) {
const word = words[i].word;
const startX = words[i].startX;
const startY = words[i].startY;
const endX = words[i].endX;
const endY = words[i].endY;
let wordIndex = 0;
let wordFound = true;
// Horizontal Check
if (startX === endX) {
if (startY > endY) {
for (let y = endY; y <= startY; y++) {
if (matrix[startX][y] !== word[wordIndex]) {
wordFound = false;
break;
}
wordIndex++;
}
} else {
for (let y = startY; y <= endY; y++) {
if (matrix[startX][y] !== word[wordIndex]) {
wordFound = false;
break;
}
wordIndex++;
}
}
}
// Vertical Check
else if (startY === endY) {
if (startX > endX) {
for (let x = endX; x <= startX; x++) {
if (matrix[x][startY] !== word[wordIndex]) {
wordFound = false;
break;
}
wordIndex++;
}
} else {
for (let x = startX; x <= endX; x++) {
if (matrix[x][startY] !== word[wordIndex]) {
wordFound = false;
break;
}
wordIndex++;
}
}
}
// Diagonal Check
else if (startX > endX) {
for (let x = startX, y = startY; x >= endX; x--, y--) {
if (matrix[x][y] !== word[wordIndex]) {
wordFound = false;
break;
}
wordIndex++;
}
} else {
for (let x = startX, y = startY; x <= endX; x++, y--) {
if (matrix[x][y] !== word[wordIndex]) {
wordFound = false;
break;
}
wordIndex++;
}
}
if (wordFound) {
foundWords.push(word);
}
}
return foundWords;
}
const solve = [
{ word: "butter", startX: 3, startY: 6, endX: 3, endY: 1 },
{ word: "chicken", startX: 8, startY: 2, endX: 2, endY: 2 },
{ word: "coconut", startX: 9, startY: 10, endX: 3, endY: 4 },
{ word: "gremilins", startX: 1, startY: 0, endX: 9, endY: 8 },
{ word: "ham", startX: 7, startY: 2, endX: 5, endY: 0 },
{ word: "iceland", startX: 10, startY: 1, endX: 4, endY: 1 },
];
const matrix = [
["r", "g", "j", "t", "o", "m", "a", "t", "o", "w", "t"],
["z", "a", "r", "r", "d", "n", "a", "l", "e", "c", "i"],
["e", "m", "n", "e", "k", "c", "i", "h", "c", "f", "b"],
["r", "c", "t", "t", "m", "a", "t", "v", "a", "a", "b"],
["o", "z", "q", "t", "t", "i", "a", "o", "u", "i", "a"],
["p", "j", "z", "u", "u", "e", "l", "u", "z", "b", "r"],
["a", "o", "e", "b", "r", "n", "y", "i", "z", "r", "g"],
["g", "n", "n", "o", "h", "w", "o", "h", "n", "e", "a"],
["n", "q", "k", "u", "w", "o", "h", "c", "y", "s", "p"],
["i", "j", "l", "a", "g", "u", "t", "r", "o", "p", "n"],
["s", "h", "y", "s", "a", "n", "d", "w", "i", "c", "h"],
];
console.log(findWords(solve, matrix));
The current output only lists some of the found words. But all the provided words are present in the matrix.