From 4fa723b69600e03f4d7310487988b326c36ab6a3 Mon Sep 17 00:00:00 2001 From: Gustav Eek Date: Wed, 25 Jan 2023 07:59:14 +0100 Subject: [PATCH] Src. Change to exponential distribution * Use crate *statrs* * Provide *exp* function for exponential distribution * Refactor function *normalize* * Call by reference in *output* function --- src/main.rs | 53 ++++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 40 insertions(+), 13 deletions(-) diff --git a/src/main.rs b/src/main.rs index 949ac53..a3d9697 100644 --- a/src/main.rs +++ b/src/main.rs @@ -4,6 +4,8 @@ use std::io; // bring flush() into scope with `use std::io::Write` use std::io::prelude::*; // Bring `std::io::BufRead` in scope +use statrs::distribution::{Exp, ContinuousCDF}; // Continuous needed for pdf +// use statrs::statistics::Distribution; fn input() -> Vec { // Consider datastructure some list of strings @@ -12,34 +14,59 @@ fn input() -> Vec { v } -fn output(prio: Vec, ranked: Vec) { +fn output(prio: &Vec, ranked: &Vec) { for (p, l) in prio.iter().zip(ranked.iter()) { println!("{:2.0} %\t{}", p * 100.0, l); } } +fn normalize(mut arg: Vec) -> Vec { + let mut sum = 0.0; + for v in &arg { + sum += v; + } + for i in 0..arg.len() { + arg[i] /= sum; + } + arg +} + + fn delta(n: i32) -> Vec { - let mut ret: Vec = Vec::new(); - for _i in 0..n { - ret.push(1.0 / n as f64); + let mut prio: Vec = Vec::new(); + const MEAN: f64 = 1.0; // unessential thanks to normalization + for i in 1..n + 1 { + prio.push(MEAN); } - ret + prio.reverse(); + normalize(prio) } +fn exp(n: i32) -> Vec { + const RATE: f64 = 1.0; // rate is unessential thanks to normalization + let mut prio: Vec = Vec::new(); + let dist = Exp::new(RATE).unwrap(); + for i in 1..n + 1 { + let f = i as f64 / (n as f64 + 1.0); + let x = dist.inverse_cdf(f); + prio.push(x); + } + prio.reverse(); + normalize(prio) +} + + fn main() { + let ranked: Vec = input(); let num = ranked.len() as i32; - let prio = delta(num); - for p in prio.iter() { - eprint!("{} ", p); - } - eprintln!(""); - for l in ranked.iter() { - eprint!("{} ", l); + let _prio1 = delta(num); + let prio2 = exp(num); + } eprintln!(""); eprintln!("That was {} items: {}", num, prio[0]); - output(prio, ranked); + output(&prio2, &ranked); } -- 2.39.5