Skip to content

Instantly share code, notes, and snippets.

@AnthonyMikh
Last active December 23, 2018 21:35
Show Gist options
  • Save AnthonyMikh/55540519dc92d1163d89371e24efa8fb to your computer and use it in GitHub Desktop.
Save AnthonyMikh/55540519dc92d1163d89371e24efa8fb to your computer and use it in GitHub Desktop.
Рекурсивное решение задачи №148 от UniLecs (Обработка массива)
type Elem = i16;
fn sink_zeros(arr: &mut [Elem]) {
sink_zeros_recurrent(arr);
}
fn sink_zeros_recurrent(arr: &mut [Elem]) -> usize {
let rev = arr.iter().rev();
let non_zeros = rev.clone().take_while(|&&x| x != 0).count();
let zeros = rev.skip(non_zeros).take_while(|&&x| x == 0).count();
let len = arr.len();
if zeros == 0 {
return len;
}
let to_insert = sink_zeros_recurrent(&mut arr[..len - non_zeros - zeros]);
for (i, j) in (to_insert..).zip(len - non_zeros..len) {
arr.swap(i, j);
}
to_insert + non_zeros
}
fn main() {
let mut arr = [0, 0, -5, 4, 0, 2, 0];
sink_zeros(&mut arr);
println!("{:?}", arr); // [-5, 4, 2, 0, 0, 0, 0]
let mut arr = [4, 0, 6, 0, 0, -5];
sink_zeros(&mut arr);
println!("{:?}", arr); // [4, 6, -5, 0, 0, 0]
let mut arr = [1, 2, 3, 4, 5, 6];
sink_zeros(&mut arr);
println!("{:?}", arr); // [1, 2, 3, 4, 5, 6]
let mut arr = [0, 0, 0, 0, 0];
sink_zeros(&mut arr);
println!("{:?}", arr); // [0, 0, 0, 0, 0]
let mut arr = [0];
sink_zeros(&mut arr);
println!("{:?}", arr); // [0]
let mut arr = [-2];
sink_zeros(&mut arr);
println!("{:?}", arr); // [-2]
let mut arr = [];
sink_zeros(&mut arr);
println!("{:?}", arr); // []
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment