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 373 views
1 answer 291 views
1 answer 285 views
1 answer 248 views
2 answers 291 views
291 views asked Nov 1, 2021 by avibootz
1 answer 252 views
252 views asked Dec 30, 2017 by avibootz
1 answer 269 views
269 views asked Oct 7, 2019 by avibootz
...