From 9979a0f4fe72e987e5d41670da7d4f365b4dbc1a Mon Sep 17 00:00:00 2001 From: inso Date: Sat, 23 Nov 2024 16:22:28 +0100 Subject: [PATCH] new algorithm --- src/main.rs | 46 +++++++++++++++++++++++++++++++--------------- 1 file changed, 31 insertions(+), 15 deletions(-) diff --git a/src/main.rs b/src/main.rs index 82fe481..3cd6a26 100644 --- a/src/main.rs +++ b/src/main.rs @@ -5,6 +5,7 @@ use axum::{ }; use once_cell::sync::Lazy; use rand::{thread_rng, Rng}; +use rand::seq::SliceRandom; use serde::Deserialize; use std::net::SocketAddr; use tokio::sync::Mutex; @@ -47,18 +48,21 @@ static STATE: Lazy> = Lazy::new(Mutex::default); struct State { participants: Vec, + remaining: Vec, } fn everyone() -> Vec { - let mut rng = thread_rng(); - let mut e = vec!["Alice".into(), "Bob".into(), "Carol".into(), "Dave".into()]; - return rng.shuffle(&e[..]; + vec!["Alice".into(), "Bob".into(), "Carol".into(), "Dave".into()] } impl Default for State { fn default() -> Self { - Self { - participants: everyone(), + let mut p = everyone(); + p.shuffle(&mut thread_rng()); + info!("distribution : {:?}", p.join(" => ")); + return Self { + participants: p, + remaining: everyone() } } } @@ -71,20 +75,32 @@ struct Input { async fn input(Json(input): Json) -> String { let mut state = STATE.lock().await; - if state.participants.is_empty() { + if state.remaining.is_empty() { return "ERROR (everybody drew already)".into(); } - match state.participants.iter().position(|p| input.person == *p) { - Some(pos) => { - info!("joueur qui pioche : {:?}", pos); - return match state.participants.iter().nth(pos+1) { - Some(x) => x.to_string(), - None => return match state.participants.first() { - Some(x) => x.to_string(), - None => "ERROR".to_string() + info!("joueurs qui restent : {:?}", state.remaining.join(",")); + match state.remaining.iter().position(|p| input.person == *p).map(|e| state.remaining.remove(e)) { + Some(rem) => { + match state.participants.iter().position(|p| input.person == *p) { + Some(pos) => { + info!("joueur qui pioche : {:?}", state.participants[pos]); + return match state.participants.iter().nth(pos+1) { + Some(x) => { + info!("joueur qui suit : {:?}", x); + return x.to_string(); + } + None => return match state.participants.first() { + Some(x) => { + info!("joueur qui suit : {:?}", x); + return x.to_string(); + } + None => "ERROR".to_string() + } + } } + None => "ERROR".to_string() } } - None => "ERROR".to_string() + None => "Vous avez déja pioché !".to_string() } }