How can I generate random numbers without duplicates assuming I have a function that will generate random integers from x to y inclusive.
Thanks.
How can I generate random numbers without duplicates assuming I have a function that will generate random integers from x to y inclusive.
Thanks.
Keep a record of all previous random numbers and reject any new random numbers that match one of these.
To add to what sorenson said. A binary tree will allow you to do this quickly. Call rand in a loop and pass the output to your binary tree insert func which you have coded to reject duplicates. End the loop when the tree contains the right number of values. You could also use stl set or stl map to do this if that sounds like too much work for you.
Free the weed!! Class B to class C is not good enough!!
And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi
If you can't be arsed to code a binary tree class then: if you know how many numbers you need, create an array of that size and fill it with 1, 2, 3... and swap random pairs a few thousand times (trivial for a PC). For more variety instead of having each slot one greater than the last make it a random amount bigger. Like:
If you have no random () function (like MSVC). The definition is as follows:Code:void swap (int *one, int *two); void main (void) { int i; int num [20]; int newNum = 1; int swapOne; int swapTwo; for (i = 0; i < 20; i++) { num [i] = newNum; newNum += (random (5)); } for (i = 0; i < 9000; i++) { swapOne = random (20); do { swapTwo = random (20); } while (swapTwo == swapOne); // Avoid duplicates. swap (num + swapOne, num + swapTwo); // Or use &num [swapOne], etc. } } void swap (int *one, int *two) { int temp = *one; *one = *two; *two = temp; }
Code:int random (int r) { return (rand () % r); }
Last edited by samGwilliam; 02-09-2002 at 07:17 PM.
MSVC++ 6.0