javascript - Generate many random numbers -


i need generate 4 million unique random numbers between 1 , 1 billion of 9 digits. fill zeros until 9 digits.

my script works (but slow) eq. 400000 numbers. not 4 millions

i need numbers in text file. fine ctrl+s output.

is there ways optimize memory/performance?

function zeropad(num, places) {   var 0 = places - num.tostring().length + 1;   return array(+(zero > 0 && zero)).join("0") + num; } var arr = [] while (arr.length < 4000000) {   var randomnumber = math.ceil(math.random() * 100000000)   if (arr.indexof(randomnumber) > -1) continue;   arr[arr.length] = randomnumber; } (i = 0; < arr.length; i++) {   document.write(zeropad(arr[i], 9) + '<br />'); } 

you can use generators , file write streams in node.js:

const fs = require('fs'); const writestream = fs.createwritestream('numbers.txt', {flags: 'w'});  writestream .on('error', error => console.log(error)) .on('close', () => console.log('done'));  const uniques = [];  function write10k() {   let = 0;   while (i < 1e4) {     const randomnumber = math.ceil(math.random() * 1e8);     if (uniques.indexof(randomnumber) > -1) continue;     uniques[uniques.length] = randomnumber;     const line = zeropad(randomnumber, 9) + '\n';     writestream.write(line);     i++;   } }  function* writegenerator() {   (let = 1; <= 4e6; i++) {     yield write10k();     console.log('wrote ' + (1e3  * i));   }   writestream.end(); }  function zeropad(num, places) {   const 0 = places - num.tostring().length + 1;   return array(+(zero > 0 && zero)).join('0') + num; }  const iter = writegenerator(); let next = iter.next();  while (!next.done) {   next = iter.next(); } 

this create file numbers.txt containing 4 million unique random numbers.


Comments