471,601 Members | 1,192 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,601 software developers and data experts.

Random individual array

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

Mar 1 '06 #1
5 1938
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
Mar 1 '06 #2
"ja******@gmail.com" <ja******@gmail.com> writes:
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
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
'Faith without judgement merely degrades the spirit divine.'
Mar 1 '06 #3
Lee wrote:
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.


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[i] = A[rNum];
A.splice(rNum,1);
}

return tArray;
}

--
Rob
Mar 1 '06 #4
JRS: In article <1w**********@hotpop.com>, dated Wed, 1 Mar 2006
08:26:43 remote, seen in news:comp.lang.javascript, Lasse Reichstein
Nielsen <lr*@hotpop.com> posted :

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.

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Mar 2 '06 #5
JRS: In article <Ki*****************@news.optus.net.au>, dated Wed, 1
Mar 2006 05:29:14 remote, seen in news:comp.lang.javascript, RobG
<rg***@iinet.net.au> posted :
ja******@gmail.com wrote:
if(flag == true)


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.

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Mar 2 '06 #6

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

11 posts views Thread by Dr John Stockton | last post: by
10 posts views Thread by Virus | last post: by
16 posts views Thread by Jason | last post: by
5 posts views Thread by Luke | last post: by
10 posts views Thread by Johnny Snead | last post: by
13 posts views Thread by Peter Oliphant | last post: by
1 post views Thread by XIAOLAOHU | last post: by
reply views Thread by leo001 | last post: by
reply views Thread by MichaelMortimer | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.