r/visualbasic • u/Bonejob VB Guru • May 09 '15
(medium)Find the longest word given a set of letters and a dictionary.
I ran across this the when I was searching for programming questions asked at interviews. This one is from Google.
Find the longest words in a given list of words that can be constructed from a given list of letters. Your solution should take as its first argument the name of a plain text file that contains one word per line. The remaining arguments define the list of legal letters. A letter may not appear in any single word more times than it appears in the list of letters (e.g., the input letters ‘a a b c k’ can make ‘back’ and ‘cab’ but not ‘abba’).
Here's an example of how it should work:
Enter your letters: w g d a s x z c y t e i o b
['azotised', 'bawdiest', 'dystocia', 'geotaxis', 'iceboats', 'oxidates', 'oxyacids', 'sweatbox', 'tideways']They should be ordered from longest word to shortest returning no more than 20 words.
I personally am going to take some time with this one, I am going to try to solve a couple of ways, starting with LINQ,and moving down to old school brute force algorithms.
Just thought I would give you guys a head start :)
HINT: look up trie problems.
Here is the Debian American English Dictionary as a copy-pasta :)
Edit: After spending a couple of days on this, trying new technologies to create a solution I came to the conclusion that sometime the old ways are the best ways.
Edit 2: If this is what it takes to get into Google I am glad I don't work for them. I could not even imagine coming up with this from scratch. Need a freaking CS degree :)
Edit 3: I agree guys this is a HARD one not a medium one ;)
2
u/PreyOnTheCosmos May 12 '15 edited May 12 '15
Wow... Thanks for making my brain explode and wrecking any hope of ever working for Google.
I was finally able to accomplish this, but it took me a couple days of toying with it and I'm certain there are much more efficient ways of doing it, since what I ended up with is really odd. :-P
The effective code is essentially 1 Sub and 1 function: The IsMatch() Function - I break the constructor string and the target word down to character lists for easy handling. Then I produce a target "WordValue" that is a sum of the contained bytes in the target Word. I then loop the supplied "random" characters and systematically subtract the bytes from the total. If the total is reduced to zero, then all letters have been matched and the function returns true. Weird, I know - but it worked! :-P
Private Function IsMatch(Values As String, Word As String) As Boolean
Dim CharList As List(Of Char) = Values.ToLower.ToList
Dim WordList As List(Of Char) = Word.ToLower.ToList
Dim WordVal As Integer
WordList.ToList.ForEach(Sub(c) WordVal += Convert.ToByte(c))
For Each c As Char In CharList
If WordList.Contains(c) Then
WordVal -= Convert.ToByte(c)
WordList.Remove(c)
End If
Next
If WordVal > 0 Then Return False
Return True
End FunctionThe ScanAll() Sub - This just clears my output box and runs lambdas for the IsMatch and sorting (to get the longest matches first, as part of the criteria), and limit the search results according to a specified value.
Private Sub ScanAll()
txtOutput.Clear()
Dim lstOut As New List(Of String)
Words.ToList.ForEach(Sub(k) If IsMatch(txtScan.Text, k.Value) Then lstOut.Add(k.Value))
lstOut.Sort(Function(a As String, b As String) a.Length.CompareTo(b.Length))
lstOut.Reverse()
Dim count As Integer
For Each line As String In lstOut
count += 1
txtOutput.AppendText(line & vbNewLine)
If IsNumeric(txtLimit.Text) AndAlso count >= txtLimit.Text Then Exit Sub
Next
End SubThere is one other small sub that just loads my dictionary from a text file into a Dictionary collection that I run the scans against. I omitted it here since it wasn't really part of the objective.
I'd share an output pic but I'm a reddit n00b and don't know how in comments. [Edit: I think I got it]
1
u/Bonejob VB Guru May 12 '15
Great idea, I had not thought to attack the problem like that. How is it for speed?
2
u/JakDrako May 13 '15
It's pretty good on speed. Those computer thingies are fast, man.
From my tests, the IsMatch can plow through the entire dictionary in about 2 tenths of a second.
2
u/JakDrako May 13 '15
That's a cool approach. While playing with it, I noticed that the IsMatch function can be simplified a bit:
Private Function IsMatch2(Values As String, Word As String) As Boolean Dim CharList As List(Of Char) = Values.ToLower.ToList Dim WordList As List(Of Char) = Word.ToLower.ToList For Each c As Char In CharList If WordList.Contains(c) Then WordList.Remove(c) End If Next Return not WordList.Any End FunctionIt's about 10% faster too.
I really like the simplicity of this approach. Kudos.
1
u/PreyOnTheCosmos May 13 '15 edited May 13 '15
Yes, indeed! :-) I'd noticed that just after I posted last night, but I had to run out and didn't get a chance to clean it up. I was going to throw that whole loop in a lambda, which would simplify it a tiny bit more.
Private Function IsMatch(Values As String, Word As String) As Boolean Dim CharList As List(Of Char) = Values.ToLower.ToList Dim WordList As List(Of Char) = Word.ToLower.ToList CharList.ForEach(Sub(c) If WordList.Contains(c) Then WordList.Remove(c)) Return Not WordList.Any End FunctionThe whole byte conversion thing was a byproduct of my experimentation with creating word "signatures" for the dictionary to reduce the number of words needed to be scanned and significantly improve the seek time in large dictionaries.
1
u/Bonejob VB Guru May 10 '15
ok this one hurt my brain. I tried a few implementations including a Regex (did not get it to work), bruteforce (had to have a nap while I waited), and even a LINQ function which worked great until I had 2 letters the same. The best I found was an algorithm I used way back in the day in C.
Here is the original paper on the Gaddag data structure written by Steven Gordon
Imports System.Collections
Imports System.Collections.Generic
Imports System.Collections.Specialized
Imports System.Linq
Imports System.IO
Imports System.Text
Module Module1
Sub Main()
Console.WriteLine("Reading Dictionary")
Dim newGaddag As New Gaddag
Using reader As StreamReader = New StreamReader("american-english")
Do Until reader.EndOfStream
Dim line As String = reader.ReadLine
newGaddag.Add(line)
Loop
End Using
Console.WriteLine("Dictionary load complete")
Dim getKey As ConsoleKeyInfo
Do
Console.WriteLine()
Console.Write("Please enter your letters: ")
Dim letters As String = Console.ReadLine()
Dim newList As List(Of String) = newGaddag.GetWords("", letters)
newList.Sort(Function(s1, s2) s2.Length.CompareTo(s1.Length)) 'Note: This lambda expression sets the sort to sort by length
Dim stringOut As New StringBuilder
stringOut.Append("[")
For x = 1 To 20
stringOut.Append("'")
stringOut.Append(newList(x))
stringOut.Append("', ")
Next
stringOut.Append("]")
Console.WriteLine(stringOut.ToString)
Console.WriteLine()
Console.WriteLine("Again? (n to close)")
getKey = Console.ReadKey()
Loop While getKey.Key <> ConsoleKey.N
End Sub
Public Class Gaddag
Public Property RootNode() As Node
Public Sub New()
RootNode = New Node() With {.Letter = Node.Root}
End Sub
Public Sub Add(word As String)
Dim w = word.ToLower()
Dim prevNode = New List(Of Node)()
For i = 1 To w.Length
Dim prefix = w.Substring(0, i)
Dim suffix = ""
If i <> w.Length Then
suffix = w.Substring(i, w.Length - (i))
End If
Dim addword = (ReverseString(prefix) & Node.Break) + suffix + Node.Eow
Dim currentNode = RootNode
Dim breakFound = False
Dim j As Integer = 0
For Each c In addword
'Long words can be joined back together after the break point, cutting the tree size in half.
If breakFound AndAlso prevNode.Count > j Then
currentNode.AddChild(c, prevNode(j))
Exit For
End If
currentNode = currentNode.AddChild(c)
If prevNode.Count = j Then
prevNode.Add(currentNode)
End If
If c = Node.Break Then
breakFound = True
End If
j += 1
Next
Next
End Sub
Private Shared Function GetWord(str As String) As String
Dim word = ""
For i = str.IndexOf(Node.Break) - 1 To 0 Step -1
word += str(i)
Next
For i = str.IndexOf(Node.Break) + 1 To str.Length - 1
word += str(i)
Next
Return word
End Function
Public Function GetWords(hook As String, rack As String) As List(Of String)
hook = hook.ToLower()
hook = ReverseString(hook)
Dim [set] = New HashSet(Of String)()
ContainsHookWithRackRecursive(RootNode, [set], "", rack, hook)
Return [set].ToList()
End Function
Private Shared Sub ContainsHookWithRackRecursive(node1 As Node, rtn As ISet(Of String), letters As String, rack As String, hook As String)
' Null nodes represent the EOW, so return the word.
If node1 Is Nothing Then
Dim w = GetWord(letters)
If Not rtn.Contains(w) Then
rtn.Add(w)
End If
Return
End If
' If the hook still contains letters, process those first.
If Not [String].IsNullOrWhiteSpace(hook) Then
letters += If(node1.Letter <> Node.Root, node1.Letter.ToString(), "")
If node1.ContainsKey(hook(0)) Then
Dim h = hook.Remove(0, 1)
'Pop the letter off the hook
ContainsHookWithRackRecursive(node1(hook(0)), rtn, letters, rack, h)
End If
Else
letters += If(node1.Letter <> Node.Root, node1.Letter.ToString(), "")
For Each key In node1.Keys.Cast(Of Char)().Where(Function(k) rack.Contains(k) OrElse k = Node.Eow OrElse k = Node.Break)
Dim r = If((key <> Node.Eow AndAlso key <> Node.Break), rack.Remove(rack.IndexOf(key), 1), rack)
'Pull the letter from the rack
ContainsHookWithRackRecursive(node1(key), rtn, letters, r, hook)
Next
End If
End Sub
Private Shared Function ReverseString(str As String) As String
Dim charArray = str.ToCharArray()
Array.Reverse(charArray)
Return (New [String](charArray))
End Function
End Class
Public Class Node
Public Const Break As Char = ">"c
Public Const Eow As Char = "$"c
Public Const Root As Char = " "c
Public Property Letter() As Char
Public Property Children() As HybridDictionary
Public Sub New()
End Sub
Public Sub New(letter As Char)
Me.Letter = letter
End Sub
Default Public ReadOnly Property Item(index As Char) As Node
Get
Return DirectCast(Children(index), Node)
End Get
End Property
Public ReadOnly Property Keys() As ICollection
Get
Return Children.Keys
End Get
End Property
Public Function ContainsKey(key As Char) As Boolean
Return Children.Contains(key)
End Function
Public Function AddChild(letter As Char) As Node
If Children Is Nothing Then
Children = New HybridDictionary()
End If
If Not Children.Contains(letter) Then
Dim node = If(letter <> Eow, New Node(letter), Nothing)
Children.Add(letter, node)
Return node
End If
Return DirectCast(Children(letter), Node)
End Function
Public Function AddChild(letter As Char, node As Node) As Node
If Children Is Nothing Then
Children = New HybridDictionary()
End If
If Not Children.Contains(letter) Then
Children.Add(letter, node)
Return node
End If
Return DirectCast(Children(letter), Node)
End Function
Public Overrides Function ToString() As String
Return Me.Letter.ToString()
End Function
End Class
End Module2
u/JakDrako May 11 '15
Nice. I also learned about HybridDictionary, so thanks for that.
Any particular reason you wrote your own ReverseString instead of using VB's StrReverse?
1
u/Bonejob VB Guru May 11 '15
No, that was me forgetting the built in function. Somedays I make way too much work for myself.
1
u/PostalElf VB.Net Intermediate May 09 '15
Someone please tell me how stupid this idea is.
First of all, you'll need a text file containing all the words you'll want to check against. Pull the data and put them in a list that we'll call OED (Oxford English Dictionary; yes, even though it's a list).
Now we start scrambling the input letters! ... something which I have no idea where to even begin doing. I'm gonna think on this a little and edit my post when I get some ideas. But is this plan of attack stupid? The idea is that you scramble the letters into as many possible combinations as possible, then compare them against the OED. Seems very resource-intensive to me, but also seems the most comprehensive.
2
u/Bonejob VB Guru May 09 '15
Actually this is a brute force method. The trick is to make it faster. The dictionary I provided is just short of 100k entries, say you have 15 letters, this gives you 1.30767E+12 (15 Factorial) potential combinations of those letters. so while possible not probable :)
One of the ways to make this faster is to pick a letter at random from you characters set. Reduce your dictionary set to all words that begin with that letter. Then grab the first word from the set scan through all chars in the word to see if you have the chars in your available pool of characters. This speeds it up.
This is how I brute forced it. The problem I had was it started with the smallest words first. Since I am trying to find the longest words it was still really slow.
This leads into creating algorithms based upon english language weighting, meaning "there are more e's than any other letter," and there are some fast implementations based upon this.
Your method would work as described though.
2
u/jackrackham19 VB.Net Advanced May 09 '15
Well, as your intuition tells you, it is an inefficient way to do it. Think of ways to add more structure. Is a list this best way to hold the dictionary? Can you do a better job of using the letters than simply scrambling them? Start from where you're at, and make incremental changes. If you want some more hints, I can tell you which two data structures I would use for this problem :)
2
u/JakDrako May 09 '15
Is it too much of a head start if I already have a solution from doing a similar problem on a "programming challenges" site? :)