打印

全排列

全排列

以前用C写很长的, 现在好象比较简单

def pailie(list)
    return [[list[1]],[list[0]]]if (2 == list.size)
    newlist = []
    list.each() {|i| pailie(list - ).each {|j| newlist.push + j}}
    newlist
end

puts pailie([1,2,3,4]).inspect

TOP



list.each() {|i| pailie(list - ).each {|j| newlist.push + j}}


括号里面漏了一段?

TOP

括号里是 list - 吧,可是即使加上了还是不对,等解。。。。

TOP

。。。。。。。。。发个帖真费劲。。。。。括号里是 list - 左中括号 i 右中括号。。。。。

TOP

“newlist.push + j ” 这个不明白,而且下面一行应该是“return newlist” 吗?

TOP

该不是想实现 数组的逆排吧?

一个 reverse 或者 reverse! 不就搞定了???

TOP

完整的代码是这样么?

def pailie(list)
    return [[list[1]],[list[0]]]if (2 == list.size)
    newlist = []
    list.each() {|i| pailie(list - [i]).each {|j| newlist.push + j}}
    newlist
end

puts pailie([1,2,3,4]).inspect


在我的电脑上似乎并不工作 (Ubutnu 7.10, ruby 1.8.6)

TOP

看明白了,是排列组合,稍微改动了一下,看起来舒服点

def pailie(list)
    return [list] if (1 == list.size)
    newlist = []
    list.each {|i| pailie(list - [i]).each {|j| newlist.push [i] + j}}
    return newlist
end

p pailie([1,2,3,4])


输出结果如下:

[[1, 2, 3, 4], [1, 2, 4, 3], [1, 3, 2, 4], [1, 3, 4, 2], [1, 4, 2, 3], [1, 4, 3, 2], [2, 1, 3, 4], [2, 1, 4, 3], [2, 3, 1, 4], [2, 3, 4, 1], [2, 4, 1, 3], [2, 4, 3, 1], [3, 1, 2, 4], [3, 1, 4, 2], [3, 2, 1, 4], [3, 2, 4, 1], [3, 4, 1, 2], [3, 4, 2, 1], [4, 1, 2, 3], [4, 1, 3, 2], [4, 2, 1, 3], [4, 2, 3, 1], [4, 3, 1, 2], [4, 3, 2, 1]]

TOP

很好,佩服楼上。。。。加紧学习。。。。。也谢谢楼主和管理员

TOP

。。。劳驾再问下,p pailie([1,2,3,4]) 中开始的那个“p”是什么啊?

TOP

Changes in Ruby 1.9

Array#combination
ary.combination(n){|c| ...}

yields all the combinations of length n of the elements in the array to the given block. If no block is passed, it returns an enumerator instead. The order of the combinations is unspecified.

 a = [1, 2, 3, 4]
 a.combination(1).to_a  #=> [[1],[2],[3],[4]]
 a.combination(2).to_a  #=> [[1,2],[1,3],[1,4],[2,3],[2,4],[3,4]]
 a.combination(3).to_a  #=> [[1,2,3],[1,2,4],[1,3,4],[2,3,4]]
 a.combination(4).to_a  #=> [[1,2,3,4]]
 a.combination(0).to_a  #=> [[]]: one combination of length 0
 a.combination(5).to_a  #=> []  : no combinations of length 5


ruby-list:42671
Array#permutation
ary.permutation(n){|c| ...}

Operates like #combination, but with permutations of length n.

 
a = [1, 2, 3]
 a.permutation(1).to_a  #=> [[1],[2],[3]]
 a.permutation(2).to_a  #=> [[1,2],[1,3],[2,1],[2,3],[3,1],[3,2]]
 a.permutation(3).to_a  #=> [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
 a.permutation(0).to_a  #=> [[]]: one permutation of length 0
 a.permutation(4).to_a  #=> []  : no permutations of length 4


TOP

p( [ anObject ]+ ) -> nil 

For each object, directly writes anObject.inspect followed by the current output record separator to the program's standard output. p bypasses the Ruby I/O libraries

TOP

2008-12-05 05:14 Crawled by CCBot/1.0 (+http://www.commoncrawl.org/bot.html) @38.103.63.61