Kamal
Kamal

Reputation: 3

Generate and sort Javascript Random Numbers

I started to print 1000 random numbers between 1 to 100 and then sort all 1000 numbers.

Here something wrong happen .

How use Math.random() for it ?

        <script type="text/javascript" language="Javascript">
function pick(n, min, max) {
    var values = [],
        i = max;
    while (i >= min)
        values.push(i--);
    var results = [];
    var maxIndex = max;
    for (i = 1; i <= n; i++) {
        maxIndex--;
        var index = Math.floor(maxIndex * Math.random());
        results.push(values[index]);
        values[index] = values[maxIndex];
    }
    return results;
}

function go() {
    var running = true;
    do {
        if (!confirm(pick(1000, 1, 100).sort(function(a, b) {
                return a - b;
            }))) {
            running = false;
        }
    } while (running)
}
</script>
</head>

<body>
         <h1>100  random number between 1 and 100</h1>
         <p><button onclick="go()">Click me</button> to start generating numbers.</p>
          <p>When the numbers appear, click OK to generate another set, or Cancel to stop.</p>
    </body>

Upvotes: 0

Views: 1871

Answers (1)

Roland Mai
Roland Mai

Reputation: 31077

If you really just want to generate 1000 random numbers and then sort them the following should be enough:

function pick(n, min, max) {
    var results = [];
    for (i = 1; i <= n; i++) {
        var value = Math.floor(Math.random() * max + min);
        results.push(value);
    }
    return results;
}

function go() {
    var running = true;
    do {
        if (!confirm(pick(1000, 1, 100).sort(function (a, b) {
            return a - b;
        }))) {
            running = false;
        }
    } while (running)
}

Upvotes: 1

Related Questions