jeudi 27 avril 2017

Non repeating random numbers in C++

I need to create an array that has a shorter length than the numbers' range that I have to choose among. In the example I have an array made by 10 int and the range is between 20 and 50. That means that most of the asnwers (found on various websites) to this question ("use the shuffle algoritm") couldn't work.

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <time.h>

using namespace std;

int main() {

const int N = 10;
int arr[N];

srand(time(0));

// Just creates the array, but with repetitions
// for (int i=0; i<N; i++) {
//     arr[i] = (rand()%31)+20;
//     }

for (int i = 0; i <= N; ++i) {
    bool valid = true;
    do {
        arr[i] = ((rand()%31)+20);
        for (int j = 0; j < i; ++j) {
            if (arr[i] == arr[j])
                valid = false;
            else
                valid = true;
        }
    } while(!valid);
}

With the "else" I check the previous value and, if it's the same, it's changed. But if the same numbers are more far than just the previous one, this algoritm doesn't change the last one because the "else" of a previous right number ends the while. If I remove the else, I remain stuck in the cicle, changing every time the number.




Aucun commentaire:

Enregistrer un commentaire