配列の配列に単語を割り当てるために、次のコードを作成しました。単語ゲームのように。配列の配列における文字割り当ての改善
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);
}
そして働いているが、それは言葉(10の最大)の数と、各単語の長さに応じて、Maximum call stack size exceeded error
エラーを引き起こす可能性があります。これを避けるための改善がありますか?そうでない場合は、最大長の単語の安全な制限を設定する数学的なアルゴリズムがありますか?
ありがとうございます。
あなたは現在、重複することなく、ランダムな位置に連続的に単語を置きます。そのようなポジションが利用できなくなるとすぐに、あなたは無限ループに陥ります。理想的には、これを認識してバックトラックを実行します。 –
なぜ以前の質問を削除しましたか? – guest271314