anon anon - 23 days ago 6
Javascript Question

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>

Answer

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?

Comments