-3

I have this:

for(int i=1; i<=6; i++)
    cout<<rand()%48+1<<"    ";

How can I edit this script so there's no chance to get a number more than 2 times? (all numbers must NOT repeat)

sfrehse
  • 1,062
  • 9
  • 22
Gelu
  • 67
  • 2
  • 3
  • 12

1 Answers1

0

There is no predefined method for that. If you want to have random numbers in a small value range only, you may safe two copies of each number in an array and then take a random element from the array:

Pseudocode:

AvailableNumbers = array(1, 1, 2, 2, ... 48, 48)
// Shuffle the array:
For i = 1 : 48 {
    swap(AvailableNumbers[i], AvailableNumbers[rand(0, len(AvailableNumbers) - 1])
}

// Take 6 elements:
for i = 1 : 6 {
    print pop(AvailableNumbers[i])
}

Where pop is a stack pop that returns the first element of the array and removes it.

urzeit
  • 2,863
  • 20
  • 36