# Selecting Random Numbers

You are here: irt.org | Articles | JavaScript | Text, String, and Number | Selecting Random Numbers [ previous next ]

Published on: Saturday 29th November 1997 By: Martin Webb

## Introduction

This article will describe how to select random numbers from a range, to produce a selection of lottery numbers. As an added bonus it will show how to also randomly show a background color.

## Random Numbers

As in previous articles regarding random numbers, we will continue to use the following random number generator produced by Paul Houle:

```<SCRIPT>
<!--
// The Central Randomizer 1.3 (C) 1997 by Paul Houle (houle@msc.cornell.edu)
// See:  http://www.msc.cornell.edu/~houle/javascript/randomizer.html

rnd.today=new Date();
rnd.seed=rnd.today.getTime();

function rnd() {
rnd.seed = (rnd.seed*9301+49297) % 233280;
return rnd.seed/(233280.0);
};

function rand(number) {
return Math.ceil(rnd()*number);
};

// end central randomizer. -->
</SCRIPT>```

## "Selecting" the balls

When picking lottery balls it is essential that once a ball has been removed from the pool of balls, that it remains removed, i.e. the number must not be chosen again it that game.

One simple mechanism that can be employed to ensure that the same number is not chosen twice is to mark the number as chosen by using an array.

The following MakeEmptyArray() function makes an empty array of the required size, note that position zero (i.e. this[0]) of the array actually holds the size of the array:

```function MakeEmptyArray(size) {
this[0] = size;
for (i = 1; i <= size; i++)
this[i] = '';
}```

When picking a number, all we do is mark the position within the array with an 'X'. Therefore we must first ensure that the number picked has not already been chosen. The following SelectLotteryBalls() function does just that. When passed the number of balls that must be chosen, it uses a while loop which ensures that the correct number of balls are chosen. If the number is already chosen, then it ignores it and goes on to pick another. If the number has not already been chosen then it is marked with an 'X' and the number of balls left to pick is decreased by 1.

```function SelectLotteryBalls(number) {
while (number > 0) {
random = rand(lotterynumbers[0]);
if (lotterynumbers[random] == '') {
lotterynumbers[random] = 'X';
number--;
}
}
}```

## Displaying the "Selection"

To display the chosen lottery balls is a simple case of walking through the array checking for any entries that are marked. Because the interrogation of the array starts at the beginning and finishes at the end then the balls are automatically displayed in ascending order (theres no need to sort them first).

When displaying the lottery balls the ShowLotteryBalls() function will actually show an image for each numbered ball. Each image is named 1.gif through to 49.gif.

The ShowLotteryBalls() function cycles through the lotterynumbers array from 1 to the size of the array (held in position 0 of the array) checking each ball to see if its marked:

```function ShowLotteryBalls() {
document.write('<P>');
for (var i=1; i <= lotterynumbers[0]; i++) {
if (lotterynumbers[i] != '')
document.write('  <IMG SRC="balls/'+i+'.gif" HEIGHT=50 WIDTH=50 ALT="' + i +'">  ');
}
}```

To actually get the ball rolling (sic) all thats required is the number of balls, the number to choose and the array to hold them in:

```var lotteryballs = 49;
var ballstoselect = 6;

var lotterynumbers = new MakeEmptyArray(lotteryballs);```

The lotteryballs variable holds the number of balls in the pool, in this case 49, and the variable ballstoselect holds the number of balls required to be chosen. The lotterynumbers array holds the intial empty array.

To pick the lottery balls we need to invoke the SelectLotteryBalls() function followed by the ShowLotteryBalls() function:

```SelectLotteryBalls(ballstoselect);
ShowLotteryBalls();```

Once the balls have been chosen, it is possible to choose some more, but firsth the balls have to be cleaned. The following ResetLotteryBalls() function does just that, it resets the balls marked with an 'X' to an empty string:

```function ResetLotteryBalls() {
for (var i = 1; i <= lotterynumbers[0]; i++)
lotterynumbers[i] = '';
}```

To choose more balls we can then use:

```ResetLotteryBalls();
SelectLotteryBalls(ballstoselect);
ShowLotteryBalls();```

## Random Color

Rather than work out the random red, green and blue attributes to create a random color, why not do it the easy way with a list of all the named colors - then just pick one at random:

```var colors = new makeArray('aliceblue','antiquewhite','aqua','aquamarine','azure',
'beige','blanchedalmond','blue','blueviolet','brown','burlywood',
'cornsilk','crimson','cyan','darkblue','darkcyan','darkgoldenrod',
'darkgray','darkgreen','darkkhaki','darkmagenta','darkolivegreen',
'darkorange','darkorchid','darkred','darksalmon','darkseagreen',
'darkslateblue','darkslategray','darkturquoise','darkviolet',
'deeppink','deepskyblue','dimgray','dodgerblue','floralwhite',
'forestgreen','fuchsia','gainsboro','ghostwhite','gold','goldenrod',
'gray','green','greenyellow','honeydew','hotpink','indianred',
'ivory','khaki','lavender','lavenderblush','lawngreen',
'lemonchiffon','lightblue','lightblue','lightcoral','lightcyan',
'lightgoldenrodyellow','lightgreen','lightgrey','lightpink',
'lightsalmon','lightseagreen','lightskyblue','lightslategray',
'lightsteelblue','lightyellow','lime','limegreen','linen','magenta',
'maroon','mediumaquamarine','mediumblue','mediumorchid',
'mediumpurple','mediumseagreen','mediumslateblue',
'mediumspringgreen','mediumturquoise','mediumvioletred',
'midnightblue','mintcream','mistyrose','moccasin','navajowhite',
'navy','oldlace','olive','olivedrab','orange','orangered','orchid',
'palegoldenrod','palegreen','paleturquoise','palevioletred',
'papayawhip','peachpuff','peru','pink','plum','powderblue','purple',
'seagreen','seashell','sienna','silver','skyblue','slateblue',
'slategray','snow','springgreen','steelblue','tan','teal','thistle',
'tomato','turquoise','violet','wheat','white','whitesmoke','yellow',
'yellowgreen');```

The colors array, made using the makeArray() function, holds the names of the colors available. To actually pick a random color all we need is the following line:

`var color = colors[rand(colors[0])];`

Again, position zero (i.e. colors[0]) of the colors array holds the size of the array. To use the color, we can include it a script to display a table:

```document.write('<TABLE BGCOLOR="' + color + '"><TR><TD ALIGN="CENTER" HEIGHT="100">');
ResetLotteryBalls();SelectLotteryBalls(ballstoselect);ShowLotteryBalls();
document.write('</TD></TD></TABLE>');```

Of course if the browser doesn't support background colors in tables, then the background will default to the documents background color.

## Working Example

Why not try the lottery picker out. Please note, I cannot be held responsible for any losses you have as a result of choosing these numbers ;-)

## Source Code

You can view the source code of the working example.

## Related items

Math functions in JavaScript

Nested Splitting

Split Ends

How long is a piece of string?

Random Numbers & Random Events