سؤال

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
هل كانت مفيدة؟

المحلول

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]
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top