473,883 Members | 1,658 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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.writel n(+rannum+ "<BR>");
holder[i-1] = rannum;
}
else
i--;

Mar 1 '06 #1
5 2089
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.writel n(+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.demo n.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.writel n(+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/rasterTriangleD OM.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**********@h otpop.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.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Mar 2 '06 #5
JRS: In article <Ki************ *****@news.optu s.net.au>, dated Wed, 1
Mar 2006 05:29:14 remote, seen in news:comp.lang. javascript, RobG
<rg***@iinet.ne t.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.demo n.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(Pre d(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.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.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
3275
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? A.sort().slice(0,n) // would do it, but sorts; and the number
10
2513
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 spots on the webpage. with a delay timer on them, so they keep changing as the page is open. Not random each time the page is loaded. If anyone can help it would be greatly appreaciated, I have tried many of
16
4235
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 shelled out on VC++ 6.0 compiling that same code is proving difficult. I am not too worried how I generate random numbers in c++, as long as it is sufficiently random. Can anybody help me out in getting what I want from VC++?
5
3116
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 wrapped in duck tape with a few diodes and two wires sticking out. When attaching the wires to your skin the diodes would light up in a random configuration. (he later modified this into a skin resistance
10
5996
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 System.Random iRnd = new System.Random(); string theNum = iRnd.Next(0,8).ToString(); lblAnswer.Text = iRnd.Next(0,8).ToString();
12
3235
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 without success. for example if the number is 123 456 : i would like to have some random strings like theese : (12 * 10 000) + (345 * 10) + (6*1) or (123*1 000)+(4*100)+(5*10)+(6*1) etc...
6
2128
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 refilled at each turn of cycle. On my developing pc, the same sequence of random numbers was repeated from on turn of cycle to the other; I put some Application.DoEvents() and all gone well.
13
2822
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, or between 0 and 99999 (inclusive). Further, the I want the range to be a variable. Concretely, I would like to create the following method: unsigned long Random( unsigned long num )
11
3028
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 of values. I get a random index value for each array so I can pull the data from them.
0
9940
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9792
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10415
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9573
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7971
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7126
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5797
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5991
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4611
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.