Michael Falch Madsen
Michael Falch Madsen

Reputation: 29

Generate many random numbers

I need to generate 4 million unique random numbers between 1 and 1 billion of 9 digits. Fill with zeros until 9 digits.

My script works (but slow) for eq. 400000 numbers. But not for 4 millions

I need the numbers in a text file. Its fine to just CTRL+S the output.

Is there any ways to optimize the memory/performance?

function zeroPad(num, places) {
  var zero = 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;
}
for (i = 0; i < arr.length; i++) {
  document.write(zeroPad(arr[i], 9) + '<br />');
}

Upvotes: 1

Views: 141

Answers (2)

Michael Falch Madsen
Michael Falch Madsen

Reputation: 29

It is a number to be printed on some packaging and printing company would have the numbers in a text file.

I ended up with just editing my code and running it 10 times with different interval.

I definitely will have a look at node.js

Thanks for your input

Upvotes: 0

Miguel
Miguel

Reputation: 20633

You can use generators and 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 i = 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() {
  for (let i = 1; i <= 4e6; i++) {
    yield write10k();
    console.log('wrote ' + (1e3  * i));
  }
  writeStream.end();
}

function zeroPad(num, places) {
  const zero = 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 will create the file numbers.txt containing 4 million unique random numbers.

Upvotes: 1

Related Questions