36 lines
926 B
Rust
36 lines
926 B
Rust
fn rotate(array: &mut [usize], start: usize) {
|
|
array.swap(start, start + 1);
|
|
array.swap(start + 1, start + 2);
|
|
}
|
|
|
|
pub fn larry_array(mut array: Vec<usize>) -> Result<bool, String> {
|
|
let mut next = 1;
|
|
|
|
while next <= array.len() {
|
|
let mut index = match array.iter().position(|&e| e == next) {
|
|
Some(x) => x,
|
|
None => {
|
|
return Err(
|
|
"The array must contains all the numbers from 1 to the array's length"
|
|
.to_owned(),
|
|
);
|
|
}
|
|
};
|
|
|
|
if index != next - 1 && next == array.len() - 1 {
|
|
return Ok(false);
|
|
}
|
|
|
|
while index != next - 1 {
|
|
let start = std::cmp::max(index - 2, next - 1);
|
|
let end = start + 2;
|
|
rotate(&mut array, start);
|
|
index = (end + index - 1) % end;
|
|
}
|
|
|
|
next += 1;
|
|
}
|
|
|
|
Ok(true)
|
|
}
|