Forum: Ruby on Rails rearranging the letters of a word

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
919a5821a43ae5fc35a495d20682544e?d=identicon&s=25 railsbugs@gmail.com (Guest)
on 2009-04-01 14:45
(Received via mailing list)
Hello there,


     I have to rearrange the letters of a word in all possible ways in
my rails application.I am not getting the exact way doing so, please
can anybody help me in developing that logic.

Thank you in advance.
53be54e5db4dc58e4980db5a8255621b?d=identicon&s=25 Harold (Guest)
on 2009-04-01 15:35
(Received via mailing list)
# Based on:
# http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/...
# Author: Endy Tjahjono

class String
   def perm
       return [self] if self.length < 2
       ret = []

       0.upto(self.length - 1) do |n|
          #rest = self.split('')
          rest = self.split(//u)            # for UTF-8 encoded
strings
          picked = rest.delete_at(n)
          rest.join.perm.each { |x| ret << picked + x }
       end

       ret
   end
end

p "abc".perm      #=>  ["abc", "acb", "bac", "bca", "cab", "cba"]
This topic is locked and can not be replied to.