|
Many countries these days have some sort of lottery or
lotto or pools (or whatever they call it) that requires
you to select so many numbers out of a given total and
if your numbers (or some of them) are drawn then you
win a prize.
One problem in entering such a competition (apart from
the extremely high odds against your numbers actually
being the ones selected) is how you choose those
numbers in the first place. If there are more than 28
numbers in the draw (which applies to just about all of
them) then selecting significant dates will give you a
selection skewed towards lower numbers. With most of
these sorts of competition you get the best payout
(assuming that you win) if as few as possible other
people share the same numbers. Without being able to
know what combinations have been selected by the least
number of other people you have the best chance by
selecting numbers at random.
So how do you pick your random numbers? Well a simple
piece of Javascript can do it for you. Here is a
Javascript function that will select a specified number
of picks out of a larger selection of numbers starting
from 1:
function randOrd(){
return (Math.round(Math.random())-0.5); }
function picks(pick,tot) {var ary = [];
for (var i = tot; i > 0; i--) ary.push(i );
ary.sort(randOrd);
return ary.slice(0,pick).join(',');}
Simply pass in the number of picks you want made and
how many numbers there are to pick from and the above
function will return a comma separated list containing
the number of picks that you asked for.
Want to see it in action? Well the following form grabs
the number of picks and the total to pick them from out
of the form, validates the values that you enter and
then calls the above function to extract the required
number of picks for you. If you don't like the
first set of numners it chooses then just press the Go
button again to get a new set of picks.
This Javascript function is a good example of how you
can combine together several of the array methods to
produce results like this involving very little code
compared to the amount of code that would be required
if fewer of the methods were used. Here we use
push to add the numbers to the array to start
with, sort (with the comparison function
overridden) to sort into random order, slice to
grab the desired number of results, and join to
convert the results into a comma separated text string.
|