Rust Array Filtering Guide
Rust Arrays: Exercise-6 with Solution
Write a Rust program to create an array of integers with size 9 and initialize it with random values. Filter out even numbers from the array and print the resulting array.
Sample Solution:
Rust Code:
use rand::Rng; // Import the rand crate to generate random numbers
fn main() {
// Define an array with a size of 9 and initialize it with random values
let mut arr: [i32; 9] = [0; 9]; // Declare an array of type i32 (integer) with a size of 9 and initialize it with zeros
let mut rng = rand::thread_rng(); // Initialize the random number generator
for i in 0..9 { // Iterate over each index of the array
arr[i] = rng.gen_range(1..101); // Generate a random integer between 1 and 100 and assign it to the current index
}
// Filter out even numbers from the array
let filtered_array: Vec<i32> = arr.iter() // Convert the array into an iterator
.copied() // Make a copy of each element of the iterator (necessary for array elements, which are references)
.filter(|&x| x % 2 != 0) // Use the filter method to keep only elements that are not even (have a remainder when divided by 2)
.collect(); // Collect the filtered elements into a new vector
// Print the resulting array with even numbers filtered out
println!("Filtered Array: {:?}", filtered_array); // Print the resulting vector using debug formatting
}
Output:
Filtered Array: [19, 51, 61, 85, 63, 7, 59]
Explanation:
Here is a brief explanation of the above Rust code:
- use rand::Rng;: This line imports the rand::Rng trait from the "rand" crate, which provides functions for generating random numbers.
- fn main() {: This line defines the main function, which is the entry point of the Rust program.
- let mut arr: [i32; 9] = [0; 9];: This line declares an array named 'arr' of type 'i32' (integer) with a size of 9 and initializes it with zeros.
- let mut rng = rand::thread_rng();: This line initializes the random number generator by creating a thread-local generator.
- for i in 0..9 { ... }: This line starts a for loop that iterates over each index of the array arr.
- arr[i] = rng.gen_range(1..101);: This line generates a random integer between 1 and 100 using the gen_range method of the random number generator 'rng', and assigns it to the current index 'i' of the array 'arr'.
- let filtered_array: Vec<i32> = arr.iter() ...: This line filters out even numbers from the array 'arr' using the "filter()" method on an iterator over the array elements. The "filter()" method keeps only elements that are not even (have a remainder when divided by 2).
- println!("Filtered Array: {:?}", filtered_array);: This line prints the resulting array with even numbers filtered out to the console using debug formatting.
Rust Code Editor:
Previous: Rust Array Search Guide.
Next: Rust Vector Operations Guide.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/rust/collections_and_data_structures/rust-arrays-exercise-6.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics