Skip to main content

Print all permutations of a string in swift

Swift program for Print all permutations of a string. Here problem description and explanation.

import Foundation
// Swift 4 program for
// Print all permutations of a string
class Permutation
{
	// Swapping two string elements by index
	func swap(_ info: String, 
              _ size: Int, 
              _ a: Int, 
              _ b: Int) -> String
	{
      	let text = info;
		 if ((a >= 0 && a < size) && 
             (b >= 0 && b < size)) {
            var result = Array(text)
            result.swapAt(a, b)
            return String(result)
        }
        return text;
	}
	// Method which is print all permutations of given string
	func findPermutation(_ info: String, 
                         _ n: Int, 
                         _ size: Int)
	{
		if (n > size)
		{
			return;
		}
		if (n == size)
		{
			print(info);
			return;
		}
			var text = info;
			var i: Int = 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;
			}
	
	}
	static func main(_ args: [String])
	{
		let task: Permutation? = Permutation();
		var text: String = "ABC";
		var size: Int = text.count;
		task!.findPermutation(text, 0, size);
		print();
		text = "abcd";
		size = text.count;
		task!.findPermutation(text, 0, size);
	}
}
Permutation.main([String]());

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




Comment

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