Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby's Array Combination Method

Tags:

arrays

ruby

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.

like image 306
Steven L. Avatar asked Oct 31 '22 12:10

Steven L.


2 Answers

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"]
like image 96
Matt Avatar answered Nov 15 '22 06:11

Matt


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
like image 22
August Avatar answered Nov 15 '22 06:11

August