Anagrams with Ruby
Posted by Sandro Paganotti in
Ruby on Rails -
3 comments
In my spare time I enjoy myself trying to figure out solutions to well-known problems without searching the web nor using third party libraries. It’s just a sort of challenge to keep my coding skills well trained.
Yesterday I challenged myself trying to find the faster way to get all the combination of the letters of a given word (excluding duplicates).
example: "ruby" -->
["ruby", "ruyb", "rbuy", "rbyu", "ryub", "rybu", "urby", "uryb", "ubry", "ubyr", "uyrb", "uybr", "bruy", "bryu", "bury", "buyr", "byru", "byur", "yrub", "yrbu", "yurb", "yubr", "ybru", "ybur"]
My code uses recursion to accomplish the task and is not able to identify at run time duplicates so it’s really far from perfection. I’m going to post it here:
class String
def anagram
chars_size = (chars = self.split('')).size
return chars if chars_size == 1
return [chars,chars.reverse] if chars_size == 2
ret = []; chars.each do |c|
(temp = chars.clone).delete_at(chars.index(c));
ret += temp.to_s.anagram.collect{|a| "#{c}#{a}" }
end
return ret.uniq
end
end
If you want to share a better solution please use the comment form below to link your code (you can use Pastie) or just to suggest changes.
Sandro


Comments
fido
Posted on July 27
Rob
Posted on August 01
dominic
Posted on August 08