[javascript] Lotto deduplication question (goto statement)

Asked 2 years ago, Updated 2 years ago, 24 views

<!DOCTYPE html>
<html>
    <head>
        <title> </title>
    </head>
    <body>
    <script type="text/javascript">
    var i;
    var j
    var cnt=5;
    var y
    var arr=[];
    for(y=0;y<cnt;y++){
        a:
        for(i=0;i<6;i++){
            arr[i]=parseInt(Math.random()*45+1);
            for(j=0;j<i;j++){
                if(arr[i]==arr[j]){
                    continue a;
                }
            }
        }
        for(i=0;i<6;i++){
            document.write(arr[i]+" ");
        }
        document.write("<br>");
    }

    </script>
    </body>
</html>

The code written by C has been converted into JavaScript.

I tried to use goto instead of continue, and I kept getting duplicate numbers.

How do I use the goto sentence?

Also, I would appreciate it if you could tell me how to use the continuation or break statement.

It doesn't have to be goto. <

javascript c

2022-09-22 15:01

1 Answers

        a:
        for(i=0;i<6;i++){
            process.stdout.write("a: " + i +"\n");
            arr[i]=parseInt(Math.random()*45+1);
            for(j=0;j<i;j++){
                if(arr[i]==arr[j]){
                    i--; // perform i-- because this index needs to be re-exposed before continuing.
                    continue a;
                }
            }
        }

If you choose 6 out of 45 numbers to avoid overlapping, you can do the following:

/**
 * Function that shuffle the order of array arr
 */
function shuffle(arr)
{
    for(var i=arr.length;i>0;i--) 
    {
        // Select any location pick with 0<=pick<i.
        var pick = Math.floor(Math.random()*i);    
        vartmp = arr[i-1]; // i-1th value and
        arr[i-1] = arr[pick]; // reorder the values at the selected pick's location
        arr[pick] = tmp;
    }
}

// I'm going to make an array of lotto numbers
var lotto = [];
for(var i=1;i<=45;i++) {
    lotto[i-1] = i;
}

// in a jumble of arrangements
shuffle(lotto);

// Choose 6 from the front
for(i=0;i<6;i++) {
    document.write(arr[i]+" ");
}


2022-09-22 15:01

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.