From 5f085f90b15bc415a27008fccae6264dda3bdeec Mon Sep 17 00:00:00 2001 From: Fizzizist Date: Sun, 16 Mar 2025 10:56:25 -0400 Subject: [PATCH] INS solution --- rust/src/solutions/ins.rs | 32 ++++++++++++++++++++++++++++++++ rust/src/solutions/mod.rs | 2 ++ rust/src/utils.rs | 2 ++ 3 files changed, 36 insertions(+) create mode 100644 rust/src/solutions/ins.rs diff --git a/rust/src/solutions/ins.rs b/rust/src/solutions/ins.rs new file mode 100644 index 0000000..2d87eee --- /dev/null +++ b/rust/src/solutions/ins.rs @@ -0,0 +1,32 @@ +pub fn ins(input_content: String) -> String { + let lines: Vec<&str> = input_content.lines().collect(); + let n: usize = lines[0].parse().unwrap(); + let mut a: Vec = lines[1] + .split_whitespace() + .map(|x| x.parse().unwrap()) + .collect(); + let mut swaps = 0; + for i in 1..n { + let mut k = i; + while k >= 1 && a[k] < a[k - 1] { + a.swap(k, k - 1); + k -= 1; + swaps += 1; + } + } + return swaps.to_string(); +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_ins() { + let input_content = r#"6 +6 10 4 5 1 2"# + .to_string(); + let expected = "12".to_string(); + assert_eq!(ins(input_content), expected); + } +} diff --git a/rust/src/solutions/mod.rs b/rust/src/solutions/mod.rs index 5db9c45..2809ea6 100644 --- a/rust/src/solutions/mod.rs +++ b/rust/src/solutions/mod.rs @@ -1,11 +1,13 @@ mod bins; mod iev; +mod ins; mod lia; mod maj; mod prtm; mod revp; pub use bins::bins; pub use iev::iev; +pub use ins::ins; pub use lia::lia; pub use maj::maj; pub use prtm::prtm; diff --git a/rust/src/utils.rs b/rust/src/utils.rs index bebecc6..6982e5b 100644 --- a/rust/src/utils.rs +++ b/rust/src/utils.rs @@ -37,6 +37,7 @@ pub enum Problem { LIA, BINS, MAJ, + INS, } pub fn run_solution(problem: Problem, in_file: &String, out_file: &String) { @@ -49,6 +50,7 @@ pub fn run_solution(problem: Problem, in_file: &String, out_file: &String) { Problem::LIA => Ok(solutions::lia(content)), Problem::BINS => Ok(solutions::bins(content)), Problem::MAJ => Ok(solutions::maj(content)), + Problem::INS => Ok(solutions::ins(content)), }, Err(e) => Err(e), };