Skip to content

Instantly share code, notes, and snippets.

@t-eckert
Last active April 19, 2021 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save t-eckert/a795f24028a64cdc462d3976aa477bf1 to your computer and use it in GitHub Desktop.
Save t-eckert/a795f24028a64cdc462d3976aa477bf1 to your computer and use it in GitHub Desktop.
fn main() {
let mut array = [0, 2, 0, 3, 8];
println!("{:?}", array); // [0, 2, 0, 3, 8]
move_zeroes(&mut array);
println!("{:?}", array); // [2, 3, 8, 0, 0]
}
/// `move_zeroes` function
///
/// Shifts all elements with a value of zero in the `array` to the end of the `array`.
/// Performs this shift in place.
///
/// ``` rust
/// let mut array = [0, 2, 0, 3, 8];
/// move_zeroes(&mut array); // array == [2, 3, 8, 0, 0]
/// ```
fn move_zeroes(array: &mut [i32]) {
for index in 0..array.len() {
if array[index] == 0 {
shift_to_end(array, index)
}
}
}
/// `shift_to_end` function
///
/// Shifts the element at `index_to_shift` to the end of `array`.
/// Performs this shift in place.
///
/// ``` rust
/// let mut array = [1, 2, 3, 4];
/// let index_to_shift = 1;
/// shift_to_end(&mut array, index_to_shift); // array == [1, 3, 4, 2]
/// ```
fn shift_to_end(array: &mut [i32], index_to_shift: usize) {
let value_to_shift = array[index_to_shift];
for index in index_to_shift..array.len() - 1 {
array[index] = array[index + 1];
}
array[array.len() - 1] = value_to_shift;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_moves_zeroes_to_end() {
// Given
let expected = [2, 3, 8, 0, 0];
let mut array = [0, 2, 0, 3, 8];
// When
move_zeroes(&mut array);
// Then
assert_eq!(expected, array);
}
#[test]
fn it_shifts_to_end() {
// Given
let expected = [1, 3, 4, 5, 6, 2];
let mut array = [1, 2, 3, 4, 5, 6];
let index_to_shift = 1;
// When
shift_to_end(&mut array, index_to_shift);
// Then
assert_eq!(expected, array);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment