feat: added counter bin

This commit is contained in:
əlemi 2023-11-18 06:13:08 +01:00
parent 77620f9ea1
commit 933cf0c762
Signed by: alemi
GPG key ID: A4895B84D311642C
3 changed files with 36 additions and 1 deletions

View file

@ -1,8 +1,17 @@
[package] [package]
name = "mood-cgi" name = "mood"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
[[bin]]
name = "mood.cgi"
path = "src/cgi.rs"
[[bin]]
name = "mood-counter"
path = "src/counter.rs"
# 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]

26
src/counter.rs Normal file
View file

@ -0,0 +1,26 @@
use std::collections::HashMap;
fn main() {
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 sum = lines.iter().map(|(x,_)| x).sum::<u64>() as f32;
let mut probabilities = HashMap::new();
for (count, line) in &lines {
probabilities.insert(line, *count as f32 / sum);
}
println!("{{");
for (line, chance) in probabilities {
println!(" \"{}\": {:.6},", line.replace('"', "\\\""), chance);
}
println!(" \"count\": {},", lines.len());
println!(" \"total\": {}", sum);
println!("}}");
}