(hopefully) fix randomness

This commit is contained in:
mehbark 2023-03-29 17:02:53 -04:00
parent 4479dfdec5
commit 8f63113e4c
2 changed files with 47 additions and 8 deletions

26
main.js
View file

@ -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;

29
main.ts
View file

@ -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;