Shuffle

/**
 * Shuffle an array of numbers.
 */

/*
The Algorithm:
- Nothing much to say, expect that
  swapping each index with another
  random index ensures that every
  index had an equal opportunity to 
  enter any other index.
*/

void shuffle(vector<int> &elements)
{
    srand(time(nullptr));
    for (int i = 0; i < elements.size(); i++)
    {
        int swap_i = rand() % elements.size();
        swap(elements.at(0), elements.at(swap_i));
    }
}

int main()
{
    vector<int> ar = { 1,2,3,4,5,6 };
    shuffle(ar);
    print(ar);
}

Last updated