Perform all permutations of numbers

I recently solved a problem that takes a 3-4-digit number, like 1234 (as well as some large numbers) and returns a sorted array of ALL possible permutations of numbers[1234, 1432, 4213, 2431, 3412, 3214, etc.]

I don't like my solution because it used .times to add numbers to the array, and therefore is still erroneous, much less ugly. Is there a way that numbers can be added to the array an ideal number of times, so that as soon as all possible shuffling of numbers has been reached, the program will stop and return the array?

def number_shuffle(number)
  array = []
  number = number.to_s.split(//)
  1000.times{ array << number.shuffle.join.to_i}
  array.uniq.sort
end
+3
source share
2 answers

Do as below Array#permutation:

>> a = 1234.to_s.chars
=> ["1", "2", "3", "4"]
>> a.permutation(4).to_a
=> [["1", "2", "3", "4"],
 ["1", "2", "4", "3"],
 ["1", "3", "2", "4"],
 ["1", "3", "4", "2"],
 ["1", "4", "2", "3"],
 ["1", "4", "3", "2"],
 ["2", "1", "3", "4"],
 ["2", "1", "4", "3"],...]

Your modified method will be:

def number_shuffle(number,size)
  number.to_s.chars.permutation(size).to_a
end
+4

:

def number_shuffle(number)
  a = number.to_s.chars
  a.permutation(a.size).to_a.map { |b| b.join.to_i }
end

p number_shuffle 123 # => [123, 132, 213, 231, 312, 321]
+1

All Articles