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
Can output format be
["buzz" "bzuz" "bzzu" "ubzz" "uzbz" "uzzb" "zbuz" "zbzu" "zubz" "zuzb" "zzbu" "zzub"]
? – Luis Mendo – 2016-11-16T01:00:54.543Sorry, as I mentioned, I'm finicky ;) output must be on separate lines, rather than in a list format – Brian Gradin – 2016-11-16T01:03:47.433
Yes, that makes sense. I just wanted to see if I could remove one byte from my CJam answer (
N*
top
) :-) – Luis Mendo – 2016-11-16T01:04:58.643Can the input be an array of characters instead of a string? – JungHwan Min – 2016-11-16T01:17:31.500
Hmmm......I'll allow it – Brian Gradin – 2016-11-16T01:19:53.833
2A solid first challenge! – xnor – 2016-11-16T06:08:04.397
1So many builtins! – Dan – 2016-11-16T11:27:07.833