I’m working on a predictive text solution and have all the words being retrieved from a Trie based on input for a certain string of characters, i.e. “at” will give all words formed with “at” as a prefix. The problem that I have now, is that we are also supposed to return all other possibilities from pressing these 2 buttons, Button 2 and button 8 on the mobile phone, which would also give words formed with, “au, av, bt, bu, bv, ct, cu, cv” (most of which won’t have any actual words.
Can anyone suggest a solution and how I would go about doing this for calculating the different permutations?
(at the moment, I’m prompting the user to enter the prefix (not using a GUI right now)
Welcome to concepts like recursivity and combinatorial-explosion 🙂
Due to combinatorial explosion, you have to be “smart” about it: if the user wants to enter a legitimate 20 letters word, it is unacceptable for your solution to “hang” trying stupidly tens of millions of possibilities.
So you should only recurse when the trie has at least one entry for your prefix.
Here’s a way to generate all prefixes and only recurse when there’s a match.
In this example, I faked a trie always saying there’s an entry. I made this in five minutes so it can surely be beautified/simplified.
The advantage of such a solution is that it works if the user presses on one, two, three, four or ‘n’ keys, without needing to change your code.
Note that you probably do not want to add all the words starting with ‘x’ letters when there are too many. It’s up to you to find the strategy that matches best your need (wait for more keypresses to reduce candidates or add most common matches as candidates etc.).
Note the recursive call (only when there’s a matching prefix).
Here’s how you could call it: I faked the user pressing ‘1’, then ‘2’ and then ‘3’ (I faked this in the chars char[][] array I created):
That example shall create a set containing 36 matches because I “faked” that every prefix is legit and that every prefix leads to exactly one word (and I only added the “word” when it’s made of at least two letters). Hence 3*3*3 + 3*3, which gives 36.
You can try the code, it’s fully working but you’ll have to adapt it of course.
In my fake example (user pressing 1,2 then 3), it creates this:
Welcome to real coding 🙂