|
A little function to help ;) function searchWord(grid, word) {
const rows = grid.length;
const cols = grid[0].length;
const wordLength = word.length;
let found = false; const directions = [
{ dr: 0, dc: 1 },
{ dr: 1, dc: 0 },
{ dr: 1, dc: 1 },
{ dr: 1, dc: -1 },
{ dr: 0, dc: -1 },
{ dr: -1, dc: 0 },
{ dr: -1, dc: -1 },
{ dr: -1, dc: 1 }
];
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
for (const { dr, dc } of directions) {
let match = true;
const positions = [];
for (let k = 0; k < wordLength; k++) {
const nr = r + k * dr;
const nc = c + k * dc;
if (nr < 0 || nr >= rows || nc < 0 || nc >= cols || grid[nr][nc].textContent !== word[k]) {
match = false;
break;
}
positions.push(grid[nr][nc]);
}
if (match) {
positions.forEach(cell => cell.style.backgroundColor = 'pink');
console.log(`Found the word '${word}' at positions:`);
positions.forEach((cell) => {
const index = Array.prototype.indexOf.call(cell.parentElement.children, cell);
const row = Math.floor(index / cols);
const col = index % cols;
console.log(`(${row}, ${col})`);
});
found = true;
return;
}
}
}
}
if (!found) {
console.log(`The word '${word}' was not found in the grid.`);
}
}const gridContainer = document.querySelector('.grid.mb-30');
const gridElements = gridContainer.querySelectorAll('.letter');
const grid = [];
const rows = 100;
const cols = 10; for (let i = 0; i < rows; i++) {
const row = [];
for (let j = 0; j < cols; j++) {
row.push(gridElements[i * cols + j]);
}
grid.push(row);
} searchWord(grid, 'FOX'); |