w3resource

Rust Array Reversal Guide

Rust Arrays: Exercise-8 with Solution

Write a Rust program to create an array of characters with size 7 and initialize it with random characters. Reverse the elements of the array and print the reversed array.

Sample Solution:

Rust Code:

use rand::distributions::Alphanumeric;
use rand::{thread_rng, Rng};

fn main() {
    let mut arr: [char; 7] = ['a'; 7];
    let mut rng = thread_rng();

    for i in 0..7 {
        // Generate a random alphanumeric character and convert it to char
        arr[i] = rng.sample(Alphanumeric) as char;
    }

    arr.reverse();

    println!("Reversed Array: {:?}", arr);
}

Output:

Reversed Array: ['Z', 'Q', 'Y', 'o', 'X', 't', '9']

Explanation:

Here is a brief explanation of the above Rust code:

  • use rand::distributions::Alphanumeric;: This line imports the "Alphanumeric" distribution from the rand::distributions module. This distribution is used for generating random alphanumeric characters.
  • use rand::{thread_rng, Rng};: This line imports the "thread_rng()" function and the 'Rng' trait from the 'rand' crate. "thread_rng()" function creates a thread-local random number generator, and 'Rng' trait provides methods for generating random numbers.
  • fn main() { ... }: This line defines the main function, which serves as the entry point of the Rust program.
  • let mut arr: [char; 7] = ['a'; 7];: This line declares an array named 'arr' of type 'char' (character) with a size of 7 and initializes all elements with the character 'a'.
  • let mut rng = thread_rng();: This line initializes the random number generator by creating a thread-local generator using the "thread_rng()" function.
  • for i in 0..7 { ... }: This line starts a for loop that iterates over each index of the array 'arr'.
  • arr[i] = rng.sample(Alphanumeric) as char;: This line generates a random alphanumeric character using the "sample()" method with the "Alphanumeric" distribution, then converts it to a 'char' type and assigns it to the current index i of the array 'arr'.
  • arr.reverse();: This line reverses the order of elements in the array 'arr'.
  • println!("Reversed Array: {:?}", arr);: This line prints the reversed array 'arr' to the console using debug formatting.

Rust Code Editor:

Previous: Rust Array Mapping Guide.
Next: Rust Array Concatenation Guide.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

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://w3resource.com/rust/collections_and_data_structures/rust-arrays-exercise-8.php