Reputation: 2155
I am going through the problems on Ruby Monk's Ruby Primer.
Problem Statement Given a 3 or 4 digit number with distinct digits, return a sorted array of all the unique numbers that can be formed with those digits. Example: Given: 123 Return: [123, 132, 213, 231, 312, 321]
I thought that the Array#combination method would do the trick. My code looks like this:
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)
But the code above returns:
1
2
3
Not sure what I'm doing wrong here. I thought the documentation made it clear:
http://www.ruby-doc.org/core-2.2.0/Array.html#method-i-combination
Any help is appreciated.
Upvotes: 5
Views: 4229
Reputation: 24572
For the ruby monk question what u need is the Array.permutations. Array.permutation(n) is the number of possible arrangements of an array taking n at a time. [1,2,3] with n = 1 will be 1, 2, 3 [1,2,3] with n = 2 will be [1,2] [2,1] [1,3] [3,1] [2,3] [3,2]
What you need is
Array.permutations(Array.length)
Array.combination(n) returns the number of unique selections that can be made from the array when taking n objects out of the array.
for an Array [1,2,3] if n = 1. You can only take out one element at a time the possible selections are 1 ,2 and 3.
for an Array [1,2,3] if n= 2. You can take out two elements at a time. the possible selections are [1,2] , [1,3] and [2,3]
You have given the length of the Array as N (N = Array.Length)
So in the case of [1,2,3] if n = 3, There is only one way to make a selection using all the elements. That is [1,2,3]. This is why your code only returns one combination.
Upvotes: 0
Reputation: 12558
You can get the permutations of the character array using Array#permutation
:
def number_shuffle(number)
number.to_s.chars.permutation.map { |x| x.join.to_i }.sort
end
Upvotes: 1
Reputation: 20766
Instead of Array#combination
, you want Array#permutation
:
number = 123
number.to_s.split('').permutation.map(&:join).uniq.sort
# => ["123", "132", "213", "231", "312", "321"]
number = 122
number.to_s.split('').permutation.map(&:join).uniq.sort
# => ["122", "212", "221"]
Upvotes: 2