Random individual array

Discussion in 'Javascript' started by jar13861@gmail.com, Mar 1, 2006.

  1. Guest

    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, 2006
    #1
    1. Advertising

  2. RobG Guest

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




    --
    Rob
     
    RobG, Mar 1, 2006
    #2
    1. Advertising

  3. "" <> 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 -
    DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
    'Faith without judgement merely degrades the spirit divine.'
     
    Lasse Reichstein Nielsen, Mar 1, 2006
    #3
  4. Lee Guest

    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.
     
    Lee, Mar 1, 2006
    #4
  5. RobG Guest

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

    return tArray;
    }



    --
    Rob
     
    RobG, Mar 1, 2006
    #5
  6. JRS: In article <>, dated Wed, 1 Mar 2006
    08:26:43 remote, seen in news:comp.lang.javascript, Lasse Reichstein
    Nielsen <> 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.
     
    Dr John Stockton, Mar 2, 2006
    #6
  7. JRS: In article <KiaNf.561$>, dated Wed, 1
    Mar 2006 05:29:14 remote, seen in news:comp.lang.javascript, RobG
    <> posted :
    > 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.
     
    Dr John Stockton, Mar 2, 2006
    #7
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Chris  Portka
    Replies:
    8
    Views:
    447
    Alexander Block
    Jun 5, 2007
  2. ...vagrahb
    Replies:
    1
    Views:
    298
    Vidar Hasfjord
    May 6, 2008
  3. globalrev
    Replies:
    4
    Views:
    774
    Gabriel Genellina
    Apr 20, 2008
  4. Stefan Kruger
    Replies:
    2
    Views:
    106
    Stefano Crocco
    Nov 10, 2008
  5. VK
    Replies:
    15
    Views:
    1,180
    Dr J R Stockton
    May 2, 2010
Loading...

Share This Page