CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Page 1 of 2 12 LastLast
Results 1 to 15 of 17
  1. #1
    Join Date
    Nov 2004
    Posts
    80

    random number that doesn't repeat?

    how do i generate random #'s that do not repeat? below is some small code for generating 20 random #s btw 1 and 20...but i don't know how to make sure the sequence of picking the #s does not repeat...

    Code:
    // rgen.cpp : Defines the entry point for the console application.
    //
    
    #include "stdafx.h"
    #include <ctime>
    #include <cmath>
    #include <cstdlib>
    #include <algorithm>
    #include <fstream>
    #include <iostream>
    #include <iomanip>
    using namespace std;
    
    int main()
    {
    	srand((unsigned)time(0)); 
    	int random_integer; 
    	for(int index=0; index<20; index++)
    	{
    		random_integer = (rand()%20)+1; 
    
    		cout << random_integer << endl; 
    	}
    }

  2. #2
    Join Date
    May 2005
    Posts
    4,954

    Re: random number that doesn't repeat?

    you can do it if you will rand() the indexs look at that code:

    Code:
      int arr&#091;20&#093;={0};
    
      for(int i=0; i<20; i++)
        arr&#091;i&#093;=i+1;
      
      srand((unsigned)time(0)); 
    
      int lastItem = 20;
      for(int index=0; index<20; index++)
      {
        int arrIndex = rand()%lastItem; 
        lastItem--;
        int tmp = arr&#091;lastItem&#093;;
        arr&#091;lastItem&#093; = arr&#091;arrIndex&#093;;
        arr&#091;arrIndex&#093; = tmp;
      }
    always you will get numbers between 1-20 shuffled and not repeated

    Cheers
    If a post helped you dont forget to "Rate This Post"

    My Article: Capturing Windows Regardless of Their Z-Order

    Cheers

  3. #3
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,721

    Re: random number that doesn't repeat?

    you can also use random_shuffle in the C++ library.

    Code:
    int arr[20];
    
    for (int i=0; i<20; ++i)
       arr[i] = i + 1;
    
    std::random_shuffle(arr,arr+20);  // #include <algorithm>

  4. #4
    Join Date
    Nov 2004
    Posts
    80

    Re: random number that doesn't repeat?

    Quote Originally Posted by golanshahar
    you can do it if you will rand() the indexs look at that code:

    Code:
      int arr[20]={0};
    
      for(int i=0; i<20; i++)
        arr[i]=i+1;
      
      srand((unsigned)time(0)); 
    
      int lastItem = 20;
      for(int index=0; index<20; index++)
      {
        int arrIndex = rand()%lastItem; 
        lastItem--;
        int tmp = arr[lastItem];
        arr[lastItem] = arr[arrIndex];
        arr[arrIndex] = tmp;
      }
    always you will get numbers between 1-20 shuffled and not repeated

    Cheers
    thanks...but both
    Code:
    cout << arrIndex <<endl;
    and
    Code:
    cout << tmp<<endl;
    repeats the numbers....

    how would I implement the swap() function? I think If I can swap the randomly generated number with its negative value, I'd never repeat the randomly generated code. Please help.

  5. #5
    Join Date
    Nov 2004
    Posts
    80

    Re: random number that doesn't repeat?

    Thanks Philip,
    But random_shuffle() will still repeat the numbers I think...It will just shuffle the generated random numbers. This helps so one doesn't go thro' the whole process of generating random numbers for say 1000 iterations...

    how would one implement the random_shuffle code for x number of iterations?

  6. #6
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    Re: random number that doesn't repeat?

    You could always keep a list of numbers already generated. If rand() repeats a number just keep adding to it or subtracting from it until you find an unused number.

  7. #7
    Join Date
    Aug 2002
    Location
    Cluj-Napoca,Romania
    Posts
    3,496

    Re: random number that doesn't repeat?

    Make a new vector/list containing the indexe in your collection ( 0 to count-1). Use random_shuffle on this new collection than use it to iterate your data collection.
    Har Har

  8. #8
    Join Date
    May 2005
    Location
    Oregon
    Posts
    3,725

    Smile Re: random number that doesn't repeat?

    Quote Originally Posted by aaadetos
    thanks...but both
    Code:
    cout << arrIndex <<endl;
    and
    Code:
    cout << tmp<<endl;
    repeats the numbers....

    how would I implement the swap() function? I think If I can swap the randomly generated number with its negative value, I'd never repeat the randomly generated code. Please help.
    try this
    Code:
    #include <ctime> 
    #include <cstdlib> 
    using namespace std; 
    int main() 
    { 
     srand((unsigned)time(0)); 
     int random_integer; 
     int lowest=1, highest=10; 
       int range=(highest-lowest)+1; 
       for(int index=0; index<20; index++)
      { 
    	 random_integer = lowest+int(rand()+range*rand()/(RAND_MAX +1.0)); 
    	cout << random_integer << endl; 
       } 
    }
    Last edited by humptydumpty; October 26th, 2005 at 07:54 AM.

  9. #9
    Join Date
    Aug 2000
    Location
    West Virginia
    Posts
    7,721

    Re: random number that doesn't repeat?

    It is not clear to me what you want.

    Do you want the numbers 1 thru 20 generated randomly ? What
    do you want the next iteration ? If you still want the numbers
    1 thru 20, just call random_shuffle again (in a loop)

    Or do you not care what the numbers are ... you just want to
    generate new ones each iteration (with the numbers in the current
    iteration not equal to any of the numbers from previous iterations).

  10. #10
    Join Date
    Nov 2004
    Posts
    80

    Re: random number that doesn't repeat?

    Thanks Philip,
    Yes, calling random_shuffle in a loop will work for x # of iterations. Here is what I want to do for now:

    I want to randomly pick 20 #'s from an array of x elements (say x = 20), in a manner that i don't pick any number from the array of 20 elements more than once. Let the elements in the source array be numbered 1 - 20 for instance.

    Now, If I can randomly pick from this array, I need to implement the swap() function such that it replaces the the number I have picked with its negative conterpart...say i pick #2; it replaces it with -2, so that since the random # generator goes only from 1 - 20, via:
    Code:
    rand()%20+1
    , i 'll never pick the number again.

    Apparently, with the code below, I am not:
    1) selecting from the array layer_array[]
    2) correctly implementing swap()

    Please help.

    Code:
    int main()
    {
    	const int size = 20;
    
    	//initialize all elements of the layer array to zero.
    	int layer_array[size]={0};
    
    	//re-initialize the array elements by incrementing...good if u got a million variables...
    	for(int i=0; i<size; i++)
    		 layer_array[i]=i+1;
    
    	//seed the random # generator using the system time
    	srand((unsigned)time(0)); 
    
    	int random_integer[size] ={0};//initialize the array of random numbers
    
    	for(int index=0; index<size; index++)
    	{
    		random_integer[index] = (rand()%size)+1; 
    		swap(&layer_array[index],&layer_array[index*-1]);
    
    		cout << random_integer[index] << endl; 
    	}
    
    	return 0;
    
    
    }

  11. #11
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    Re: random number that doesn't repeat?

    Quote Originally Posted by aaadetos
    Thanks Philip,
    Yes, calling random_shuffle in a loop will work for x # of iterations. Here is what I want to do for now:

    I want to randomly pick 20 #'s from an array of x elements (say x = 20), in a manner that i don't pick any number from the array of 20 elements more than once. Let the elements in the source array be numbered 1 - 20 for instance.

    Now, If I can randomly pick from this array, I need to implement the swap() function such that it replaces the the number I have picked with its negative conterpart...say i pick #2; it replaces it with -2, so that since the random # generator goes only from 1 - 20, via:
    Code:
    rand()%20+1
    , i 'll never pick the number again.

    Apparently, with the code below, I am not:
    1) selecting from the array layer_array[]
    2) correctly implementing swap()

    Please help.

    Code:
    int main()
    {
    	const int size = 20;
    
    	//initialize all elements of the layer array to zero.
    	int layer_array[size]={0};
    
    	//re-initialize the array elements by incrementing...good if u got a million variables...
    	for(int i=0; i<size; i++)
    		 layer_array[i]=i+1;
    
    	//seed the random # generator using the system time
    	srand((unsigned)time(0)); 
    
    	int random_integer[size] ={0};//initialize the array of random numbers
    
    	for(int index=0; index<size; index++)
    	{
    		random_integer[index] = (rand()%size)+1; 
    		swap(&layer_array[index],&layer_array[index*-1]);
    
    		cout << random_integer[index] << endl; 
    	}
    
    	return 0;
    
    
    }
    That seems like it's more complicated than it needs to be. I don't see in the code where you're ignoring negative numbers either. As I mentioned earlier, if rand results in you picking a number that's already used, just pick the next available number that hasn't been used yet. Alternatively, you could use a dynamic array, vector or list and remove an item entirely once it's selected. Then just use the modulus operator using the current size of the list of available numbers.

  12. #12
    Join Date
    Nov 2004
    Posts
    80

    Re: random number that doesn't repeat?

    i'm not ignoring -ve numbers in the code....
    the swap() is to replace the randomly picked number with a negative one. I'm doing this incorrectly, cos the line:
    Code:
    swap(&layer_array[index],&layer_array[index*-1]);
    gives error c2664....

    What im trying to do forms the backbone of latin hypercube sampling...and things may get sloppy or really slow down system resources if i add and subtract from the array in a piecewise manner...think abt 10,000 iterations....
    Thanks again.

  13. #13
    GCDEF is offline Elite Member Power Poster
    Join Date
    Nov 2003
    Location
    Florida
    Posts
    12,635

    Re: random number that doesn't repeat?

    Quote Originally Posted by aaadetos
    i'm not ignoring -ve numbers in the code....
    the swap() is to replace the randomly picked number with a negative one. I'm doing this incorrectly, cos the line:
    Code:
    swap(&layer_array[index],&layer_array[index*-1]);
    gives error c2664....

    What im trying to do forms the backbone of latin hypercube sampling...and things may get sloppy or really slow down system resources if i add and subtract from the array in a piecewise manner...think abt 10,000 iterations....
    Thanks again.
    But you're never checking for a negative number when setting your random_integer value. Why use swap at all? If you're really set on this procedure, and it really isn't a good approach, why not just code layer_array[index] *= -1? What do you plan on doing when you do detect a negative number in layer_array?

  14. #14
    Join Date
    Jul 2003
    Posts
    147

    Re: random number that doesn't repeat?

    The Boost Random Number Library provides a vast variety of generators and distributions to produce random numbers having useful properties, such as uniform distribution.

    http://www.boost.org/libs/random/index.html

  15. #15
    Join Date
    May 2005
    Posts
    4,954

    Re: random number that doesn't repeat?

    Quote Originally Posted by aaadetos
    thanks...but both
    Code:
    cout << arrIndex <<endl;
    and
    Code:
    cout << tmp<<endl;
    repeats the numbers....

    how would I implement the swap() function? I think If I can swap the randomly generated number with its negative value, I'd never repeat the randomly generated code. Please help.
    you should check the arr in the end! it will always be shuffled after my code add :

    Code:
       for(int index=0; index<20; index++)
        cout << arr[index] << endl;
    and you will see each time randomized unrepeated numbers from the range 1-20

    Cheers
    If a post helped you dont forget to "Rate This Post"

    My Article: Capturing Windows Regardless of Their Z-Order

    Cheers

Page 1 of 2 12 LastLast

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured