Since you want an array or vector of shuffled integer values, use std::shuffle
to shuffle a vector (or whatever) initialized with sequential values.
#include <iostream>
#include <vector>
#include <random>
#include <algorithm>
#include <numeric>
int main() {
std::random_device rd;
std::mt19937 rng(rd()); // seed rng using rd
std::vector<int> data(3); // create a 3-entry vector
std::iota(data.begin(), data.end(), 0); // fill with sequence
std::shuffle(data.begin(), data.end(), rng); // mix entries using rng
// dump the result
for(auto r : data) { std::cout << r << ' '; }
std::cout << '\n';
}
The outputs of 3 executions:
1 0 2
2 1 0
2 0 1
Here is a version which doesn't rely so much on the standard C++ library, and uses the C-runtime's crappy random number generator, just because I didn't have access to Rndom's source code, which is undoubtedly of a proprietary nature, so this is quite understandable:
#include <iostream> // only for std::cout
#include <cstdlib> // for srand, rand
#include <ctime> // for time
namespace shuffle {
using size_t = decltype(sizeof(1));
bool Srndom() {
std::srand(std::time(0));
return true;
}
int Rndom(int low, int high) {
static bool init = Srndom();
return std::rand() % (high - low + 1) + low;
}
template <typename T>
void Shuffle(T* pdata, size_t N) {
for(size_t i=0; i<N-1; ++i) {
const int swap_idx = Rndom(i, N-1);
if(swap_idx != i) {
const T t = pdata[i];
pdata[i] = pdata[swap_idx];
pdata[swap_idx] = t;
}
}
}
template <typename T, size_t N>
void Shuffle(T (&data)[N]) {
Shuffle(data, N);
}
template <typename T>
void Series(T* pdata, size_t N, T start) {
for(size_t i=0; i<N; ++i) {
pdata[i] = start++;
}
}
template <typename T, size_t N>
void Series(T (&data)[N], T start) {
Series(data, N, start);
}
}
int main() {
using namespace shuffle;
int Data[4]; // I guess you actually want 4
Series(Data, 1); // and maybe to start at 1.
Shuffle(Data); // Shuffle Data's entries.
// Dump Data's entries
for(size_t i=0; i<sizeof(Data)/sizeof(Data[0]); ++i) {
std::cout << Data[i] << ' ';
}
std::cout << '\n';
}
The outputs of 3 executions (over 1 second apart):
2 3 1 4
4 2 3 1
2 4 3 1