anon
anon

Reputation: 49

random number WITH duplicates

This current code gives me N (input value) numbers, all lower then N and drops the data off at id="demo" in a random order -- which is fine; but I would like for the numbers to be completely random, as it stands it gives me one of every number lower/including N (so no duplicates, just a random order counting up to N).

How would I write it so I would get duplicates?

<!DOCTYPE html>
<html>
<body>

<input id="input1" type="number" min=10" max="100" onchange="test();">

<p id="demo"></p>


<script>
function test() {
var N = document.getElementById("input1").value;
var arr = [];
while(arr.length < N){
var randomnumber = Math.ceil(Math.random()*N);
if(arr.indexOf(randomnumber) > -1) continue;
arr[arr.length] = randomnumber;
}
document.getElementById("demo").innerHTML = arr;}



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

Upvotes: 0

Views: 35

Answers (1)

Brandt Solovij
Brandt Solovij

Reputation: 2134

to specifically answer your question:

remove

if(arr.indexOf(randomnumber) > -1) continue;

that is a conditional clause which checks for duplicates (in your code)

edit2: also check the .innerHTML assignment - i may give you [Object object] or [Array array]

edit: can I ask how this was elusive?

Upvotes: 2

Related Questions