How to random (shuffle) an array of ints in C++

2 Answers

0 votes
#include <iostream>
#include <algorithm>
#include <ctime>
 
using std::cout;
using std::endl;
 
int main()
{
    int arr[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
 
    std::srand(std::time(0));
 
    std::random_shuffle(std::begin(arr), std::end(arr));
 
    for (auto i : arr) {
        cout << i << " ";
    }
 
    cout << endl;
}
 
 
/*
run:
 
6 2 5 9 4 1 8 0 7 3 
 
*/

 



answered Feb 20, 2018 by avibootz
edited May 17, 2024 by avibootz
0 votes
#include <iostream>
#include <algorithm>
#include <ctime>
 
using std::cout;
using std::endl;
 
int main()
{
    int arr[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    int size = sizeof(arr) / sizeof(arr[0]);

    std::srand(std::time(0));
 
    std::random_shuffle(arr, arr + size);
 
    for (auto i : arr) {
        cout << i << " ";
    }
 
    cout << endl;
}
 
 
 
/*
run:
 
7 0 2 9 8 5 3 4 1 6 
 
*/

 



answered May 17, 2024 by avibootz

Related questions

2 answers 236 views
1 answer 183 views
1 answer 188 views
1 answer 170 views
1 answer 166 views
166 views asked Dec 30, 2017 by avibootz
2 answers 171 views
171 views asked Nov 1, 2021 by avibootz
1 answer 189 views
189 views asked Oct 7, 2019 by avibootz
...