diff --git a/main.js b/main.js index b5bad1f..3dbba8c 100644 --- a/main.js +++ b/main.js @@ -21,20 +21,38 @@ function with_move(board, move) { // } // return best_move; // } +// classic: https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array +function shuffle(array) { + let currentIndex = array.length, randomIndex; + // While there remain elements to shuffle. + while (currentIndex != 0) { + // Pick a remaining element. + randomIndex = Math.floor(Math.random() * currentIndex); + currentIndex--; + // And swap it with the current element. + [array[currentIndex], array[randomIndex]] = [ + array[randomIndex], + array[currentIndex], + ]; + } + return array; +} // could return early if zero but meh function min_move_by(board, score) { let best_score = Infinity; let best_move = ""; let moves = board.moves(); + shuffle(moves); // console.log(moves); - for (const i in moves) { - let move = moves[i]; + for (const move of moves) { try { let new_board = with_move(board, move); let new_score = score(new_board); // console.log({ move, best_score, new_score, best_move }); - if (new_score < best_score || - (new_score == best_score && Math.random() > 0.5)) { + if (new_score < best_score + // array is already shuffled + // (new_score == best_score && Math.random() > 0.5) + ) { console.log("New best (or equal): ", new_score, move); best_score = new_score; best_move = move; diff --git a/main.ts b/main.ts index 75823aa..e99542d 100644 --- a/main.ts +++ b/main.ts @@ -43,6 +43,26 @@ function with_move(board: Chess, move: string): Chess { // return best_move; // } +// classic: https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array +function shuffle(array) { + let currentIndex = array.length, + randomIndex; + + // While there remain elements to shuffle. + while (currentIndex != 0) { + // Pick a remaining element. + randomIndex = Math.floor(Math.random() * currentIndex); + currentIndex--; + + // And swap it with the current element. + [array[currentIndex], array[randomIndex]] = [ + array[randomIndex], + array[currentIndex], + ]; + } + + return array; +} // could return early if zero but meh function min_move_by(board: Chess, score: (_: Chess) => number): string { @@ -50,17 +70,18 @@ function min_move_by(board: Chess, score: (_: Chess) => number): string { let best_move = ""; let moves = board.moves(); + shuffle(moves); // console.log(moves); - for (const i in moves) { - let move = moves[i]; + for (const move of moves) { try { let new_board = with_move(board, move); let new_score = score(new_board); // console.log({ move, best_score, new_score, best_move }); if ( - new_score < best_score || - (new_score == best_score && Math.random() > 0.5) + new_score < best_score + // array is already shuffled + // (new_score == best_score && Math.random() > 0.5) ) { console.log("New best (or equal): ", new_score, move); best_score = new_score;