PowerShell v3+, 171 bytes
param([char[]]$x)$a,$b=$x;$a=,$a;while($b){$z,$b=$b;$a+=$a|%{0..($y=($c="$_").Length)|%{-join($c[0..$_]+$z+$c[++$_..$y])};"$z$c";"$c$z"}}$a|?{$_.length-eq$x.count}|sort -u
PowerShell v3 introduced the -Unique
flag on the Sort-Object
cmdlet, so it's a few bytes shorter than the below v2 version, since we don't need to Select
first.
v2 version, 178 bytes:
param([char[]]$x)$a,$b=$x;$a=,$a;while($b){$z,$b=$b;$a+=$a|%{0..($y=($c="$_").Length)|%{-join($c[0..$_]+$z+$c[++$_..$y])};"$z$c";"$c$z"}}$a|?{$_.length-eq$x.count}|select -u|sort
PowerShell doesn't have any built-in permutations, so I borrowed my code from Prime Factors Buddies and slightly tweaked it for use here.
This is essentially three portions, which I'll expand on below.
param([char[]]$x)$a,$b=$x;$a=,$a
Takes input $x
, casts it as a char
-array, strips off the first letter into $a
and the rest into $b
, and then recasts $a
as an array with the comma-operator.
while($b){$z,$b=$b;$a+=$a|%{0..($y=($c="$_").Length)|%{-join($c[0..$_]+$z+$c[++$_..$y])};"$z$c";"$c$z"}}
Loops through the remaining letters ($b
), each iteration taking the next letter and storing it into $z
and leaving the remaining in $b
, then array-concatenating onto $a
the result of sending $a
through its own loop -- each item of $a
(temporarily stored into $c
) is looped over its own .length
, and then $z
is inserted into every position, including prepending and appending with $z$c
and $c$z
. For example, for $c = '12'
and $z = '3'
, this will result in '132','312','123'
being concatenated back into $a
.
The final portion $a|?{$_.length-eq$x.count}|select -u|sort
takes each element of $a
and uses Where-Object
clause to filter out only those that have the same length as the input string, then select
s only the -u
nique items, and finally sort
s those alphabetically. The resulting strings are all left on the pipeline, and output via implicit Write-Output
happens at program completion.
PS C:\Tools\Scripts\golfing> .\alphabetically-permute-a-string.ps1 'PPCG'
CGPP
CPGP
CPPG
GCPP
GPCP
GPPC
PCGP
PCPG
PGCP
PGPC
PPCG
PPGC
["buzz" "bzuz" "bzzu" "ubzz" "uzbz" "uzzb" "zbuz" "zbzu" "zubz" "zuzb" "zzbu" "zzub"]
? \$\endgroup\$ – Luis Mendo Nov 16 '16 at 1:00N*
top
) :-) \$\endgroup\$ – Luis Mendo Nov 16 '16 at 1:04