Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3

Thread: array

  1. #1
    Regular Coder
    Join Date
    Jun 2002
    Posts
    156
    Thanks
    0
    Thanked 0 Times in 0 Posts

    array

    I want the array of 10 random no. withought duplication of no. from 1 to 20. It might be very difficult to understand what I want to say. But it will get u understand once u will go through the below code.
    Here I am pasting my code but it's not working fine it giving me array of 10 with diffrent nos. but with undifined ........

    Can anybody give me solution for this

    <html>
    <head>
    <title></title>
    <script language="javascript">
    numpics = 20;
    var i=0;
    var j=0;
    var rndnum = new Array(10);
    for (i=0; i<rndnum.length; i++)
    {
    arraynum = Math.round(Math.random()*numpics);

    for (j=0; j<rndnum.length; j++)
    {
    if(rndnum[j] == arraynum)
    {
    break;
    }
    }
    if(j==rndnum.length)
    {
    rndnum[i] = arraynum;
    }
    }

    </script>
    </head>

    <body>
    <script language="javascript">
    for (i=0; i<rndnum.length; i++)
    {
    document.write(rndnum[i] + ", ");
    }
    </script>

    </body>
    </html>

  • #2
    Regular Coder
    Join Date
    Jul 2002
    Location
    USA
    Posts
    151
    Thanks
    0
    Thanked 0 Times in 0 Posts
    The reason you're getting undefined values is because you're incrementing your loop regardless of whether you get a value for that pass. Change your loop to this:
    Code:
    for (i=0; i<rndnum.length && i<=numpics; i++) {
        arraynum = Math.round(Math.random()*numpics);
    
        for (j=0; j<i; j++) {
            if(rndnum[j] == arraynum) {
                break;
            }
        }
        if(j==i) {
            rndnum[i] = arraynum;
        } else {
            i--;
        }
    }
    Last edited by Algorithm; 12-27-2002 at 10:06 AM.

  • #3
    Regular Coder
    Join Date
    Jun 2002
    Posts
    156
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Thanks


  •  

    Posting Permissions

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