mercredi 9 mai 2018

How to check that all random array elements are different

So, I'm trying to pass random integers (between 0 and 11) to the Numbers[] array, but i have to make sure that all 10 of its elements are different. I've tried to pass the numbers first in the array, and then check if there are any numbers that are equal but its not working this way. Here's my code:

#include <iostream>
#include <time.h>
#include <stdlib.h>

using namespace std;

int main()
{
    int Numbers[10];
    srand( time(NULL) );

    for (int i = 0; i < 10; i++ )
    {
        Numbers[i] = rand() % 12;         // First, the integers are passed 
        to the array (They must be between 0 and 11)
        cout << Numbers[i] << endl;        // and printed to the screen
    }

    cout << endl << endl;

    for (int u = 0; u < 10; u++)
    {
        if(Numbers[u] == Numbers[u - 1])      // If there are two equal 
numbers 
     {
       switch (Numbers[u])     // One of them is incremented (But that 
    causes problems as well because it can lead to another pair of equals)
       {
       case 11:     // In case one of them is 11
        Numbers[u]--;
        break;

       default:
        Numbers[u]++;
        break;

       }
     }
     cout << Numbers[u] << endl;
    }

    return 0;
}

Halp!




Aucun commentaire:

Enregistrer un commentaire