Another update from ingydotnet^djgoku

This commit is contained in:
Ingy döt Net 2015-11-18 06:14:39 +00:00
parent 91df62d461
commit 948b86eafa
7604 changed files with 108452 additions and 22726 deletions

View file

@ -1,16 +1,20 @@
// works for Rust 0.9
fn entropy(s: &str) -> f32 {
let mut entropy: f32 = 0.0;
let mut histogram = [0, ..256];
let len = s.len();
fn entropy(s: &[u8]) -> f32 {
let mut entropy: f32 = 0.0;
let mut histogram = [0; 256];
for i in range(0, len) { histogram[s[i]] += 1; }
for i in range(0, 256) {
if histogram[i] > 0 {
let ratio = (histogram[i] as f32 / len as f32) as f32;
entropy -= (ratio * log2(ratio)) as f32;
}
}
entropy
for i in 0..s.len() {
histogram.get_mut(s[i] as usize).map(|v| *v += 1);
}
for i in 0..256 {
if histogram[i] > 0 {
let ratio = (histogram[i] as f32 / s.len() as f32) as f32;
entropy -= (ratio * ratio.log2()) as f32;
}
}
entropy
}
fn main() {
let arg = std::env::args().nth(1).expect("Need a string.");
println!("Entropy of {} is {}.", arg, entropy(&arg.bytes().collect::<Vec<_>>()));
}