Javascript generates m bit random Numbers up to 13 bits over time

  • 2020-03-30 04:12:41
  • OfStack

Generate m-bit random Numbers according to time, with a maximum of 13 random Numbers, and there is no guarantee that the first digit will not be 0


function ran(m) {
m = m > 13 ? 13 : m;
var num = new Date().getTime();
return num.toString().substring(13 - m);
}
console.log(ran(5));

According to the random Numbers generated by the random function of Math, m bits are intercepted. The generated random Numbers are no more than 16 bits at most, which can ensure that the first digit is not 0


function rand(m) {
m = m > 16 ? 16 : m;
var num = Math.random().toString();
if(num.substr(num.length - m, 1) === '0') {
return rand(m);
}
return num.substring(num.length - m);
}
console.log(rand(5));

Generated from Math's random function, there is no limit to the number of digits, and the first digit is not 0


function rando(m) {
var num = '';
for(var i = 0; i < m; i++) {
var val = parseInt(Math.random()*10, 10);
if(i === 0 && val === 0) {
i--;
continue;
}
num += val;
}
return num;
}
console.log(rando(5));

Related articles: