Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Produce all permutations of a number's digits

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

I don't like my solution, because it used .times to add the numbers to the array, and thus is still fallible, and furthermore ugly. Is there a way that the numbers could be added to the array the perfect number of times, so that as soon as all the possible shufflings of the numbers have 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
like image 757
maudulus Avatar asked May 14 '26 05:05

maudulus


2 Answers

Do as below using 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
like image 152
Arup Rakshit Avatar answered May 15 '26 19:05

Arup Rakshit


For your method it will be:

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]
like image 28
zishe Avatar answered May 15 '26 17:05

zishe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!