Skip to content
Advertisement

Duplicating each character for all permutations of a string

This is a slightly odd/unique request. I am trying to achieve a result where e.g “yes” becomes, “yyes”, “yees”, “yess”, “yyees”, “yyess”, “yyeess”.

I have looked at this: Find all lowercase and uppercase combinations of a string in Javascript which completes it for capitalisation, however my understanding is prohibiting me from manipulating this into character duplication (if this method is even possible to use in this way).

JavaScript

If I haven’t explained this particularly well please let me know and I’ll clarify. I’m finding it quite the challenge!

Advertisement

Answer

General idea
To get the list of all words we can get from ordered array of letters, we need to get all combinations of letters, passed 1 or 2 times into word, like:

JavaScript

Amount of all possible words equal to 2 ^ word.length (8 for "yes"), so we can build binary table with 8 rows that represent all posible combinations just via convering numbers from 0 to 7 (from decimal to binary):

JavaScript

Each decimal we can use as pattern for new word, where 0 means letter must be used once, and 1 – letter must be used twice:

JavaScript

Code
So, your code representation may looks like this:

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