I made the following code to allocate words in a array of arrays. Like a word game.
var board = [
["m","t","h","v","g","y","m","w","n","q"],
["q","e","v","f","a","k","n","c","c","k"],
["x","s","r","e","r","c","m","c","h","a"],
["j","z","f","w","g","i","o","t","b","l"],
["x","v","j","m","x","q","s","s","v","c"],
["m","i","i","a","e","u","t","t","j","m"],
["t","n","j","w","h","j","e","m","b","d"],
["v","n","t","f","r","y","b","q","v","a"],
["k","q","x","b","q","w","c","i","v","g"],
["s","o","m","e","t","h","i","n","g","t"]
];
const directions = [
'horizontal',
'vertical'
];
function chooseRandomPlace() {
return [Math.floor(Math.random() * 10),
Math.floor(Math.random() * 10)];
}
let i = 0;
function horizontal(word) {
i++;
console.log(i);
let wordLength = word.length;
let [x, y] = chooseRandomPlace();
if (9 - y < wordLength) return horizontal(word);
for (let i = 0; i < wordLength; i++) {
if (typeof board[x][y + i] !== 'string') {
return horizontal(word)
}
}
for (let i = 0; i < wordLength; i++) {
board[x][y + i] = {value: word[i]};
}
}
function vertical(word) {
i++;
console.log(i);
let wordLength = word.length;
let [x, y] = chooseRandomPlace();
if (9 - x < wordLength) return vertical(word);
for (let i = 0; i < wordLength; i++) {
if (typeof board[x + i][y] !== 'string') {
return vertical(word);
}
}
for (let i = 0; i < wordLength; i++) {
board[x + i][y] = {value: word[i]};
}
}
function alocate(word) {
let direction = directions[Math.floor(Math.random() * directions.length)];
if (direction === 'horizontal') {
horizontal(word)
} else {
vertical(word);
}
console.log(JSON.stringify(board));
}
const words = ['SOMETHIN', 'SOMETHIN', 'SOMETHIN', 'SOMETHIN', 'SOMETHIN'];
for (let word of words) {
let location = alocate(word);
}
And is working, but it can cause a Maximum call stack size exceeded error error depending on the number of words (max of 10) and the length of each word. Is there any type of improvement to do to avoid this... and if not, is there some sort of mathematic algorithm to set a secure limit of words with max length?
Thank you.