Hey, I'm just wanting to know how i can make some code so no random numbers are the same, I've got this so far to get the random numbers and display them but tried this and that and couldn't get it to work.

#include <iostream>

using namespace std;

int main()
{
    int i, j, k, randomNumber[10];
    
    for(i = 0; i < 10; i++)
    {
            
            randomNumber[i] = rand() % 10 + 1;                  
    }
    
    for(k = 0; k < 10; k++)
    {
            cout << randomNumber[k] << ", ";
    }
    
    cin.get();
}

I've tried having other loops inside for loop int i, to check if randomNumber == ..[j] but no output was outputted and yes i did increment j etc. Please help.

Recommended Answers

All 4 Replies

While your adding numbers to the array, just check if the array already has the value, if so, then try again. This seems to do the trick.

#include <iostream>

using namespace std;

int main()
{
    int i, j, k, randomNumber[10];

    for(i = 0; i < 10; i++)
    {

            randomNumber[i] = rand() % 10 + 1;
            for (int q = 0; q < i; ++q)
            {
                    if (randomNumber[q] == randomNumber[i]) // Array already has value
                    {
                            --i; // Retry
                            break;
                    }
            }
    }

    for(k = 0; k < 10; k++)
    {
            cout << randomNumber[k] << ", ";
    }

    cin.get();
}

Hope this helps.

C or C++ program without functions is a nonsense.
The 1st step on the right way: try to select code fragments to define usefull functions, for example:

int isHere(const int array[], int nelem, int number)
{
    for (int i = 0; i < nelem; ++i)
        if (array[i] == number)
            return true;
    return false;
}

const int N = 10;

int main(int argc, char* argv[])
{
    int randomNumber[N];
    int r;

    for (int n = 0; n < N; ++n)
    {
        do {
            r = rand() % N + 1;
        } while (isHere(randomNumber,n,r));
        randomNumber[n] = r;
    }
    for (int i = 0; i < N; ++i)
        cout << i << ".\t" 
        << randomNumber[i] << "\n";
    cout << endl;

    return 0;
}

The suffling is a nice solution.

However let's come back to the assignment. Why r = rand() % N + 1; (or randomNumber[i] = rand() % 10 + 1 as in original code)? Why all numbers in the array must be in 1..N range?

If we have another range, a shuffle method is no good.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.