OneBite.Dev - Coding blog in a bite size

Shuffle The Elements In An Array In C++

Code snippet for how to Shuffle The Elements In An Array In C++ with sample and detail explanation

Shuffling elements in an array can be crucial when developing games, simulations, and statistical applications in C++. It is a way of arranging the elements of an array (or any collection) into a random order.

Code Snippet for Shuffling Elements in an Array

Let’s first take a look at a simple implementation of shuffling an array in C++:

#include <algorithm>
#include <random>
#include <chrono>
#include <array>

int main() {

    std::array<int, 7> arr = {1, 2, 3, 4, 5, 6, 7};
    
    unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
    std::shuffle(arr.begin(), arr.end(), std::default_random_engine(seed));
    
    for(int i=0; i<arr.size(); i++)
    {
        std::cout<<arr[i]<<" ";
    }
}

Code Explanation for Shuffling Elements in an Array

In this code snippet, we begin by including the necessary C++ libraries for our operation. The <algorithm> library gives us access to various algorithm functions such as std::shuffle which we’ll use for shuffling the array. <random> and <chrono> will provide functionality for generating a random seed necessary for the shuffle, and <array> defines a container for a fixed-size array.

In the main() function, we first declare and initialize an array of seven integers (arr) to be shuffled.

unsigned seed = std::chrono::system_clock::now().time_since_epoch().count(); is used to generate a seed for the shuffle function. We use the std::chrono::system_clock::now().time_since_epoch().count() to produce a different seed each time the program runs, ensuring a different shuffle order every time.

The next line is where the shuffle actually happens: std::shuffle(arr.begin(), arr.end(), std::default_random_engine(seed));. std::shuffle takes three arguments - iterators pointing to the start and the end of the sequence to be shuffled, and a random number generator - which in our case is std::default_random_engine(seed).

Finally, the for loop is used to display the shuffled array.

Run this code, and you’ll see that the elements of the array are shuffled randomly every time the program is executed. That’s a basic overview of how you can shuffle the elements in an array in C++.

c-plus-plus