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.
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"]
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With