INS solution

This commit is contained in:
Fizzizist 2025-03-16 10:56:25 -04:00
parent 125e0163d9
commit 5f085f90b1
3 changed files with 36 additions and 0 deletions

32
rust/src/solutions/ins.rs Normal file
View File

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

View File

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

View File

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