-
-
Save jimblandy/0d5dc4ebc8133e6fdc85c0d6997e0395 to your computer and use it in GitHub Desktop.
Rust code shared from the playground
This file contains hidden or 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
#![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