Skip to content

Instantly share code, notes, and snippets.

@joduplessis
Created September 11, 2017 15:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joduplessis/f69a88ae6324b03983b5c504e473ae4d to your computer and use it in GitHub Desktop.
Save joduplessis/f69a88ae6324b03983b5c504e473ae4d to your computer and use it in GitHub Desktop.
Generate random numbers that are unique and writing that to a CSV document.
/*
* System for generating x number of unique numbers and writing that to a CSV
* document. Good for competitions or anything requiring true unique numbers.
* Also an interesting exercise for Node/Javascript perf.
*/
const fs = require('fs');
const numbers = [];
const start = 111111111; // We don't want any leading 0's
const end = 999999999;
const amount = 3000000;
const step = Math.floor((end-start)/amount);
const padding = 9;
const file = fs.createWriteStream('numbers.csv');
function toText(number) {
const toPad = padding - number.toString().length;
let paddingString = '';
for (let c=0; c<toPad; c++) {
paddingString += '0';
}
return number.toString()+''+paddingString;
};
function shuffle(array) {
let counter = array.length;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
let index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
let temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
}
function convertArraytoText(arr) {
let numberArray = [];
for (let c=0; c<arr.length; c++) {
numberArray.push(toText(arr[c]));
}
return numberArray;
}
// Create our array to shuffle
for (let c=1; c<=amount; c++) {
numbers.push(toText(c*step));
// console.log(c+'> '+toText(c*step));
}
// Shuffle array
const shuffledNumbers = shuffle(numbers);
// Write each entry to file
shuffledNumbers.forEach(function(v) {
file.write(v + '\n');
});
file.end();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment