简体   繁体   中英

I'm trying to get a random order of numbers 1:16 using srand and rand. The code works as expected but only up to the 12th iteration.Why?

#include "stdafx.h"
#include <iostream>
#include <string>
#include <cstdlib>
#include <cmath>
#include <ctime>
#include <algorithm>
#include <iterator>


int _tmain(int argc, _TCHAR* argv[])
{
    using namespace std;   

    int ord[] = {
             0,0,0,0,
             0,0,0,0,
             0,0,0,0
            };

    srand(time(NULL));

    int i = 0;

    do{
        int r = rand() % 16 + 1;
        bool exista =( find(begin(ord), end(ord), r) != end(ord));
        if (!exista){
            ord[i] = r;
            cout << ord[i] << endl;
            i++;
            cin.get();
        }

    } while (find(begin(ord), end(ord), 0) != end(ord));
    return 0;
}

After 12 numbers ,the program exits and I cannot understand why ,it should be after 16 iterations .

The reason is that you have only 12 zeros in ord and when they're exhausted (in your case filled with unique values from 1 to 16 the loop stops (because there are no more zeros to find.

changing the declaration of ord to

int ord[] = {
         0,0,0,0,
         0,0,0,0,
         0,0,0,0,
         0,0,0,0
        };

or

int ord[16] = {0};

By the way if you only want to shuffle those numbers randomly I'd suggest to use random_shuffle from <algorithm> .

You defined an array size of 12 and you are filling the array ord[] with the randomized integers r . Even though you set the random num generator to run for 16 iterations, your array will be filled on the twelfth iteration. Just increase your array size.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM