Created
March 15, 2022 07:41
-
-
Save ugovaretto/93dd31dca990c978acf996e955963ea5 to your computer and use it in GitHub Desktop.
Height equalizer
This file contains 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
/// Tower equaliser: givern list of tower heights return the minimum number | |
/// of moves required to obtain tower of the same height or return "No solution" | |
fn towers(t: &[u32]) -> Option<u32> { | |
let mut moves: u32 = 0; | |
let mut n = t.to_vec(); | |
let max_moves: u32 = n.iter().sum(); | |
loop { | |
let imax = match n.iter().enumerate().max_by(|&(_, x), &(_, y)| x.cmp(&y)) { | |
Some((m, _)) => m, | |
_ => usize::MIN, | |
}; | |
let imin = match n.iter().enumerate().min_by(|&(_, x), &(_, y)| x.cmp(&y)) { | |
Some((m, _)) => m, | |
_ => usize::MAX, | |
}; | |
if n[imax] == n[imin] { | |
return Some(moves); | |
} | |
n[imax] -= 1; | |
n[imin] += 1; | |
moves += 1; | |
if moves >= max_moves { | |
return None; | |
} | |
} | |
} | |
fn main() { | |
let mut args = std::env::args(); | |
let exe = match args.next() { | |
Some(p) => p, | |
_ => "".to_string(), | |
}; | |
let n: Vec<u32> = args.flat_map(|x| x.parse()).collect(); | |
if n.is_empty() { | |
eprintln!("Error, usage: {} SPACE SEPARATED NUMBERS", exe); | |
std::process::exit(1); | |
} | |
if let Some(r) = towers(&n) { | |
println!("Number of moves: {}", r); | |
} else { | |
println!("No solution"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment