Reputation: 351
I have written the following code in PowerShell to display the permutation and combination for the given string but I am not able to achieve it by recursive functions.
function Swapping1 {
$a = "abc"
$b = $a.ToCharArray()
$c = $b.Length-1
$d = 0
GetPer($b, $d, $c)
}
function GetPer {
Param($list, $k, $m)
[char[]] $list1 = $list[0]
$k = $list[1]
$m = $list[2]
if ($k -eq $m) {
# Write-Host $list1
} else {
for ($i = $k; $i -le 1; $i++) {
$a = $list1[$k]
$b = $list1[$i]
$a, $b = $b, $a
$k = $k+1
Write-Host $list[0]
GetPer($list[0], $k, $m)
$a, $b = $b, $a
}
}
}
The same logic when I write it in C# it is working fine.
private static void Swap(ref char a, ref char b) {
if (a == b) return;
a ^= b;
b ^= a;
a ^= b;
}
private static void GetPermutation(char[] list, int k, int m) {
if (k == m) {
Console.Write(list);
Console.WriteLine();
} else
for (int i = k; i <= m; i++) {
Swap(ref list[k], ref list[i]);
GetPermutation(list, k + 1, m);
Swap(ref list[k], ref list[i]);
}
}
static void Main(string[] args) {
string str = "abc";
char[] arr = str.ToCharArray();
int x = arr.Length - 1;
GetPermutation(arr, 0, x);
//GetPer(arr);
Console.Read();
}
Below is the output when I executed the PowerShell script:
PS C:\WINDOWS\system32> C:\Dorababu\Power Shell\Swapping1.ps1
a b c
a b c
a b c
C# output:
Upvotes: 1
Views: 139
Reputation: 200213
Your C# and PowerShell code do different things. You output at a different place in PowerShell, the condition in the for
loop is different ($i -le 1
vs i <= m
), you increment $k
in the PowerShell code ($k = $k+1
) but not in the C# code, and your swapping as well as the parameter handling are completely wrong. A function call foo(a, b, c)
passes an array a, b, c
to the first parameter of foo()
and nothing to the second and third parameter. The correct way to call foo()
with three parameters a
, b
, and c
in PowerShell would be foo a b c
. And for swapping array elements simply use the array elements. Don't assign them to variables first.
If you actually implement the same logic the PowerShell code works as expected:
function Swapping1 {
$a = "abc"
$b = $a.ToCharArray()
$c = $b.Length-1
$d = 0
GetPer $b $d $c
}
function GetPer {
Param($list, $k, $m)
if ($k -eq $m) {
Write-Host $list
} else {
for ($i = $k; $i -le $m; $i++) {
$list[$k], $list[$i] = $list[$i], $list[$k]
GetPer $list ($k+1) $m
$list[$k], $list[$i] = $list[$i], $list[$k]
}
}
}
Swapping1
Upvotes: 3