配列の順列の列挙

class Array
  def perm()
    if self.length <= 1 then
      [self]
    else
      a=self[1..-1].perm;
      c=[];
      a.each { |x|
        0.upto(x.length) { |y|
          c.push( (y==0 ? [] : x[0..y-1]) +
                  [ self[0] ] +
                  x[y..-1])
        }
      }
      c.uniq
    end
  end
end

"123".split(//).perm.each{ |x|
  p x
}

["1", "2", "3"]
["2", "1", "3"]
["2", "3", "1"]
["1", "3", "2"]
["3", "1", "2"]
["3", "2", "1"]

ruby 1.9 ではArrayクラスにある

(2007-12-18T22:27:03+0900)
C++だと std::next_permutation
http://cplusplus.com/reference/algorithm/next_permutation.html