Rust Program: Calculate differences in Arrays
Write a Rust program that iterates over a vector of arrays [i32; 2] and calculates the difference between the first and second elements of each array.
Sample Solution:
Rust Code:
fn main() {
// Define a vector of arrays
let arrays = vec![[10, 20], [30, 20], [150, 60]];
// Iterate over each array, calculate the difference between the first and second elements,
// and collect the differences into a new vector
let differences: Vec<i32> = arrays
.iter() // Use iter() to borrow the vector
.map(|arr| arr[0] - arr[1]) // Calculate the difference between the first and second elements
.collect(); // Collect the differences into a new vector
println!("Original arrays: {:?}", arrays);
println!("Differences: {:?}", differences);
}
Output:
Original arrays: [[10, 20], [30, 20], [150, 60]] Differences: [-10, 10, 90]
Explanation:
In the exercise above,
- Start by defining a vector 'arrays' containing arrays of type [i32; 2].
- Then, we use the "iter()" method to iterate over each array in the 'arrays' vector.
- Within the "map()" function, we calculate the difference between the first and second elements of each array using array indexing (arr[0] and arr[1]).
- The "map()" function returns an iterator over the calculated differences.
- Finally, we collect these differences into a new vector of type 'Vec
' using the "collect()" method. - Print both the original vector of arrays and the vector containing the calculated differences using "println!()" statements.
Rust Code Editor:
Previous: Rust Program: Extract Some values.
Next: Rust Program: Find Prime numbers in Range.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics