Ruby Array Combination Method

I am experiencing problems with the Ruby Monk Ruby Primer.

Problem Given a 3 or 4-digit number with even digits, return a sorted array of all the unique numbers that can be formed with these digits. Example: Subject to: 123 Return: [123, 132, 213, 231, 312, 321]

I thought that the Array # combinational method would do the trick. My code is as follows:

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 above code returns:

1
2
3

Not sure what I'm doing wrong here. I thought the documentation was clear:

http://www.ruby-doc.org/core-2.2.0/Array.html#method-i-combination

Any help is appreciated.

+4
source share
3 answers

Instead Array#combinationyou 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"]
+1

, Array#permutation:

def number_shuffle(number)
  number.to_s.chars.permutation.map { |x| x.join.to_i }.sort
end
+1

, , Array.permutations. Array.permutation(n) - , n . [1,2,3] n = 1 1, 2, 3 [1,2,3] n = 2 [1,2] [2,1] [1,3] [3,1] [2,3] [3,2]

   Array.permutations(Array.length)

Array.combination(n) , n .

[1,2,3], n = 1. : 1, 2 3.

[1,2,3], n = 2. . [1,2], [1,3] [2,3]

N (N = Array.Length)

So, in the case of [1,2,3], if n = 3, there is only one way to make a choice using all the elements. This is [1,2,3]. This is why your code returns only one combination.

0
source

Source: https://habr.com/ru/post/1569365/


All Articles