I've been developing an algorithm to calculate anagrams for a given (set of) word(s). I just got it to work, with ONE incredibly frustrating exception (no pun intended; there is no actual exception being thrown). Despite my attempts to utilize effective "pruning" to decrease the number of repititions, my algorithm is adding duplicate to the master list, in this case an object of type final static ArrayList(StringBuilder)(). I can't seem to figure out why this is happening. Below is my code; i decided to post the entire method for convenience.
This is an assignment for school, so rather then a straight answer/solution, I'm looking for guidance/conceptual mistakes on my end.
EDIT: (code edited out to avoid possible plagiarism prior to the assignment's due date.)
Here is an example:
**input:**
pnxish
bauelqbs
coxiuqit
elbarcbs
ptos
**output:**
Now printing anagrams:
Anagram #0: sphinx
Anagram #1: squabble
Anagram #2: squabble
Anagram #3: quixotic
Anagram #4: quixotic
Anagram #5: scrabble
Anagram #6: scrabble
Anagram #7: pots
Anagram #8: post
Anagram #9: tops
Anagram #10: opts
Anagram #11: spot
Anagram #12: stop
Thanks for the help! :)
The obvious algorithm (just swapping letters) is a bit naive, and doesn't consider identical letters as instances of the same letter. For example, If you have a word like "eve", the two "e"s are distinct; if we bold the first E for purpose of illustration, you get combinations like "e v e" and "e v e" at various points in the process.
You need to somehow eliminate the duplicates. The easiest way to do so is to stuff the combos into a Set of some type (like a HashSet). It can only contain one of each item, so the duplicates will effectively be discarded.
Oh, and use String
s, not StringBuilder
s. I just noticed you were doing that. StringBuilder
doesn't override equals
, so you're left with the version inherited from Object
. End result: for two StringBuilders a
and b
, a.equals(b)
only if a == b
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With