Thread: unique random nums - i can't sleep - i've got to know

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    3

    Question unique random nums - i can't sleep - i've got to know

    been working on this simple problem for 3 days. totally frustrated.
    please, can anybody help me generate unique random nums?
    only been programming w/ c++ 4-1/2 months. have read the tuts, coder, but don't understand. anyway, here's my code, and it won't generate unique nums.

    //UNIQUE

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

    void main()
    {
    int randomNums[5] = {-1};

    int index = 0;

    int temp = 0;

    char found = 'n';

    int i = 0;

    srand(time(NULL) );

    while (index < 5)
    {

    found = 'n';

    for (i; i < 5 ; i = i + 1)
    {
    temp = 1 + rand() % (10 - 1 + 1);
    if (randomNums[index] == temp)
    {

    found ='y';
    }
    else
    if(found = 'n')
    {
    randomNums[index] = temp;
    index = index + 1;
    }
    }
    }
    cout<< randomNums[0]<< endl;
    cout<< randomNums[1]<< endl;
    cout<< randomNums[2]<< endl;
    cout<< randomNums[3]<< endl;
    cout<< randomNums[4]<< endl;
    }

  2. #2
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    I'm not sure what range of numbers you were trying to get, but something like this should work -

    Code:
    #include <iostream> 
    #include <cstdlib> 
    #include <ctime> 
    
    
    using namespace std;
    
    int main() 
    { 
    	int randomNums[5] = {-1,-1,-1,-1,-1}; 
    
    	int index = 0; 
    	int temp = 0; 
    
    	char found = 'n'; 
    
    	int i = 0; 
    	srand(time(NULL) ); 
    
    	while (index < 5) 
    	{ 
    		found = 'n'; 
    		temp = 1 + rand()%10; 
    		
    		for(i=0;i<index;i++)
    		{
    			if (randomNums[i]==temp)
    			{
    				found ='y';
    				break;
    			}
    		}
    
    		if(found=='n')
    			randomNums[index++]=temp;
    	}
    
    	for(i=0;i<5;i++)
    		cout<< randomNums[i]<< endl; 
    
    	return 0;
    	
    }
    zen

  3. #3
    Registered User
    Join Date
    Nov 2001
    Posts
    3
    perfect!!!!!!!
    thanks sooooooo much, zen.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. generating 10 unique random numbers in C
    By creeping death in forum C Programming
    Replies: 4
    Last Post: 01-28-2009, 11:23 AM
  2. Generating 100k to 1 million unique random numbers
    By Ariod in forum C Programming
    Replies: 4
    Last Post: 08-26-2005, 12:59 PM
  3. Another brain block... Random Numbers
    By DanFraser in forum C# Programming
    Replies: 2
    Last Post: 01-23-2005, 05:51 PM
  4. Unique random numbers
    By aydin in forum C Programming
    Replies: 7
    Last Post: 11-23-2004, 12:21 PM
  5. Unique Random Numbers in 2D Array
    By kssjbr in forum C++ Programming
    Replies: 2
    Last Post: 08-06-2003, 02:45 AM