Shuffle/Sample Data

shuffle code - The mathematics of shuffling / HN

C++ shuffle

Using Fisher-Yates Shuffle Algorithm / wikipedia

#include <iostream>
#include <vector>
#include <algorithm>
 
void print(std::vector<int> const &v)
{
    for (int i: v) {
        std::cout << i << ' ';
    }
}
 
int main()
{
    std::vector<int> v = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    int n = v.size();
 
    for (int i = 0; i < n - 1; i++)
    {
        // generate a random number `j` such that `i <= j < n` and
        // swap the element present at index `j` with the element
        // present at current index `i`
        int j = i + rand() % (n - i);
        std::swap(v[i], v[j]);
    }
 
    print(v);
 
    return 0;
}

std::shuffle

std::vector<int> v = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
std::shuffle(std::begin(v), std::end(v), std::default_random_engine());
std::string in = "hgfedcba", 
            out;
std::sample(in.begin(), in.end(), std::back_inserter(out),
                5, std::mt19937{std::random_device{}()});

Ruby

Written on January 24, 2021, Last update on October 21, 2022
c++ ruby random