From a0500d142def750cf8cd07245357ad4e687ff8e7 Mon Sep 17 00:00:00 2001 From: Gleb Koval Date: Mon, 8 Aug 2022 00:26:36 +0000 Subject: [PATCH] optimised o-x-rust --- wasm/o-x-rust/Cargo.lock | 2 +- wasm/o-x-rust/Cargo.toml | 2 +- wasm/o-x-rust/src/lib.rs | 21 +++++++++++++++------ 3 files changed, 17 insertions(+), 8 deletions(-) diff --git a/wasm/o-x-rust/Cargo.lock b/wasm/o-x-rust/Cargo.lock index 8d5c546..ebd7e24 100644 --- a/wasm/o-x-rust/Cargo.lock +++ b/wasm/o-x-rust/Cargo.lock @@ -25,7 +25,7 @@ dependencies = [ [[package]] name = "o-x-rust" -version = "0.0.5" +version = "0.0.6" dependencies = [ "wasm-bindgen", ] diff --git a/wasm/o-x-rust/Cargo.toml b/wasm/o-x-rust/Cargo.toml index 46fd215..92898db 100644 --- a/wasm/o-x-rust/Cargo.toml +++ b/wasm/o-x-rust/Cargo.toml @@ -4,7 +4,7 @@ description = "Noughts and crosses WASM algorithms" repository = "https://git.koval.net/cyclane/game-algorithms/src/branch/main/wasm/o-x-rust" license = "GNU GPLv3" readme = "README.md" -version = "0.0.5" +version = "0.0.6" edition = "2021" [lib] diff --git a/wasm/o-x-rust/src/lib.rs b/wasm/o-x-rust/src/lib.rs index 265cb2d..b3ff053 100644 --- a/wasm/o-x-rust/src/lib.rs +++ b/wasm/o-x-rust/src/lib.rs @@ -35,16 +35,23 @@ pub fn get_turn(me: u8, other: u8, first: bool, empty: usize) -> u8 { } #[wasm_bindgen] -pub fn get_score(me: u8, other: u8, first: bool, board: &[u8]) -> i32 { +pub fn get_score(me: u8, other: u8, first: bool, board: &[u8]) -> f64 { + let (outcomes, score) = sub_get_score(me, other, first, board); + score as f64 / outcomes as f64 +} + +// outcomes*2, winning outcomes (win = 2, draw = 1, loose = 0) +pub fn sub_get_score(me: u8, other: u8, first: bool, board: &[u8]) -> (i32, i32) { let winner = find_winner(board); if winner != 0 { - return if winner == me { 1 } else { -1 }; + return if winner == me { (2, 2) } else { (2, 0) }; } let empty = count_empty(board); if empty == 0 { - return 0; + return (2, 1); } let mut score = 0; + let mut outcomes = 0; for i in 0..9 { if board[i] != 0 { continue; @@ -52,14 +59,16 @@ pub fn get_score(me: u8, other: u8, first: bool, board: &[u8]) -> i32 { let copy = &mut [0u8; 9]; copy.copy_from_slice(board); copy[i] = get_turn(me, other, first, empty); - score += get_score(me, other, first, copy); + let (sub_outcomes, sub_score) = sub_get_score(me, other, first, copy); + outcomes += sub_outcomes; + score += sub_score; } - score + (outcomes, score) } #[wasm_bindgen] pub fn predict(me: u8, other: u8, first: bool, board: &[u8]) -> usize { - let (mut max_p, mut max_s) = (0, i32::MIN); + let (mut max_p, mut max_s) = (0, f64::MIN); let empty = count_empty(board); if empty == 0 { return 0;