Print all permutations of a string in typescript
Ts program for Print all permutations of a string. Here problem description and explanation.
// TypeScript program for
// Print all permutations of a string
class Permutation
{
// Swapping two string elements by index
public string swap(text: string,
size: number,
a: number,
b: number)
{
// Check valid location of swap element
if ((a >= 0 && a < size) && (b >= 0 && b < size))
{
// Get first character
var first = text.charAt(a);
// Get second character
var second = text.charAt(b);
// Put character
text = text.substring(0, b) +
first + text.substring(b + 1);
text = text.substring(0, a) +
second + text.substring(a + 1);
}
return text;
}
// Method which is print all permutations of given string
public findPermutation(text: string,
n: number,
size: number)
{
if (n > size)
{
return;
}
if (n == size)
{
console.log(text);
return;
}
for (var i = n; i < size; ++i)
{
// Swap the element
text = this.swap(text, size, i, n);
this.findPermutation(text, n + 1, size);
// Swap the element
text = this.swap(text, size, i, n);
}
}
public static main(args: string[])
{
var task = new Permutation();
var text = "ABC";
var size = text.length;
task.findPermutation(text, 0, size);
console.log();
text = "abcd";
size = text.length;
task.findPermutation(text, 0, size);
}
}
Permutation.main([]);
/*
file : code.ts
tsc --target es6 code.ts
node code.js
*/
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