Generate Random Non-Repeating Numbers

One function of a current program I am working on is meant to generate an array of 5 numbers from 0-9, but they can't repeat. I can have {1, 6, 9, 4, 7} but not {1, 1, 2, 3, 4}. When I was playing with it before, I always got stuck in an infinite loop. Now, I'm generating 5 numbers, but the results are not what they are supposed to be. I get no compile errors, but my last numbers generated were {8, 2291952, 3324799, 0, 2291968}. And the 4th place in the array is always zero. Any feedback would be greatly appreciated!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <ctime>
using namespace std;

void generateSetOfNumbers(int numbers[], int size);

int main()
{
  const int SIZE = 5;	     
  int winningNums[SIZE];
  
  srand(time(0));	
  
  generateSetOfNumbers(winningNums, SIZE);
  
  cout << "And the winning numbers are...\n";
  cout << winningNums[0] << " " << winningNums[1] << " " 
       << winningNums[2] << " " << winningNums[3] << " " 
       << winningNums[4] << endl;
  
}

void generateSetOfNumbers(int numbers[], int size)
{
  int tempNum;			// temp variable to hold random number
  bool found;			// used for value in array
  
  numbers[0] = rand() % 10;	// generate the first number in the array
  
    for (int index = 1; index < size; index++)	// loop to place other numbers 
    {
      do
      {
	tempNum = rand() % 10;
	found = false;

	for (int index2 = 0; index2 < size; index2++)
	  if (tempNum == numbers[index2])
	  {
	     found = true;
	     tempNum = numbers[index];
				}
      } while (found != false);	 
    }	 
}
your last numbers generated were {8, 2291952, 3324799, 0, 2291968} because your winningNums array doesn't get initialized, so the numbers in winningNums at first could be any numbers, such as 2291952. Also your generateSetOfNumbers function only assign one value to numbers[0], and it doesn't assign any values to numbers[index] in the for loop.


Take a look at random_shuffle http://cplusplus.com/reference/algorithm/random_shuffle/

First create an array of numbers 0-9, then shuffle it and take the first 5 (or any size <= 10) numbers. That will be your non-repeating numbers.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void generateSetOfNumbers(int arr[], int n)
{
  int p[10] = {0,1,2,3,4,5,6,7,8,9};
  
  //shuffle p
  for (int i=9; i>0; --i)
  {
    //get swap index
    int j = rand()%i;
    //swap p[i] with p[j]
    int temp = p[i];
    p[i] = p[j];
    p[j] = temp;
  }

  //copy first n elements from p to arr
  for (int i=0; i<n; ++i)
    arr[i] = p[i];
}
Oh my goodness, thank you SO much! That is a much more simple solution to the issue. I've been working on this function for almost 4 days & it was absolutely driving me crazy. Thank you again!
Topic archived. No new replies allowed.