ja******@gmail.com wrote:
I'm confused on how to write a random array that will only generate 9
different numbers from 1-9. Here is what I have, but its only writing
one number....
Seems there are some copy/paste induced errors, I'll ignore those.
holder = new Array ( 9 );
var flag = true;
var rannum = Math.floor( 1 + Math.random() * 9 );
That will generate a single random number that is an integer in the
range 1 to 9 inclusive.
for (var j = 0; j < 9; j++)
{
flag = true;
if (rannum == holder[j])
{
flag = false;
}
}
if(flag == true)
{
document.writeln(+rannum+ "<BR>");
This line will apply the unary '+' operator to rannum which will convert
its value from a string to a number (if possible). Since the value of
rannum is already a number, there seems little point in doing so.
Conversion (if it happens) only occurs within the context of evaluation
of the statement which is then used to write the value of rannum to the
document. An observer looking at the document can't tell whether a type
string or number was written - they both look like numbers. So even if
conversion did occur, it has no bearing on the result of the
document.write() statement.
holder[i-1] = rannum;
Where was 'i' declared? It is undefined, so this line will throw an
error when it is parsed.
}
else
i--;
'i' hasn't been initialised with a number value, so that will produce an
error.
If you are trying to generate an array of the numbers from 1 to 9 in
some random order, the easiest way is to create the array then shuffle
it. There is a shuffling algorithm here:
<URL:http://www.merlyn.demon.co.uk/js-randm.htm#SDD>
Applied to your circumstance, the following shuffles an array's elements
so that they all occupy a different position to that before shuffling.
If further randomisation is required, shuffle twice but then some of the
elements may return in their original position and the entire array
*may* return in its original order (with an array of 9 elements the
chance is 1:9! or 1:493,920).
<script type="text/javascript">
// Set numTerms to number of terms required
var numTerms = 9;
// Declare a as an array and fill with numbers
// from 1 to numTerms inclusive
var a = [];
for (var i=0; i<numTerms; ++i){
a[i] = i+1;
}
// Return a random number in the
// range 0 to (num-1) inclusive
function getRandomNumber(num)
{
return Math.floor(Math.random() * num);
}
// Based on algorithm at
//
http://www.merlyn.demon.co.uk/js-randm.htm#SDFS
function shuffleArray(A)
{
var rNum; // Store random number to shuffle with
var temp; // Temporary value store
for (var i=0, j=A.length; i<j; ++i){
rNum = getRandomNumber(i);
temp = A[i];
A[i] = A[rNum];
A[rNum] = temp;
}
return A;
}
document.write( shuffleArray(a).join('<br>') );
</script>
Lightly tested.
--
Rob