does anybody know any algorithom that will chose k numbers form n numbers where k<n(random)
i want to create a lottery drawing system
does anybody know any algorithom that will chose k numbers form n numbers where k<n(random)
i want to create a lottery drawing system
There are a couple of ways to go about it. The simplest is to create an array of all possible numbers, shuffle the array, then either pop or shift off the required number of choices. (In PHP, you can do the shuffling with array_rand().) Since pseudorandom number generators are far from perfect (and array_rand() uses mt_rand()), this doesn't actually create an "every ticket can win" scenario. Slightly (and only slightly) more complex, but likely to be fairer, is to create two different shuffled arrays of the numbers, pop or shift off the required number of selections from one array and use that result as the index to fetch the drawn number from the other array.
“Beware of bugs in the above code; I have only proved it correct, not tried it.” --Donald Knuth
"It was as if its architects were given a perfectly good hammer and gleefully replied, 'neat! With this hammer, we can build a tool that can pound in nails.'" -- Alex Papadimoulis (on TheDailyWTF.com)
Code:n = number of balls in bucket k = number of balls to draw bucket = Array( n ); winners = Array( k ); for( i = 0 , j = 1 ; i < n ; j++ , i++ ){ bucket[ i ] = j ; # throw the numbered balls into the bucket... } for( i = 0 ; i < k ; i++ ){ pick = rand( i , n - 1 ) ; # pick from 'remaining balls' ... number between i and n-1 winners[ i ] = bucket[ pick ] ; bucket[ pick ] = bucket[ i ] ; # replace picked ball with 'top' ball }
Last edited by dlukin; 06-08-2010 at 01:32 PM.
That's basically the Fisher-Yates shuffle. You're not likely to find much better, as the modern version requires O(n) space and has O(k) time complexity. The only difference is the modern Fisher-Yates shuffles in place; the picked numbers are held in the same array that holds the unpicked numbers at one end or the other (in your sample, bucket[0..i] would be the winning numbers).
Stackoverflow has many questions along these lines. Look over them if you want more.
Be sure to read all pages linked in this post; they have further information that should prove useful. When asking for help, make sure you follow Eric Raymond's and Jon Skeet's guidelines for prompt, accurate responses. Please answer any questions I ask; they're not rhetorical (probably). Any posted code is intended as illustrative example, rather than a solution to your problem to be copied without alteration. Study it to learn how to write your own solution.Misson, not Mission.