Print all permutations of a string in ruby
Ruby program for Print all permutations of a string. Here more information.
# Ruby program for
# Print all permutations of a string
class Permutation
# Swapping two string elements by index
def swap(text, size, a, b)
# Check valid location of swap element
if ((a >= 0 && a < size) && (b >= 0 && b < size))
# Get first character
first = text[a]
text[a]=text[b]
text[b]=first
end
return text
end
# Method which is print all permutations of given string
def findPermutation(text, n, size)
if (n > size)
return
end
if (n == size)
print(text, "\n")
return
end
i = n
while (i < size)
# Swap the element
text = self.swap(text, size, i, n)
self.findPermutation(text, n + 1, size)
# Swap the element
text = self.swap(text, size, i, n)
i += 1
end
end
end
def main()
task = Permutation.new()
text = "ABC"
size = text.length
task.findPermutation(text, 0, size)
print("\n")
text = "abcd"
size = text.length
task.findPermutation(text, 0, size)
end
main()
Output
ABC
ACB
BAC
BCA
CBA
CAB
abcd
abdc
acbd
acdb
adcb
adbc
bacd
badc
bcad
bcda
bdca
bdac
cbad
cbda
cabd
cadb
cdab
cdba
dbca
dbac
dcba
dcab
dacb
dabc
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment