Results 1 to 11 of 11
  1. #1
    apandhi's Avatar
    Join Date
    Apr 2007
    Gender
    male
    Location
    NY
    Posts
    45
    Reputation
    10
    Thanks
    19

    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();
    }

  2. #2
    Void's Avatar
    Join Date
    Sep 2009
    Gender
    male
    Location
    Inline.
    Posts
    3,198
    Reputation
    205
    Thanks
    1,445
    My Mood
    Mellow
    What do you mean it's overlapping? Meaning all the integers stored in the arrays have to be different from each other?

  3. #3
    apandhi's Avatar
    Join Date
    Apr 2007
    Gender
    male
    Location
    NY
    Posts
    45
    Reputation
    10
    Thanks
    19
    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

  4. #4
    why06's Avatar
    Join Date
    Jul 2009
    Gender
    male
    Location
    IBM
    Posts
    4,304
    Reputation
    170
    Thanks
    2,204
    My Mood
    Flirty
    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++;
    }
    }

    "Every gun that is made, every warship launched, every rocket fired signifies, in the final sense, a theft from those who hunger and are not fed, those who are cold and are not clothed. This world in arms is not spending money alone. It is spending the sweat of its laborers, the genius of its scientists, the hopes of its children. The cost of one modern heavy bomber is this: a modern brick school in more than 30 cities. It is two electric power plants, each serving a town of 60,000 population. It is two fine, fully equipped hospitals. It is some fifty miles of concrete pavement. We pay for a single fighter plane with a half million bushels of wheat. We pay for a single destroyer with new homes that could have housed more than 8,000 people. This is, I repeat, the best way of life to be found on the road the world has been taking. This is not a way of life at all, in any true sense. Under the cloud of threatening war, it is humanity hanging from a cross of iron."
    - Dwight D. Eisenhower

  5. #5
    apandhi's Avatar
    Join Date
    Apr 2007
    Gender
    male
    Location
    NY
    Posts
    45
    Reputation
    10
    Thanks
    19
    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 ;"?

  6. #6
    Void's Avatar
    Join Date
    Sep 2009
    Gender
    male
    Location
    Inline.
    Posts
    3,198
    Reputation
    205
    Thanks
    1,445
    My Mood
    Mellow
    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.

  7. The Following User Says Thank You to Void For This Useful Post:

    why06 (05-23-2010)

  8. #7
    r_arraz's Avatar
    Join Date
    Jan 2010
    Gender
    male
    Location
    Your desktop h4x1n up your compooter
    Posts
    370
    Reputation
    16
    Thanks
    76
    My Mood
    Cool

    [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.
    Last edited by r_arraz; 05-22-2010 at 11:13 PM.
    [IMG]https://lh4.ggph*****m/_-aCmMp6G0AQ/S4-phW7LRvI/AAAAAAAAALc/3cpKkpjIgUM/s400/display.php.png[/IMG]




  9. #8
    schim's Avatar
    Join Date
    May 2010
    Gender
    male
    Location
    My chair
    Posts
    367
    Reputation
    10
    Thanks
    115
    My Mood
    Twisted
    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):

    [YOUTUBE]PZZUJ1fxG04[/YOUTUBE]

  10. #9
    Hell_Demon's Avatar
    Join Date
    Mar 2008
    Gender
    male
    Location
    I love causing havoc
    Posts
    3,976
    Reputation
    343
    Thanks
    4,321
    My Mood
    Cheeky
    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
    Last edited by Hell_Demon; 05-23-2010 at 11:49 AM.
    Ah we-a blaze the fyah, make it bun dem!

  11. The Following User Says Thank You to Hell_Demon For This Useful Post:

    Void (05-23-2010)

  12. #10
    Mr.Magicman's Avatar
    Join Date
    Sep 2009
    Gender
    male
    Location
    Sitting in my cave full of thoughts learning Asembly
    Posts
    2,102
    Reputation
    16
    Thanks
    650
    My Mood
    Cold
    i would say you use rand_s ( ) instead its much better

  13. #11
    Hell_Demon's Avatar
    Join Date
    Mar 2008
    Gender
    male
    Location
    I love causing havoc
    Posts
    3,976
    Reputation
    343
    Thanks
    4,321
    My Mood
    Cheeky
    Quote Originally Posted by iopop9 View Post
    i would say you use rand_s ( ) instead its much better
    the safe functions are bullshit =P
    Ah we-a blaze the fyah, make it bun dem!

Similar Threads

  1. [Question]Random Number+Letter Generator
    By Dreamer in forum Visual Basic Programming
    Replies: 4
    Last Post: 03-08-2010, 10:34 PM
  2. Fill with random numbers between 0-12
    By ppl2pass in forum Visual Basic Programming
    Replies: 13
    Last Post: 02-22-2010, 03:00 PM
  3. [Question] Random number below a set number
    By That0n3Guy in forum C++/C Programming
    Replies: 4
    Last Post: 10-24-2009, 06:02 AM
  4. [TuT]Generate Random Number
    By Iamazn1 in forum Visual Basic Programming
    Replies: 1
    Last Post: 10-09-2009, 11:10 PM
  5. Random Number Generator
    By Iam"iDude" in forum Visual Basic Programming
    Replies: 5
    Last Post: 10-02-2007, 04:16 PM