Last active
December 23, 2018 21:35
-
-
Save AnthonyMikh/55540519dc92d1163d89371e24efa8fb to your computer and use it in GitHub Desktop.
Рекурсивное решение задачи №148 от UniLecs (Обработка массива)
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
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
Playground: https://play.rust-lang.org/?gist=693c6deb2a7307b02d44d83ca4143a5d
Условия: https://tgraph.io/Anons-148-Obrabotka-massiva-12-19