SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Enthusiast
    Join Date
    Dec 2003
    Location
    Raleigh, NC
    Posts
    44
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    A random sequence of integers into an array?

    Hi,

    I'd like to create an array of randomly sequenced integers. I want to specify the count (n) and have the resulting array containing n numbers starting at 0 but not repeating.

    So for example, something like this:

    for N=5: [0, 4, 3, 1, 2]
    for N=10: [4, 1, 3, 8, 6, 9, 2, 5, 0, 7]

    The plan is then to use this array to randomly access elements from another array in this random order. So for the n=5 example, it would result in:

    data[0]
    data[4]
    data[3]
    data[1]
    data[2]

    Is this possible? How do I do this?
    Thanks very much.
    David.

  2. #2
    Programming Since 1978 silver trophybronze trophy felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, NSW, Australia
    Posts
    16,862
    Mentioned
    25 Post(s)
    Tagged
    1 Thread(s)
    Just add the following code to your page:

    Code:
    var tot = 10; // change this to the number you want 
    function randOrd(){
    return (Math.round(Math.random())-0.5); }
    var data = [];
    for (var i = tot-1; i >= 0; i--) data.push(i );
    data.sort(randOrd);
    Now your array contains the numbers you want (0 thru 9 if you set tot = 10) in random order.
    Stephen J Chapman

    javascriptexample.net, Book Reviews, follow me on Twitter
    HTML Help, CSS Help, JavaScript Help, PHP/mySQL Help, blog
    <input name="html5" type="text" required pattern="^$">

  3. #3
    SitePoint Enthusiast
    Join Date
    Dec 2003
    Location
    Raleigh, NC
    Posts
    44
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Stephan, that is brilliant! Thanks very much!


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •