【发布时间】:2014-12-30 00:43:10
【问题描述】:
我正在解决关于 Ruby Monk 的 Ruby Primer 的问题。
问题陈述 给定一个具有不同数字的 3 或 4 位数字,返回可以由这些数字组成的所有唯一数字的排序数组。 例子: 给定:123 返回:[123、132、213、231、312、321]
我认为 Array#combination 方法可以解决问题。我的代码如下所示:
def number_shuffle(number)
# take integer and turn it into an array of digits
digits = Array.new
number.to_s.split('').each do |element|
digits << element.to_i
end
# shuffle the elements
return digits.combination(digits.length).to_a
end
puts number_shuffle(123)
但是上面的代码返回:
1
2
3
不知道我在这里做错了什么。我认为文档说得很清楚:
http://www.ruby-doc.org/core-2.2.0/Array.html#method-i-combination
感谢任何帮助。
【问题讨论】:
-
对于
number = 123,计算[1,2,3].combination(3).to_a => [[1,2,3]]和puts [[1,2,3]]将在连续的行上打印1、2和3。相比之下,p [[1,2,3]]在一行上打印[[1, 2, 3]]。你得到这个结果是因为每个数组a只有一个大小组合a.size,即a,所以返回[a]。另一方面,[1,2,3].combination(1).to_a => [[1], [2], [3]]和[1,2,3].combination(2) => [[1, 2], [1, 3], [2, 3]]。我相信您知道您需要使用permutation而不是combination。