so im basically new at c++.
i need to generate 20 entries randomly from 1-20, and each number must be unique.
i was able to generate the number but i don't know how to make them unique.
any suggestions?

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

using namespace std;

int array[20];

int main ()
{
    srand(time(NULL));
    for (int i=0; i<20; i++)
    {
        int x;
        x=rand()%20+1;
        cout << array[0]<<x<< " ";
    }
    return 0;
}

Try putting the numbers 1-20 into your array first (in order), and then shuffling it. (Hint: start by picking a random element-index and swapping that element with the last element in the array, now you have only 19 more elements to deal with, etc.)

If you can use STL then you could use the random shuffle algo. Since I don't think you can use that algo you would need to use two for loops. One to populate the array with the numbers 1-20 and the other to swap the elements in the array around. When you shuffle the element around go through the array for each element swap it with a random index in the array.

If you can use STL then you could use the random shuffle algo. Since I don't think you can use that algo you would need to use two for loops. One to populate the array with the numbers 1-20 and the other to swap the elements in the array around. When you shuffle the element around go through the array for each element swap it with a random index in the array.

thanks nathan, i can't use STL but i'll do by creating two loops.thanks.

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.