feat: weighted random, 1 per minute

This commit is contained in:
əlemi 2023-11-14 06:02:16 +01:00
parent 2a37428f56
commit 05fde380f9
Signed by: alemi
GPG key ID: A4895B84D311642C
2 changed files with 39 additions and 6 deletions

View file

@ -6,4 +6,3 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
rand = "0.8.5"

View file

@ -1,11 +1,45 @@
use rand::seq::IteratorRandom; use std::{hash::Hasher, collections::hash_map::DefaultHasher, time::{SystemTime, UNIX_EPOCH}};
// this is trash but i only need a unique string each minute
fn formatted_timestamp() -> String {
let t = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("UNIX time overflowed again")
.as_secs();
format!(
"D{} H{} M{}",
(t / (60 * 60 * 24)),
(t / (60 * 60)) % 60,
(t / 60) % 60,
)
}
fn main() { fn main() {
let file = std::env::var("MOOD_FILE").unwrap_or("/srv/http/api/mood.txt".to_string()); let now_str = formatted_timestamp();
let content = std::fs::read_to_string(file).unwrap();
let choice = content.lines().choose(&mut rand::thread_rng()).unwrap(); let mut hasher = DefaultHasher::new();
hasher.write(now_str.as_bytes());
let index = hasher.finish() as usize;
let file = std::env::var("MOOD_FILE").expect("missing MOOD_FILE env variable");
let content = std::fs::read_to_string(file).expect("could not read MOOD_FILE contents");
let lines : Vec<(u64, &str)> = content.lines()
.map(|l| l.split_once(' ').unwrap())
.map(|(n, l)| (n.parse::<u64>().unwrap(), l))
.collect();
let mut pool = Vec::new();
pool.reserve(lines.iter().map(|(x,_)| x).sum::<u64>() as usize);
for (count, line) in lines {
for _ in 0..count {
pool.push(line);
}
}
let choice = pool[index % pool.len()];
println!("Content-type: application/json"); println!("Content-type: application/json");
println!(); println!();
println!("{{\"mood\":\"{}\"}}", choice); println!("{{\"id\":{},\"mood\":\"{}\"}}", index, choice);
} }