Created
June 12, 2018 14:44
-
-
Save AnthonyMikh/23db0802802deae793ba815837ede659 to your computer and use it in GitHub Desktop.
Решение задачи №101 от UniLecs (Мажоритарный элемент массива)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Playground: http://play.rust-lang.org/?gist=67c7fa50f902ed2f81d43060495c7d4e&version=stable&mode=debug