Entropy: Difference between revisions

102 bytes removed ,  5 years ago
Improve Rust.
(Added Fōrmulæ)
(Improve Rust.)
Line 2,463:
=={{header|Rust}}==
<lang rust>fn entropy(s: &[u8]) -> f32 {
let mut entropy: f32histogram = 0.0[0u64; 256];
let mut histogram = [0; 256];
 
for i&b in 0..s.len() {
histogram.get_mut(s[i]b as usize).map(|v| *v] += 1);
}
 
for i in 0..256 {
if histogram[i] > 0 {
.iter()
let ratio = (histogram[i] as f32 / s.len() as f32) as f32;
.cloned()
entropy -= (ratio * ratio.log2()) as f32;
}.filter(|&h| h != 0)
.map(|h| let ratio = (histogram[i]h as f32 / s.len() as f32) as f32;
}
entropy.map(|ratio| -= (ratio * ratio.log2()) as f32;
entropy
.sum()
}
 
fn main() {
let arg = std::env::args().nth(1).expect("Need a string.");
println!("Entropy of {} is {}.", arg, entropy(&arg.bytes().collect::<Vec<_>>as_bytes()));
}</lang>
{{out}}
Anonymous user