473,388 Members | 1,468 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,388 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 2058
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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
by: Dr John Stockton | last post by:
Q1 : Given an array such as might have been generated by var A = is there a highly effective way of reducing it to - i.e. removing the undefineds and shifting the rest down? ...
10
by: Virus | last post by:
Ok well what I am trying to do is have 1.) the background color to change randomly with 5 different colors.(change on page load) 2,) 10 different quotes randomly fadeing in and out in random...
16
by: Jason | last post by:
Hi, I need a way to use random numbers in c++. In my c++ project, when using the mingw compiler I used a mersenne twister that is publicly available and this did its job well. Now I have...
5
by: Luke | last post by:
Hello, I am the administrator for http://www.nickberg.org - Nick is the man who was recently beheaded in Iraq. He was a very ingenious man - once for my birthday had gave me a small box...
10
by: Johnny Snead | last post by:
Hey guys, Need help with this random sort algorithm private void cmdQuestion_Click(object sender, System.EventArgs e) { Random rnd = new Random(); //initialize rnd to new random object...
12
by: Pascal | last post by:
hello and soory for my english here is the query :"how to split a string in a random way" I try my first shot in vb 2005 express and would like to split a number in several pieces in a random way...
6
by: Pao | last post by:
My code works in this way: I declared a static array in a class (public static int GVetRandom = new int;) that in a for cycle I fill with random numbers. The array gets cleared (clear method) and...
13
by: Peter Oliphant | last post by:
I would like to be able to create a random number generator that produces evenly distributed random numbers up to given number. For example, I would like to pick a random number less than 100000,...
11
TTCEric
by: TTCEric | last post by:
This will be original. I promise. I cannot get the random number generator to work. I tried seeding with Date.Now.Milliseconds, it still results in the same values. What I have are arrays...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

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.