This is a scrabble challenge. What are the different combinations of letters that can be derived from a set of letters.
For example with input tiles of “AAB” there are the following possibilities:
Note that there are no repetitions for the tile possibilities here!
Dictionaries in Swift typically have a lookup of O(1). This makes it a good candidate for this problem.
We can place each of our tiles into a frequency array, and can use the great initializer in Swift that allows us to give a default for each tile (making the syntax easy to read):
This algorithm for the input “AAB” is as follows:
We put the tiles into the frequency table -
freq = [“A”: 2, “B”: 1]
for the first letter we can either pick A or B.
so the two possibilities return:
freq = [“A”: 1, “B”: 1]
freq = [“A”: 2, “B”: 0]
In either case we iterate through the elements remaining in the array. For each element in turn we remove it from the dictionary, and recurse on this new dictionary.
After we have finished, we need to replace the tile into the dicionary. In Swift this looks like:
The runtime is fast, but over time this may be beaten by other contributions (who knows?)
Want to get in contact? Try the link here: