c++algorithmrandomnumberssrand

C++ rand() each number only once


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"; 

Solution

  • 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.