new algorithm

This commit is contained in:
gvcgael
2022-11-30 22:54:29 +01:00
parent 487b6312f6
commit 6d92ccb908

View File

@@ -5,6 +5,7 @@ use axum::{
}; };
use once_cell::sync::Lazy; use once_cell::sync::Lazy;
use rand::{thread_rng, Rng}; use rand::{thread_rng, Rng};
use rand::seq::SliceRandom;
use serde::Deserialize; use serde::Deserialize;
use std::net::SocketAddr; use std::net::SocketAddr;
use tokio::sync::Mutex; use tokio::sync::Mutex;
@@ -47,18 +48,21 @@ static STATE: Lazy<Mutex<State>> = Lazy::new(Mutex::default);
struct State { struct State {
participants: Vec<String>, participants: Vec<String>,
remaining: Vec<String>,
} }
fn everyone() -> Vec<String> { fn everyone() -> Vec<String> {
let mut rng = thread_rng(); vec!["Alice".into(), "Bob".into(), "Carol".into(), "Dave".into()]
let mut e = vec!["Alice".into(), "Bob".into(), "Carol".into(), "Dave".into()];
return rng.shuffle(&e[..];
} }
impl Default for State { impl Default for State {
fn default() -> Self { fn default() -> Self {
Self { let mut p = everyone();
participants: 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<Input>) -> String { async fn input(Json(input): Json<Input>) -> String {
let mut state = STATE.lock().await; let mut state = STATE.lock().await;
if state.participants.is_empty() { if state.remaining.is_empty() {
return "ERROR (everybody drew already)".into(); return "ERROR (everybody drew already)".into();
} }
match state.participants.iter().position(|p| input.person == *p) { info!("joueurs qui restent : {:?}", state.remaining.join(","));
Some(pos) => { match state.remaining.iter().position(|p| input.person == *p).map(|e| state.remaining.remove(e)) {
info!("joueur qui pioche : {:?}", pos); Some(rem) => {
return match state.participants.iter().nth(pos+1) { match state.participants.iter().position(|p| input.person == *p) {
Some(x) => x.to_string(), Some(pos) => {
None => return match state.participants.first() { info!("joueur qui pioche : {:?}", state.participants[pos]);
Some(x) => x.to_string(), return match state.participants.iter().nth(pos+1) {
None => "ERROR".to_string() 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()
} }
} }