Generating Unique Random Numbers?

Posts 1–11 of 11 · Page 1 of 1
Generating Unique Random Numbers?
Okay guys, here is a problem I'm having. I have an array and I want to generate 10 random integers that dont overlap between 1 and 25. This is what I have but it keeps overlapping. Any Ideas?
Code:
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <conio.h>

using namespace std;

int main(){
	int question[9];
	unsigned seed = time(NULL);
	srand(seed);
	for(int i=0; i < 10; i++){
		question[i]=0;
	}
	for(int i=0; i < 10; i++){
		question[i] = rand()/100%(10)+ 1;
			//rand();
		for(int x=0; x < 10; x++){
			if(i==x) continue;
			else{
				while(question[i]==question[x]){
					question[i] = rand()/100%(10)+ 1;
				}
			}
		}
		cout << question[i] << endl;
	}
	getch();
}
What do you mean it's overlapping? Meaning all the integers stored in the arrays have to be different from each other?
Quote Originally Posted by Void View Post
What do you mean it's overlapping? Meaning all the integers stored in the arrays have to be different from each other?
Yea, for example there cant be two 7s
U need to create an array of every unique number u generate. WHen u generate a new number compare it to all the entries in that array. if it comes up that none of them are a match add that number to the array. if not recalculate a rand # untill you get a unique one
Code:
int numbersfound = 1;
//generate 1st number
int numbers[10];
numbers[0] = gen_num ;
while(numbersfound < 10)
{
//generate number here
for(int i = 0; i < numbersfound; i++)
{
if(generated_number == numbers[i])break;
if(i == numbersfound-1)numbersfound++;
}
}
Quote Originally Posted by why06 View Post
U need to create an array of every unique number u generate. WHen u generate a new number compare it to all the entries in that array. if it comes up that none of them are a match add that number to the array. if not recalculate a rand # untill you get a unique one
Code:
int numbersfound = 1;
//generate 1st number
int numbers[10];
numbers[0] = gen_num ;
while(numbersfound < 10)
{
//generate number here
for(int i = 0; i < numbersfound; i++)
{
if(generated_number == numbers[i])break;
if(i == numbersfound-1)numbersfound++;
}
}
Im sorry but what do I put here:
"numbers[0] = gen_num ;"?
[LEECHED]
I got some code here I found that works, courtesy of bling bling vr6 for their source code involving generating random numbers with validation for unique numbers, and Infarction for cleaning up his code so that it would work properly . I mainly just inserted the LinearSearch function and replaced one of your for loops with the for loop Infarction fixed. Just google "c++ unique random numbers" and I got it from the first result. Anyway here it is .

Code:
#include <iostream>
#include <ctime>
#include <conio.h>

using namespace std;

int LinearSearch(const int number[], int value) //Determines if the given number already exists
{
    int index = 0;
    int position = -1; 
    bool found = false; //Bool for duplicate number

    while (index < 15 && !found)
    {
        if (number[index] == value) //If any integer in the list is equal to the new
        {                           //random number
            found = true; //Sets bool to true because it found a duplicate
            position = index; //Sets position to where it found the duplicate
        }
        index++; //Increments through the list of numbers
    }
    return position; //Returns -1 if number is unique, else if duplicate is found
}



int main(){
    int question[14]; //List of numbers
    int temp; //Random number holder
    unsigned seed = time(NULL);
    srand(seed);

    for(int i=0; i < 15; i++){
        question[i]=0; //Set all integers in array to 0
    }

      for(int i = 0; i < 15; i++)
      {
      do {
      temp = rand() % 15 + 1; // Generate random number
      } 
      while (LinearSearch(question, temp) != -1); // Call function to check for duplicates of randomly generated number
                                                  //Repeats proccess until return value is equal to -1
      question[i] = temp; // If it's unique then save the number
      cout << question[i] << endl; //Print to screen
      }
    getch(); //Wait for user to press any key
    }
Please tell me if it's not ok to leech this.
Sorry for the wait, it's late and I'm tired..

[php]
#include <iostream>
#include <ctime>

using namespace std;

int question[10];

int main()
{
srand(time(NULL));

while(true)
{
gen:
//generate
for(int i=0;i<9;i++)
{
question[i] = rand()%25;
}
//generate

for(int i=0;i<9;i++)
{
for(int n=0;n<9;n++)
{
if(i != n)
{
if(question[i] == question[n])
{
goto gen;
}
}
}
}
break;
}


for(int i=0;i<9;i++)
{
cout << question[i] << endl;
}

cin.get();
}
[/php]

It keeps generating until it gets a set with all different numbers. Not sure if this is what you're looking for..

Sorry if you hate "goto"s, I couldn't think of any other clean way of breaking out of a crap load of loops in a single line.
Like r_arraz said, using the rand();
Function will get you an array of (pseudo) random numbers
Here is an very easy tut on how to do it, and some theory as well(youtube):

Code:
class UniqueRand
{
private:
    int min, max, OptionsLeft;
    bool bUsed[];

public:
    void Initialize(int min=0, int max=1000)
    {
        this.min = min;
        this.max = max;
        bUsed = new bool[max-min];
    }
    int Random()
    {
        for(int i=0; i<max-min; i++)
        {
            if(bUsed[i]==false)
            {
                 OptionsLeft++;
            }
        }
        if(OptionsLeft==0)
        {
             return -1;
        }
        int retval = (rand()%(max-min));
        while(bUsed[retval]==true)
        {
            retval = (rand()%(max-min));
        }
        bUsed[retval]=true;
        OptionsLeft=0;
        return (retval+min);
    }
    void Reset()
    {
        for(int i=0; i<max-min; i++)
        {
            bUsed[i]=false;
        }
    }
};
usage:
Code:
UniqueRand myRandGen;
myRandGen.Initialize(20,500);
int mygeneratedrang = myRandGen.Random();
note: written in here, so untested meaning it will probably throw some errors at you =P
i would say you use rand_s ( ) instead its much better
Quote Originally Posted by Mr.Magicman View Post
i would say you use rand_s ( ) instead its much better
the safe functions are bullshit =P
Posts 1–11 of 11 · Page 1 of 1
This thread is closed for replies.

Similar Threads

Tags for this Thread

None

Talk with us