Skip to content

Commit 5eb49ed

Browse files
committed
Find permutation of string.
1 parent efbf759 commit 5eb49ed

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

Algorithm-Recursions/permutation.rb

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
=begin
2+
Write a program to print all permutations of a given string
3+
A permutation, also called an “arrangement number” or “order,” is a rearrangement of the elements of an ordered list S into a one-to-one correspondence with S itself. A string of length n has n! permutation.
4+
Source: Mathword(http://mathworld.wolfram.com/Permutation.html)
5+
6+
Below are the permutations of string ABC.
7+
ABC ACB BAC BCA CBA CAB
8+
=end
9+
10+
# Time complexity: O(2^n)
11+
def permutation(arr, l, r)
12+
if(l == r)
13+
p arr.join.to_s
14+
else
15+
for i in (l..r)
16+
arr[i], arr[l] = arr[l], arr[i]
17+
permutation(arr, l+1, r)
18+
arr[i], arr[l] = arr[l], arr[i]
19+
end
20+
end
21+
end
22+
23+
a = ['a', 'b', 'c']
24+
permutation(a, 0, a.size-1)

0 commit comments

Comments
 (0)