Skip to content

Instantly share code, notes, and snippets.

@jimblandy
Forked from anonymous/playground.rs
Created November 27, 2017 00:54
Show Gist options
  • Save jimblandy/0d5dc4ebc8133e6fdc85c0d6997e0395 to your computer and use it in GitHub Desktop.
Save jimblandy/0d5dc4ebc8133e6fdc85c0d6997e0395 to your computer and use it in GitHub Desktop.
Rust code shared from the playground
#![allow(unused_variables)]
/// Given an array of `true` or `false` values (the type `bool`),
/// return a new array whose `i`'th element is true iff `array[i]`
/// and `array[i+1]` are different.
///
/// Rust numbers array elements starting with zero. Since `array` has 80
/// elements, its first element is `array[0]`, and its last element is
/// `array[79]`. The function's return value is similar.
///
/// Given the definition above, the final element of the result would have to
/// compare `array[79]` to `array[80]`, but there is no `array[80]`; if you try
/// to access that, Rust panics. So instead, make the final comparison "wrap
/// around" to the front, and just compare `array[79]` with `array[0]`.
fn find_changes(array: [bool; 80]) -> [bool; 80] {
let mut arr: [bool; 80] = [false; 80];
for i in 0..79 {
arr[i] = array[i] != array[i+1];
}
arr[79] = array[79] != array[0];
arr
}
fn main() {
let mut a = [false; 80]; // Make an array holding 80 `false` values.
a[10] = true; // Change two of them.
a[11] = true;
for i in 0..80 {
println!("{}", find_changes(a)[i]);
}
}
// let b = find_changes(a);
// for i in 0..80 {
// if i == 9 {
// assert_eq!(b[i], true);
// } else if i == 11 {
// assert_eq!(b[i], true);
// } else {
// assert_eq!(b[i], false);
// }
// }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment