I need something like rand() but I want each number only once.
In example I have 10 ".txt" files that are named as numbers (1-10).I want to read what is inside there and cout it, but randomly.
I don't want 1.txt -> 2.txt -> 3.txt -> ...but something random like
5.txt -> 4.txt -> 1.txt -> ...
and each number should only come up once
Is there an "easy" way to do this?
string Path = "./Questions_Niko/" + random + ".txt";
Best Answer
Create a vector of the numbers you want and use std::shuffle.
Then iterate over the vector in order.
There are several approaches. For example you can use standard algorithm std::random_shuffle
declared in header <algorithm>
For example
#include <algorithm>#include <iterator>//...int main(){int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };std::random_shuffle( std::begin( a ), std::end( a ) );for ( int i : a ){// some stuff}}
The other way is to use standard class std::bitset
and set the corresponding bit in the set for already selected number.
Create a hashmap of each result. If it does exist regenerate it.
std::random_shuffle
likely suits your needs, but if you can't/ don't want to, you can borrow mshuffle:
int mix[10];int swap;for (i = 9; i >= 0; i--) {int j = rand() % i;swap = mix[j];mix[j] = mix[i];mix[i] = swap;}
Assuming you've called srand()
first, this mixes up the array named mix
. It need not be an array of int
s.
Using srand()
will solve your problem
//Randomize seedsrand(time(NULL));for(i to size)Arr[i]=rand()%size