-3

I have a code which produces 5 unique random numbers between 0-9. However I don't want the first number to be zero.

How do I solve this?

var arr = []
while(arr.length < 5){
    var randomnumber = Math.floor(Math.random()*10);
    if(arr.indexOf(randomnumber) > -1) continue;
    arr[arr.length] = randomnumber;
}
document.write(arr);
jokr1
  • 69
  • 3
  • 13

2 Answers2

0

It's very simple, as your numbers don't get repeated. If first number is 0, just swap it with a value of random index. Here I have used index 3.

var arr = []
while (arr.length < 5) {
  var randomnumber = Math.floor(Math.random() * 10);
  if (arr.indexOf(randomnumber) > -1) continue;
  arr[arr.length] = randomnumber;
}
if (arr[0] === 0) {
  arr[0] = arr[3];
  arr[3] = 0;
}
console.log(arr);
.as-console-wrapper {top: 0; height: 100%;}

Testing to create 100 different cases:

var all = [];
var arr = [];
for (var i = 0; i < 100; i++) {
  arr = [];
  while (arr.length < 5) {
    var randomnumber = Math.floor(Math.random() * 10);
    if (arr.indexOf(randomnumber) > -1) continue;
    arr[arr.length] = randomnumber;
  }
  if (arr[0] === 0) {
    arr[0] = arr[3];
    arr[3] = 0;
  }
  all.push(arr.join(", "));
}
console.log(all);
.as-console-wrapper {top: 0; height: 100%;}
Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0

You could insert a check for a zero at start and continue.

var array = [],
    randomnumber;

while (array.length < 5) {
    randomnumber = Math.floor(Math.random() * 10);
    if (array.indexOf(randomnumber) > -1 || !array.length && !randomnumber) continue;
    array.push(randomnumber);
}

console.log(array);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392