RosettaCodeData/Task/Entropy/Rust/entropy.rust

21 lines
458 B
Text
Raw Permalink Normal View History

2015-11-18 06:14:39 +00:00
fn entropy(s: &[u8]) -> f32 {
2019-09-12 10:33:56 -07:00
let mut histogram = [0u64; 256];
2014-04-02 16:56:35 +00:00
2019-09-12 10:33:56 -07:00
for &b in s {
histogram[b as usize] += 1;
2015-11-18 06:14:39 +00:00
}
2019-09-12 10:33:56 -07:00
histogram
.iter()
.cloned()
.filter(|&h| h != 0)
.map(|h| h as f32 / s.len() as f32)
.map(|ratio| -ratio * ratio.log2())
.sum()
2015-11-18 06:14:39 +00:00
}
2014-04-02 16:56:35 +00:00
2015-11-18 06:14:39 +00:00
fn main() {
let arg = std::env::args().nth(1).expect("Need a string.");
2019-09-12 10:33:56 -07:00
println!("Entropy of {} is {}.", arg, entropy(arg.as_bytes()));
2014-04-02 16:56:35 +00:00
}