Rust Array Mapping Guide
Rust Arrays: Exercise-7 with Solution
Write a Rust program to create an array of integers with size 5 and initialize it with random values. Map each element of the array to its square 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 5 and initialize it with random values
let mut arr: [i32; 5] = [0; 5]; // Declare an array of type i32 (integer) with a size of 5 and initialize it with zeros
let mut rng = rand::thread_rng(); // Initialize the random number generator
// Generate random values and fill the array
for i in 0..5 { // 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
}
// Map each element of the array to its square
let squared_array: Vec = arr.iter() // Convert the array into an iterator
.map(|&x| x * x) // Use the map method to square each element of the iterator
.collect(); // Collect the squared elements into a new vector
// Print the resulting array with each element squared
println!("Squared Array: {:?}", squared_array); // Print the resulting vector using debug formatting
}
Output:
Squared Array: [4489, 5476, 361, 3600, 5184]
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; 5] = [0; 5];: This line declares an array named 'arr' of type 'i32' (integer) with a size of 5 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..5 { ... }: 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 squared_array: Vec
= arr.iter() ...: This line maps each element of the array arr to its square using the "map()" method on an iterator over the array elements. The "map()" method applies the specified closure to each element of the iterator. - println!("Squared Array: {:?}", squared_array);: This line prints the resulting array with each element squared to the console using debug formatting.
Rust Code Editor:
Previous: Rust Array Filtering Guide.
Next: Rust Array Reversal 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-7.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics