MAJ solution

This commit is contained in:
Fizzizist 2025-03-15 16:07:47 -04:00
parent 7ca6bad320
commit 125e0163d9
3 changed files with 51 additions and 0 deletions

47
rust/src/solutions/maj.rs Normal file
View File

@ -0,0 +1,47 @@
use std::collections::HashMap;
fn get_maj(a: Vec<u32>) -> 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<String> = lines[1..]
.iter()
.map(|x| {
let arr: Vec<u32> = 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);
}
}

View File

@ -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;

View File

@ -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),
};