Here's a game that I'm trying to implement. A kids game where they name an object in a selected category ( say animals! ) such that the first letter of the player's word is the same as the last letter of the previous player's word.
An example would be:
- Player 1: giraffee
- Player 2: elephant
- Player 3: tiger
- Player 4: raccoon
and so on!
Now, I want to write a code that given a list of words it will find the longest possible chain of words.
A possible list:
['giraffe', 'elephant', 'ant', 'tiger', 'raccoon', 'cat', 'hedgehog', 'mouse']
The longest will have to be:
['hedgehog', 'giraffe', 'elephant', 'tiger', 'raccoon']
The bug in my code is if I change the order of the original list the longest chain will differ!!! :(
Here's the pseudo code:
function longest-chain(chain, V , longest) #Recursively return the longest chain in V
extended = False
for word in V do
if chain + word is a legal chain then
longest = longest-chain(chain + word, V / {word})
extended = True
if extended is False then # No word in V could extend chain
if chain is longer than longest then
longest = chain
return longest
(The / indicates the set difference operator)
Could somebody help me implement it correctly? I didn't want to post my code because I wanted to start over.