Created
September 11, 2017 15:02
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* 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