Meino,
I want to produce from a give string all permutations of its
characters.Building all permutations of something is a typical recursive task.
But in this case I dont want a recursive solution...
In addition to the other responses, I thought I'd throw in the
following home-grown solution with no recursion whatsoever:
def factorial(number)
(2..number).inject(1) { |product,current_number| product *=
current_number }
end
def get_permutation(array,permutation_number)
number_of_permutations = factorial(array.length)
return nil unless (0...number_of_permutations) ===
permutation_number
array_copy = array.dup
result =
(array.length - 1).times do
number_of_permutations /= array_copy.length
next_element,permutation_number =
permutation_number.divmod(number_of_permutations)
result << array_copy.delete_at(next_element)
end
result + array_copy
end
The nice thing about this solution is that returns permutations in
"alphabetical order". In other words, if you feed it a string like
"ABC", permutations 0..5 will be in alphabetical order:
str = "ABC"
factorial(str.length).times { |i| puts
get_permutation(str.split(//),i).join }
produces:
ABC
ACB
BAC
BCA
CAB
CBA
I hope this helps, or at least gives someone another way of looking
at permutations.
- Warren Brown