红宝石 |数组组合()操作
Array#combination() :combination()是一个 Array 类方法,它使用一个块调用,产生数组元素长度为“n”的所有组合。
Syntax: Array.combination()
Parameter: Arrays in which we want elements to be invoked
Return: all combinations of length 'n' of elements of the array.
代码 #1:combination() 方法的示例
# Ruby code for combination() method
# declaring array
a = [1, 2, 56, 23]
# combination of length 2
puts "combination a : #{a.combination(2).to_a}\n\n"
# combination of length 3
puts "combination a : #{a.combination(3).to_a}\n\n"
输出 :
combination a : [[1, 2], [1, 56], [1, 23], [2, 56], [2, 23], [56, 23]]
combination a : [[1, 2, 56], [1, 2, 23], [1, 56, 23], [2, 56, 23]]
代码 #2:combination() 方法的示例
# Ruby code for combination() method
# declaring array
a = [[1, 2, 56, 23],
[34, 54, 23, 1]]
# combination of length 2
puts "collect a : #{a.combination(2).to_a}\n\n"
# combination of length 1
puts "collect a : #{a.combination(1).to_a}\n\n"
输出 :
collect a : [[[1, 2, 56, 23], [34, 54, 23, 1]]]
collect a : [[[1, 2, 56, 23]], [[34, 54, 23, 1]]]