0

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>
1
  • Your second loop (the for loop) runs from 1 to the value of "n". Each time through the loop, you decrement "maxIndex". Well, that starts off as 100, but "n" is 1000. Commented Nov 16, 2014 at 20:39

1 Answer 1

1

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)
}
Sign up to request clarification or add additional context in comments.

2 Comments

if want 1 million random numbers then ?
Technically you can change the parameter to 1000000 but it's going to be a bit slow. Javascript is not good with this sort of thing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.