Ruby On Rails, Design, Simplicity, Web 2.0, Ajax, Mac and Tons of Pizza.

Jul 25

Anagrams with Ruby

Posted by Sandro Paganotti in Ruby on Rails - 3 comments digg this add to delicious

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

    There's also a snippet over at http://snippets.dzone.com/posts/show/3332 (by Endy Tjahjono) So which one is faster?
  • Rob

    Posted on August 01

    I've used the Endy Tjahjono snippet mentioned by fido before too. I've just run a couple of quick benchmarks and your anagram method came out between 2 and 5 seconds faster over 10,000 iterations...nice work!
  • dominic

    Posted on August 08

    check out http://pragdave.blogs.pragprog.com/pragdave/2008/01/pipelines-using.html where he uses ruby 1.9 new coroutines (fibers)

Post a comment

Categories:

Tags:

Powered by Mephisto, Valid XHTML 1.1, Valid CSS - Supported by Wave Factory