Random Number Generator

I created this program for a class assignment and it works fine but I noticed that sometimes it will return 2 of the same numbers in the same run. Is there a way to make sure that it returns unique integers each run?

#include <iostream>
#include <ctime>
using namespace std;

//function prototypes
void displayArray(int numbers[], int numElements);
int getHighest(int numbers[], int numElements);

int main()
{
//declare array
int randNums[6] = {0};
int sub = 0;
int temp = 0;
int maxSub = 5;
int lastSwap = 0;
char swap = 'Y';

//initialize random number generator
srand(static_cast<int>(time(0)));
//assign random integers from 1 through 54 to the array
for (int sub = 0; sub < 6; sub += 1)
randNums[sub] = 1 + rand() % (54 - 1 + 1);
//end for

while (swap == 'Y')
{
swap = 'N'; //assume no swaps are necessary

sub = 0; //begin comapring with first
//array element

//compare adjacent array elements to determine
//whether a swap is necessary
while (sub < maxSub)
{
if (randNums[sub] > randNums[sub + 1])
{
//a swap is necessary
temp = randNums[sub];
randNums[sub] = randNums[sub + 1];
randNums[sub + 1] = temp;
swap = 'Y';
lastSwap = sub;
} //end if
sub+=1; //increment subscript
} //end while

maxSub = lastSwap; //reset maximum subscript
} //end while

//display array
displayArray(randNums, 6);

//display the highest number in the array
cout << endl << "Highest number: " << getHighest(randNums, 6) << endl;

return 0;
} //end of main

//*****function definitions*****
void displayArray(int numbers[], int numElements)
{
for (int sub = 0; sub < numElements; sub += 1)
cout << numbers[sub] << endl;
//end for
} //end of displayArray function

int getHighest(int numbers[], int numElements)
{
//assign first element'e value to the highest variable
int high = numbers[0];

//begin the search with the second element
int x = 1;

//search for highest number
while (x < numElements)
{
if (numbers[x] > high)
high = numbers[x];
//end if
x += 1;
} //end while

return high;
} //end of getHighest function
just keep track of the numbers that have already been produced. Then if a number is generated twice just throw that value away and run the generator again until you get a unique number.
An alternative is to put all the possible numbers in an array (only one number each, easily done with a for loop), then call std::random_shuffle to shuffle the array contents around.

Then you can pick the first handful of values and you can be sure that they will all be unique.
Thanks, I'll give that a try.
I think this will generation better random numbers:

1
2
3
4
5
6
7
8
9
#include<iostream>
#include<cstdlib>
#include<time.h>
using namespace std;

int main(){
	srand(time(0));
	cout << rand() << endl;
	return 0;}
That's what he's doing, creekist. The problem is he needs numbers within a certain range, and the numbers he picks can't be duplicates.
Topic archived. No new replies allowed.