How would I do this in Ruby?
p "abc".all_possible_permutations
Would return:
[ "abc", "acb", "bca", "bac", "cba", "cab", ]
Thanks to Jakub Hampl:
class String def all_possible_permutations self.chars.to_a.permutation.map(&:join) end end
A permutation of a string S iis another string that contains the same characters, only the order of characters can be different. For example, “abcd” and “dabc” are permutations of each other.
We can find the count without finding all permutation. Idea is to find all the characters that is getting repeated, i.e., frequency of all the character. Then, we divide the factorial of the length of string by multiplication of factorial of frequency of characters.
To find all possible permutations of a given string, you can use the itertools module which has a useful method called permutations(iterable[, r]). This method return successive r length permutations of elements in the iterable as tuples.
%w[a b c].permutation.map &:join
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With