Random individual array

J

jar13861

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....

holder = new Array ( 9 );
var flag = true;
var rannum = Math.floor( 1 + Math.random() * 9 );

for (var j = 0; j < 9; j++)
{
flag = true;
if (rannum == holder[j])
{
flag = false;

}
}


if(flag == true)
{
document.writeln(+rannum+ "<BR>");
holder[i-1] = rannum;
}
else
i--;
 
R

RobG

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+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;
A = A[rNum];
A[rNum] = temp;
}
return A;
}

document.write( shuffleArray(a).join('<br>') );

</script>


Lightly tested.
 
L

Lasse Reichstein Nielsen

I'm confused on how to write a random array that will only generate 9
different numbers from 1-9.

Try writing down, in more detail, what your requirements are, and use
precise wording. Once you can explain the problem clearly, the result
is often much closer :)

I'll give it a shot. Correct me if I'm wrong.

You want to create an array with nine entries (indexed 0 through 8)
each having one of the integer values 1 through 9. Each of these
integers must occour exactly once. The order of the integers should
be random, with all different orderings being equally likely.
Here is what I have, but its only writing
one number....

holder = new Array ( 9 );
var flag = true;
var rannum = Math.floor( 1 + Math.random() * 9 );

Here you generate one random number.
for (var j = 0; j < 9; j++)
{
flag = true;
if (rannum == holder[j])
{
flag = false;

}

Here you appear to check whether the j'th entry already has your
number. As this happening inside some loop that you haven't included?
Otherwise you know that holder[j] is uninitialized at this point.

(You should name your variables meaningfully. What is the flag
representing? Could it be called "okToAssignFlag"?)
}


if(flag == true)
{
document.writeln(+rannum+ "<BR>");
holder[i-1] = rannum;

Here you refer to "i", which isn't defined anywhere. Again this suggests
to me that your code has another for loop between the assignment to
holder and the following code, one using "i" as an index.
(It also helps that you posted that code in another thread :)


A generic method for creating a number of elements in uniform random
order is to create them in a fixed order and then shuffle the array.
Try googling for shuffling algorithms. There is one that satisfies
the requirements (at least as well as the computer's pseudo-random
number generator allows), and it's even pretty simple.

/L
 
L

Lee

RobG said:
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).

If you're shuffling an array, it doesn't matter what order the
elements start out in.

Shuffling twice won't make the order any more random.

Any randomization must allow some of the elements to remain in
the original position. It wouldn't be random, otherwise.
 
R

RobG

Lee said:
RobG said:




If you're shuffling an array, it doesn't matter what order the
elements start out in.

The code I posted starts with the elements in the same order every time.
The shuffle algorithm does not put any element back where it started,
so for a single shuffle there are a number of possible combinations that
will never occur - in a truly random shuffle it should be possible that
none of the elements will change their position.

Shuffling twice won't make the order any more random.

In this particular case, yes it will. It is the only way that any
element can return to its original position.

Any randomization must allow some of the elements to remain in
the original position. It wouldn't be random, otherwise.

Yes, a failing of the algorithm that I posted. That's why I mentioned
it - it may not bother the OP, or maybe it does.

Here's another shuffle that is more random, elements have an equal
chance of being put into any position.

function shuffleArray(A)
{
var rNum;
var tArray = [];

for (var i=0, j=A.length; j; ++i){
rNum = getRandomNumber(j--);
tArray = A[rNum];
A.splice(rNum,1);
}

return tArray;
}
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Wed, 1 Mar 2006
08:26:43 remote, seen in Lasse Reichstein
Nielsen said:
A generic method for creating a number of elements in uniform random
order is to create them in a fixed order and then shuffle the array.
Try googling for shuffling algorithms.

Better not to recommend Google for something covered in the newsgroup
FAQ.
 
D

Dr John Stockton

JRS: In article <[email protected]>, dated Wed, 1
Mar 2006 05:29:14 remote, seen in RobG
(e-mail address removed) wrote:

There is no need for ==true - evidently the OP does not understand
the use of Booleans.

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.

Not true (unless one has Shuffling code but not Dealing code).
There is a shuffling algorithm here:

<URL:http://www.merlyn.demon.co.uk/js-randm.htm#SDD>

True. But one should read on from Shuffling to Dealing, which contains
and demonstrates

function Deal(N) { var J, K, Q = new Array(N)
for (J=0; J<N; J++) { K = Random(J+1) ; Q[J] = Q[K] ; Q[K] = J }
return Q }

Applied to your circumstance, the following shuffles an array's elements
so that they all occupy a different position to that before shuffling.

That, of course, would not be a proper Shuffle.

Inevitably, it does not meet specification for a 1-element array <g>.

It should be equivalent to, from the end of my pas-rand.htm#Shuf,

for J := Max downto 2 do Swap(A[J], A[Succ(Random(Pred(J)))]) ;

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).

9! is somewhat smaller than that.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top