Question Anagram Solver - Need Help Please!

joeinnes

New member
Joined
Oct 7, 2009
Messages
4
Programming Experience
1-3
I am making an anagram solver.
I have written a function to solve the anagram, with two parameters; "Anagram" (the scrambled string) and "Dictionary" (the arraylist of words).
I am confused! Sometimes it solves it correctly, 99% of the time, it doesn't - im not sure where I have gone wrong!

Here is my code:

Private Function SolveAnagram(ByVal Anagram As String, ByVal Dictionary As ArrayList)
Dim solved As String = ""
Dim inputarray As Array = Anagram.ToCharArray
Dim charcount As Integer = Anagram.Length
Dim check As Integer = 0
Dim exiting As Boolean = False
For i As Integer = 0 To Dictionary.Count - 1
If Dictionary.Item(i).ToString.Length = charcount Then
For Each character As Char In inputarray
If Dictionary.Item(i).ToString.Contains(character) Then
check += 1
Else
Exit For
End If
Next
If check = charcount Then
solved = Dictionary.Item(i).ToString
exiting = True
End If
End If
If exiting = True Then
Exit For
End If
Next
If solved = "" Then
MsgBox("Failed to solve anagram", MsgBoxStyle.Exclamation)
End If
Return solved
End Function

Thanks in advance! :D
 
You can't do a For-Each-Contains with the anagram word chars and the list word chars, because if former for example contains two 'a' and latter contains only one you get True result for both. You have to match each char only once. Here is a function that does that, it sorts both arrays and check if each char in both arrays is the same:
VB.NET:
Private Function IsAnagram(ByVal word1() As Char, ByVal word2() As Char) As Boolean
    If word1.Length = word2.Length Then
        Array.Sort(word1)
        Array.Sort(word2)
        Return word1.SequenceEqual(word2)
    End If
End Function
usage sample:
VB.NET:
Dim anagram As String = "test"        
Dim lookup As String = "tste"
Dim match As Boolean = IsAnagram(anagram.ToArray, lookup.ToArray)
Your profile says your using VB 2008 so SequenceEqual extension should be good, if not you can do the same by checking each char in both arrays (For-Next, return False if any is different, return True after Next).
 
Back
Top