Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

All possible permutations of a given String?

Tags:

ruby

How would I do this in Ruby?

p "abc".all_possible_permutations 

Would return:

[   "abc",   "acb",   "bca",   "bac",   "cba",   "cab", ] 

Edit

Thanks to Jakub Hampl:

class String   def all_possible_permutations     self.chars.to_a.permutation.map(&:join)   end end 
like image 783
RyanScottLewis Avatar asked Apr 24 '11 23:04

RyanScottLewis


People also ask

What are all permutations of a string?

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.

How do you find the permutation of a string?

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.

How do you generate all permutations of a string in Python?

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.


1 Answers

%w[a b c].permutation.map &:join 
like image 52
Jakub Hampl Avatar answered Oct 04 '22 14:10

Jakub Hampl