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

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

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]

Need Your Help

JFreeChart Large Data Can't Read Axis

java graph jfreechart

I am using JFreeChart to plot a line graph. The app reads in sensory data every 100 milliseconds so for a few minutes of capture it's a a lot of data. I don't plot the graph dynamically, it is stat...

Name cannot begin with the ' ' character

c# xml memorystream xmltextreader

I'm parsing some XML in C#. I'm getting it from a database, and so converting it to a MemoryStream before reading it with an XmlTextReader. The problem is that I get this error: Name cannot begin w...