Ruby 数组permutation()函数

Ruby 数组permutation()函数

Array#permutation() : permutation()是Array类的一个方法,它返回数组中所有长度为n的元素的排列组合,然后返回数组本身。

语法。Array.permutation()

参数。数组

返回:所有长度为n的数组元素的排列组合,然后返回数组本身。

例子 #1 :

# Ruby code for permutation() method
  
# declaring array
a = [18, 22, 33, nil, 5, 6]
  
# declaring array
b = [1, 4, 1, 1, 88, 9]
  
# declaring array
c = []
  
# permutation method example
puts "permutation() method form : #{a.permutation(2).to_a}\n\n"
  
puts "permutation() method form : #{b.permutation(1).to_a}\n\n"
  
puts "permutation() method form : #{c.permutation(4).to_a}\n\n"

输出:

permutation() method form : [[18, 22], [18, 33], [18, nil], [18, 5], [18, 6], [22, 18], [22, 33], [22, nil], [22, 5], [22, 6], [33, 18], [33, 22], [33, nil], [33, 5], [33, 6], [nil, 18], [nil, 22], [nil, 33], [nil, 5], [nil, 6], [5, 18], [5, 22], [5, 33], [5, nil], [5, 6], [6, 18], [6, 22], [6, 33], [6, nil], [6, 5]]

permutation() method form : [[1], [4], [1], [1], [88], [9]]

permutation() method form : []

例子 #2 :

# Ruby code for permutation() method
  
# declaring array
a = ["abc", "nil", "dog"]
  
# declaring array
c = [nil]
  
# declaring array
b = ["cow", nil, "dog"]
  
# permutation method example
puts "permutation() method form : #{a.permutation(2).to_a}\n\n"
  
puts "permutation() method form : #{b.permutation(1).to_a}\n\n"
  
puts "permutation() method form : #{c.permutation(4).to_a}\n\n"

输出:

permutation() method form : [["abc", "nil"], ["abc", "dog"], ["nil", "abc"], ["nil", "dog"], ["dog", "abc"], ["dog", "nil"]]

permutation() method form : [["cow"], [nil], ["dog"]]

permutation() method form : []

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程