Thread: yet another random num guestion

  1. #1
    Registered User
    Join Date
    Jan 2002
    Posts
    7

    yet another random num guestion

    Im trying to get a group 20 random numbers with no duplicates
    I thought my code is right to do this, but i still am getting duplicates. What changes should I make? Any help is greatly appreciated.

    Here my random number function:

    void random (info data)
    {
    int count, counta, n, go, num[20];


    for (count = 0; count < 20; count++) num[count] = 0;

    srand ((unsigned)time(NULL));

    for (count = 0; count < 20; count ++)
    {
    go = 0;

    do
    {
    n = (rand() % 50);

    for (counta = 0; counta < 20; counta++)
    {
    if (num[counta] == n) go = 0;
    else go = 1;
    }
    }
    while (go ==0);
    num[count] = n;
    }

    out (num, data);
    }

  2. #2
    Registered User
    Join Date
    Dec 2001
    Posts
    421
    Firstly, if you're going to put code in your posts, please put them in [ code ][ /code ] tags (without the spaces).

    Here's a possible solution:

    Code:
    #include <iostream.h>
    #include <stdlib.h>
    #include <time.h>
    #include <memory.h>
    
    #define RAND_SIZE	100
    #define NUMBERS		20
    
    int main(void)
    {
    	int flags[RAND_SIZE];
    	int numbers[NUMBERS];
    	int i;
    
    	memset(flags, 0, sizeof(flags));
    	memset(numbers, 0, sizeof(numbers));
    
    	srand(time(NULL));
    
    	for(i = 0; i < NUMBERS; i++)
    	{
    		int num = rand() % RAND_SIZE;
    
    		if(flags[num])
    		{
    			i--;
    			continue;
    		}
    
    		flags[num] = 1;
    		numbers[i] = num;
    	}
    
    	cout << "The random numbers are:\n";
    
    	for(i = 0; i < NUMBERS; i++)
    	{
    		cout << numbers[i] << endl;
    	}
    
    	return(0);
    }
    Quidquid latine dictum sit, altum sonatur.
    Whatever is said in Latin sounds profound.

  3. #3
    Registered User
    Join Date
    Jan 2002
    Posts
    7
    thanks for the help and the tip about the [ code ] tags

  4. #4
    Registered User
    Join Date
    Dec 2001
    Posts
    421
    no problem
    Quidquid latine dictum sit, altum sonatur.
    Whatever is said in Latin sounds profound.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. a searching tree
    By lindaonline15 in forum C++ Programming
    Replies: 2
    Last Post: 10-15-2008, 06:06 AM
  2. Another brain block... Random Numbers
    By DanFraser in forum C# Programming
    Replies: 2
    Last Post: 01-23-2005, 05:51 PM
  3. help! fifo read problem
    By judoman in forum C Programming
    Replies: 1
    Last Post: 08-16-2004, 09:19 AM
  4. Problem Using bsearch
    By Zildjian in forum C Programming
    Replies: 4
    Last Post: 11-13-2003, 08:14 PM
  5. Optimization of code
    By dpro in forum C++ Programming
    Replies: 5
    Last Post: 10-28-2002, 04:01 PM