Skip to content

Instantly share code, notes, and snippets.

@danilor
Created September 7, 2022 17:48
Show Gist options
  • Save danilor/80414423ab4c348239efde52e7e0315d to your computer and use it in GitHub Desktop.
Save danilor/80414423ab4c348239efde52e7e0315d to your computer and use it in GitHub Desktop.
/**
* This will only calculate how many random
* attemps it will take to form a full phrase.
*
* It takes around 5000 attemps for a 2 characters phrase.
* Cannot imagine how much will it take for a full book with meaning.
*
* Tests:
* - "h" = min: 16 | max. 40
* - "ha" = min: 1189 | max: 7500
* - "hel" = one single test: 166797
*
*/
// What we are looking for
const phraseToSearch = 'hello';
const waitMilliseconds = 2000; // milliseconds to start the application
/**
* function that generates a random password
*/
generateRandomPassword = (length) => {
/**
* Available characters.
* If we include special characters, it may take forever to get
*/
const charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 ";
let retVal = "";
for (var i = 0, n = charset.length; i < length; ++i) {
retVal += charset.charAt(Math.floor(Math.random() * n));
}
return retVal;
}
/**
* This will make the whole calculation
*/
calculateAttemps = ()=>{
let attemps = 0;
let got_phrase = '';
while( got_phrase !== phraseToSearch ){
got_phrase = generateRandomPassword(phraseToSearch.length);
console.log(got_phrase);
attemps++;
}
return attemps;
}
console.log('We are going to try to get the following phrase: ' + phraseToSearch.toString());
setTimeout( ()=>{
console.log(' ');
const totalAttemps = calculateAttemps();
console.log(' ');
console.log(`It took [${totalAttemps}] attemps to get to the phrase ${phraseToSearch}`);
}, waitMilliseconds ); // seconds before starting the application
/*const test = generateRandomPassword(8);
console.log('Test: ' + test);*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment