问题
I've been struggling a bit today, trying to make a function, that can generate all possible strings, with all possible ascii chars, up to a certain length.
So basically, first a single char, from 0-255. Then two where I get AA, then AB, then AC... etc (but using ascii char codes, to get all possible values in each spot).
Does that make sense?
I guess I suck at recursion, because every attempt I make, either gets way too complicated for myself to figure it out, or ends up only increasing the last position in my string.
I'm completely stuck here and loosing all overview of what I'm doing.
I've tried googling to no avail, usually ending up in the same articles that doesn't quite seem to be the same problem.
I'll be happy with any examples, it doesn't have to be javascript.
Help me stackoverflow, you're my only hope.
回答1:
You could use a generator, that recursively builds up the string and yields up the results to the caller:
function* chars() {
for(let i = 0; i < 255; i++)
yield String.fromCharCode(i);
}
function* combinations(length, previous = "") {
if(length <= 0) {
yield previous;
return;
}
for(const char of chars())
yield* combinations(length - 1, previous + char);
}
That way you can get all combinations as:
const result = [...combinations(5)];
Note that 255 ** n is a lot, so you might want to consume the combinations one after another:
const timer = ms => new Promise(res => setTimeout(res, ms));
(async function() {
for(const combo of combinations(5)) {
console.log(combo);
await timer(1);
}
})();
回答2:
I guess I suck at recursion
You seem to be looking for a recursive solution.
Might this pseudocode solve your problem?
F(n)
if (n == 1)
return asciiCharacters
suffixes = F(n - 1)
for each character of asciiCharacters
for each suffix of suffixes
results.push(character + suffix)
return results
where asciiCharacters is an array of ASCII characters.
来源:https://stackoverflow.com/questions/53693201/how-to-generate-all-possible-strings-with-all-ascii-chars-to-a-certain-length