Skip to content

Instantly share code, notes, and snippets.

@AnthonyMikh
Created June 12, 2018 14:44
Show Gist options
  • Save AnthonyMikh/23db0802802deae793ba815837ede659 to your computer and use it in GitHub Desktop.
Save AnthonyMikh/23db0802802deae793ba815837ede659 to your computer and use it in GitHub Desktop.
Решение задачи №101 от UniLecs (Мажоритарный элемент массива)
fn majority(arr: &[f64]) -> Option<f64> {
use std::collections::HashMap;
let threshold = arr.len() / 2;
let mut occurs = HashMap::new();
for &f in arr {
//f64 не хэшируется, в отличие от
//битового представления u64
let fbits = f.to_bits();
let count = occurs.entry(fbits).or_insert(0usize);
*count += 1;
if *count > threshold {
return Some(f);
}
}
None
}
#[test]
fn some_variants() {
let arr = [1.0, 2.0, 3.0, 4.0, 1.0, 1.0, 1.0];
assert_eq!(majority(&arr), Some(1.0));
let arr = [1.1, 1.0, 1.1, 1.1];
assert_eq!(majority(&arr), Some(1.1));
let arr = [1.0, 2.0, 3.0];
assert_eq!(majority(&arr), None);
let arr = [];
assert_eq!(majority(&arr), None);
}
@AnthonyMikh
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment