Q: Given a list of words like https://github.com/NodePrime/quiz/blob/master/word.list find the longest compound-word in the list, which is also a concatenation of other sub-words that exist in the list. The program should allow the user to input different data. The finished solution shouldn't take more than one hour. Any programming language can be used, but Go is preferred.
Fork this repo, add your solution and documentation on how to compile and run your solution, and then issue a Pull Request.
Obviously, we are looking for a fresh solution, not based on others' code.
go test && go build
$ ./quiz /path/to/word.list
inputted words count 263534
The longest compound word is
antidisestablishmentarianisms
It has 29 characters
It consists of the following words:
[anti disestablishmentarian isms]
- Since we want the biggest compound word, sort all the words by length - biggest goes first
- For each word (
compoundWordCandidate
) starting from the first (biggest), find other words - its substrings and put them tosubWords
slice.
for _, compoundWordCandidate := range sortedWords {
var subWords []string
for _, partWordCandidate := range sortedWords {
if compoundWordCandidate == partWordCandidate {
continue
}
if !strings.Contains(compoundWordCandidate, partWordCandidate) {
continue
}
subWords = append(subWords, partWordCandidate)
validParts := getCompoundParts(compoundWordCandidate, subWords)
if len(validParts) == 0 {
continue
}
compound = compoundWordCandidate
parts = validParts
return
}
}
-
After every append to
subWords
, check if the slice has length more than 1 and try to build the currentcompoundWordCandidate
fromsubWords
using methodgetCompoundParts
. If it returns positive length slice, that's it. CurrentcompoundWordCandidate
is the result of the program - the longest compound word. It consists ofvalidParts
. -
Function
func getCompoundParts(wholeWord string, parts []string) (validParts []string)
cuts off beginning and end ofwholeWord
reducing number of possibleparts
by 2 and calls itself with shorterwholeWord
and lower lengthparts
until has trivial cases whenparts
length is one or two.
Maxim Yefremov upwork profile