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 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<Mutex<State>> = Lazy::new(Mutex::default);
struct State {
participants: Vec<String>,
remaining: Vec<String>,
}
fn everyone() -> Vec<String> {
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,16 +75,25 @@ struct Input {
async fn input(Json(input): Json<Input>) -> String {
let mut state = STATE.lock().await;
if state.participants.is_empty() {
if state.remaining.is_empty() {
return "ERROR (everybody drew already)".into();
}
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 : {:?}", pos);
info!("joueur qui pioche : {:?}", state.participants[pos]);
return match state.participants.iter().nth(pos+1) {
Some(x) => x.to_string(),
Some(x) => {
info!("joueur qui suit : {:?}", x);
return x.to_string();
}
None => return match state.participants.first() {
Some(x) => x.to_string(),
Some(x) => {
info!("joueur qui suit : {:?}", x);
return x.to_string();
}
None => "ERROR".to_string()
}
}
@@ -88,3 +101,6 @@ async fn input(Json(input): Json<Input>) -> String {
None => "ERROR".to_string()
}
}
None => "Vous avez déja pioché !".to_string()
}
}