Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Win ratio #12

Merged
merged 3 commits into from
Jan 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 26 additions & 13 deletions src/config.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
//! `config` contains logic for configuring and running the tournament

use std::sync::{Arc, Mutex};
use std::{sync::{Arc, Mutex}, cmp::Ordering};
use rand::{prelude::*, distributions};
use threadpool::ThreadPool;
use constcat::concat;
Expand Down Expand Up @@ -207,7 +207,7 @@ impl Config {
/// * `player_1`- A [player](Player)
/// * `player_2`- A [player](Player) (may be the same as `player_1`)
/// * `score_totals` - Total score values for the players in the tournament
fn add_game(&self, player_1: Player, player_2: Player, score_totals: (Arc<Mutex<i32>>, Arc<Mutex<i32>>)) {
fn add_game(&self, player_1: Player, player_2: Player, score_totals: (Arc<Mutex<(i32, i32)>>, Arc<Mutex<(i32, i32)>>)) {
let rounds = self.rounds;
let show_games = self.show_games;
self.threadpool.execute(move || {
Expand All @@ -220,17 +220,27 @@ impl Config {
}

if let Ok(mut score) = score_totals.0.lock() {
*score += scores.0;
score.0 += scores.0;
score.1 += match scores.0.cmp(&scores.1) {
Ordering::Less => -1,
Ordering::Equal => 0,
Ordering::Greater => 1,
}
}

if let Ok(mut score) = score_totals.1.lock() {
*score += scores.1;
score.0 += scores.1;
score.1 += match scores.1.cmp(&scores.0) {
Ordering::Less => -1,
Ordering::Equal => 0,
Ordering::Greater => 1,
}
}
});
}
}

/// Create a vector of atomically reference counted and mutable score counters.
/// Create a vector of atomically reference counted and mutable score and relative win counters.
///
/// # Arguments
///
Expand All @@ -239,14 +249,14 @@ impl Config {
/// # Panics
///
/// If `length == 0`.
fn init_scores(length: usize) -> Vec<Arc<Mutex<i32>>> {
fn init_scores(length: usize) -> Vec<Arc<Mutex<(i32, i32)>>> {
if length == 0 {
panic!("Cannot initialize scores with a length of 0");
}

let mut scores = Vec::new();
for _ in 0..length {
scores.push(Arc::new(Mutex::new(0)));
scores.push(Arc::new(Mutex::new((0, 0))));
}

scores
Expand Down Expand Up @@ -305,9 +315,9 @@ fn random_rounds(min: u32, max: u32) -> u32 {
///
/// let scores_1 = run(&config_1, &players).unwrap();
///
/// assert_eq!(scores_1, [(36, "1"), (5, "2")]);
/// assert_eq!([(scores_1[0].0, scores_1[0].2), (scores_1[1].0, scores_1[1].2)], [(36, "1"), (5, "2")]);
/// ```
pub fn run<'a>(config: &Config, players: &'a Vec<Player>) -> Result<Vec<(i32, &'a str)>, &'static str> {
pub fn run<'a>(config: &Config, players: &'a Vec<Player>) -> Result<Vec<(i32, f32, &'a str)>, &'static str> {
if players.len() < 2 {
return Err("Too few players");
}
Expand All @@ -334,9 +344,12 @@ pub fn run<'a>(config: &Config, players: &'a Vec<Player>) -> Result<Vec<(i32, &'

let mut scores = scores.iter()
.enumerate()
.map(|(i, v)| (*v.lock().unwrap(), players[i].get_name()))
.map(|(i, v)| {
let v = v.lock().unwrap();
(v.0, v.1 as f32 / (players.len() - 1) as f32, players[i].get_name())
})
.collect::<Vec<_>>();
scores.sort();
scores.sort_unstable_by(|a, b| a.0.cmp(&b.0));

Ok(scores.iter()
.rev()
Expand Down Expand Up @@ -366,8 +379,8 @@ mod tests {
let scores_1 = run(&config_1, &players).unwrap();
let scores_2 = run(&config_2, &players).unwrap();

assert_eq!(scores_1, [(36, "1"), (5, "2")]);
assert_eq!(scores_2, [(14, "1"), (3, "2")]);
assert_eq!([(scores_1[0].0, scores_1[0].2), (scores_1[1].0, scores_1[1].2)], [(36, "1"), (5, "2")]);
assert_eq!([(scores_2[0].0, scores_2[0].2), (scores_2[1].0, scores_2[1].2)], [(14, "1"), (3, "2")]);
}

#[test]
Expand Down
13 changes: 9 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ fn main() {
}
};

println!("Program start\n");
println!("\nTournament start\n");

let players = vec![
Player::with_name("Take back 1", take_back_once_prisoner),
Expand All @@ -40,10 +40,15 @@ fn main() {

let scores = run(&config, &players).unwrap();

println!("{0} rounds!", config.rounds());
println!("{0} rounds!\n", config.rounds());
println!("no. program_name avg_score rel_win_ratio");
println!("--------------------------------------------------------------");

for (i, v) in scores.iter().enumerate() {
println!("{0}. {2} - {1:.2}", i + 1, v.0 as f32 / players.len() as f32, v.1);
let placement = format!("{}.", i + 1);
let ratio = format!("({:.2}%)", v.1 * 100.0);
println!("{0:<3} {2:<32} {1:<11.2} {3:<8}", placement, v.0 as f32 / players.len() as f32, v.2, ratio);
}

println!("\nProgram end");
println!("\nTournament end\n");
}
12 changes: 0 additions & 12 deletions src/programs/prisoners.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,6 @@ pub fn take_back_once_prisoner(last_moves: &[Move]) -> Color {
Color::Green
}

pub fn friendly(_last_moves: &[Move]) -> Color {
Color::Green
}

pub fn evil(_last_moves: &[Move]) -> Color {
Color::Red
}

pub fn blue(_last_moves: &[Move]) -> Color {
Color::Blue
}

pub fn tit_for_tat_prisoner(last_moves: &[Move]) -> Color {
if let Some(last_move) = last_moves.last() {
if last_move.1 == Color::Red {
Expand Down
12 changes: 12 additions & 0 deletions src/programs/simple.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
use crate::programs::prelude::*;

pub fn friendly(_last_moves: &[Move]) -> Color {
Color::Green
}

pub fn evil(_last_moves: &[Move]) -> Color {
Color::Red
}

pub fn blue(_last_moves: &[Move]) -> Color {
Color::Blue
}

pub fn random(_last_moves: &[Move]) -> Color {
*[Color::Red, Color::Green, Color::Blue].choose(&mut rand::thread_rng()).unwrap()
}
Expand Down