Reputation: 4333
I'm trying to output all the possible combinations of 4 character strings using uppercase letters.
function makeid(length) {
var result = '';
var characters = 'ABCDEFGHIJKLMNPRSTUVWXYZ';
var charactersLength = characters.length;
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength));
}
return result;
}
function getcodes(){
var newcode =makeid(4);
if (codes.includes(newcode)){
getcodes();
}
else
{
codes.push(newcode)
document.getElementById("demo").innerHTML += newcode + "<br>";
getcodes();
}
}
getcodes()
console.log(codes.length)
The problem, of course, is that this loops forever. I'm not sure how to stop the loop when all the codes have been generated. How can I stop this after all combinations have been created?
The use case is that we're trying to generate unique URLs that will be something like example.com/CODES-HERE The codes generated with this script will be used for the CODES-HERE part.
Upvotes: 0
Views: 179
Reputation: 142
// there are 26! / (4! * 22!) = 14950 combinations possible. it takes a lot of time to get all those by trying random characters
const chrs = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
// function that returns the cartesian product of two arrays, excluding combinations with repeating characters or
// not in alphabetic order (because ACB is the same combination with ABC)
const cartesian = (arr1, arr2) => arr1.flatMap(x => arr2.filter(v => x < v[0]).map(y => x + y));
const combs = (ra, n) => [...Array(n - 2)].reduce(a => cartesian(ra, a), cartesian(ra, ra));
const str = combs([...chrs], 4).reduce((a, v) => a + v + '<br>', '');
document.getElementById("demo").innerHTML = str;
// if you want to allow combinations with repeating characters or not in alphabetic order
// remove the filter from cartesian
// but there are 26 ** 4 = 456976 possible outcomes then, so it'll take some time to print them all
Upvotes: 1