Skip to content
Advertisement

How do you generate all 5 letter strings from 3 characters?

Given 3 characters (abc), I want to generate all possible 5-letter strings with them (aaaaa, aaaab, … ccccb, ccccc)

JavaScript

This feels like an inefficient way to do this, so is there a more elegant/efficient way to do this?

Advertisement

Answer

Your nested for loops does imply that code can be refactored either using recursion or as in my example below by creating a higher level loop.

This approach allows us to generate strings of any desired length.

JavaScript

We can make that extendWith function more succinct like this

JavaScript

and as it’s now just a one line expression we can dispense with the utility function and simplify a bit more

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement