w3resource

Rust Array Sorting & Slicing

Rust Vectors, Arrays, and Slices: Exercise-8 with Solution

Write a Rust program that creates an array of random integers of size 12. Sort the array in descending order and slice it to get a sub-array containing the top 4 elements. Print the sub-array.

Sample Solution:

Rust Code:

use rand::prelude::*; // Import the necessary traits for random number generation

fn main() {
    // Declare an array to store random integers with size 12
    let mut numbers: [i32; 12] = [0; 12]; // Declare an array initialized with zeros

    // Initialize the random number generator
    let mut rng = thread_rng(); // Create a random number generator instance

    // Generate random integers and add them to the array
    for i in 0..12 {
        numbers[i] = rng.gen_range(1..=100); // Generate a random integer between 1 and 100
    }

    // Sort the array in descending order
    numbers.sort_by(|a, b| b.cmp(a)); // Sort the array using a custom comparator to sort in descending order

    // Slice the array to get a sub-array containing the top 4 elements
    let top_four = &numbers[0..4]; // Slice the array from index 0 to index 3 (inclusive)

    // Print the sub-array containing the top 4 elements
    println!("Top four elements: {:?}", top_four); // Print the sub-array using debug formatting
}

Output:

Top four elements: [99, 88, 73, 57]

Explanation:

Here is a brief explanation of the above Rust code:

  • use rand::prelude::*;: This line imports the necessary traits for random number generation from the "rand" crate.
  • fn main() { ... }: This line defines the main function, which is the entry point of the Rust program.
  • let mut numbers: [i32; 12] = [0; 12];: This line declares an array named 'numbers' of type [i32; 12] (array of integers with size 12) and initializes it with zeros.
  • let mut rng = thread_rng();: This line creates an instance of the random number generator.
  • for i in 0..12 { ... }: This line starts a loop to generate 12 random integers.
  • numbers[i] = rng.gen_range(1..=100);: This line generates a random integer between 1 and 100 using the "gen_range()" method and assigns it to the i-th element of the numbers array.
  • numbers.sort_by(|a, b| b.cmp(a));: This line sorts the 'numbers' array in descending order using the "sort_by()" method with a custom comparator.
  • let top_four = &numbers[0..4];: This line slices the 'numbers' array to get a sub-array containing the top 4 elements.
  • println!("Top four elements: {:?}", top_four);: This line prints the sub-array containing the top 4 elements to the console using debug formatting. The {:?} format specifier prints the elements of the array slice.

Rust Code Editor:

Previous: Rust Array Initialization & Slicing.
Next: Rust Array Filtering & Slicing.

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-vectors-arrays-slices-exercise-8.php