From 125e0163d95a03fda5aff83bc49c6f66972f49ab Mon Sep 17 00:00:00 2001 From: Fizzizist Date: Sat, 15 Mar 2025 16:07:47 -0400 Subject: [PATCH] MAJ solution --- rust/src/solutions/maj.rs | 47 +++++++++++++++++++++++++++++++++++++++ rust/src/solutions/mod.rs | 2 ++ rust/src/utils.rs | 2 ++ 3 files changed, 51 insertions(+) create mode 100644 rust/src/solutions/maj.rs diff --git a/rust/src/solutions/maj.rs b/rust/src/solutions/maj.rs new file mode 100644 index 0000000..d8f22cf --- /dev/null +++ b/rust/src/solutions/maj.rs @@ -0,0 +1,47 @@ +use std::collections::HashMap; +fn get_maj(a: Vec) -> i32 { + let mut counts = HashMap::new(); + for &i in &a { + let count = counts.entry(i).or_insert(0); + *count += 1; + if *count > a.len() / 2 { + return i as i32; + } + } + -1 +} + +pub fn maj(file_content: String) -> String { + let lines: Vec<&str> = file_content.lines().collect(); + let result: Vec = lines[1..] + .iter() + .map(|x| { + let arr: Vec = x + .split(' ') + .map(|y| { + y.parse() + .expect("couldn't parse one of the nums in one of the arrays") + }) + .collect(); + get_maj(arr).to_string() + }) + .collect(); + result.join(" ") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_maj() { + let input_content = r#"4 8 +5 5 5 5 5 5 5 5 +8 7 7 7 1 7 3 7 +7 1 6 5 10 100 1000 1 +5 1 6 7 1 1 10 1"# + .to_string(); + let expected = "5 7 -1 -1".to_string(); + assert_eq!(maj(input_content), expected); + } +} diff --git a/rust/src/solutions/mod.rs b/rust/src/solutions/mod.rs index b41f75b..5db9c45 100644 --- a/rust/src/solutions/mod.rs +++ b/rust/src/solutions/mod.rs @@ -1,10 +1,12 @@ mod bins; mod iev; mod lia; +mod maj; mod prtm; mod revp; pub use bins::bins; pub use iev::iev; pub use lia::lia; +pub use maj::maj; pub use prtm::prtm; pub use revp::revp; diff --git a/rust/src/utils.rs b/rust/src/utils.rs index 5b21f1e..bebecc6 100644 --- a/rust/src/utils.rs +++ b/rust/src/utils.rs @@ -36,6 +36,7 @@ pub enum Problem { IEV, LIA, BINS, + MAJ, } pub fn run_solution(problem: Problem, in_file: &String, out_file: &String) { @@ -47,6 +48,7 @@ pub fn run_solution(problem: Problem, in_file: &String, out_file: &String) { Problem::IEV => Ok(solutions::iev(content)), Problem::LIA => Ok(solutions::lia(content)), Problem::BINS => Ok(solutions::bins(content)), + Problem::MAJ => Ok(solutions::maj(content)), }, Err(e) => Err(e), };