Alphabetically permute a string

27

2

Task

Your goal, should you choose to accept it, is to write a program, that, given an input string (or array of characters), outputs every possible permutation of the letters in that string. I'm finicky with my output, so it should be sorted alphabetically, with no duplicates.

Example:

Input: buzz

Output:

buzz
bzuz
bzzu
ubzz
uzbz
uzzb
zbuz
zbzu
zubz
zuzb
zzbu
zzub

Rules

  • This is so the shortest code wins.
  • Trailing spaces on each/any line are ok
  • A single newline after the last line is allowed (but no more)

Brian Gradin

Posted 2016-11-16T00:33:04.720

Reputation: 569

Can output format be ["buzz" "bzuz" "bzzu" "ubzz" "uzbz" "uzzb" "zbuz" "zbzu" "zubz" "zuzb" "zzbu" "zzub"]? – Luis Mendo – 2016-11-16T01:00:54.543

Sorry, 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* to p) :-) – Luis Mendo – 2016-11-16T01:04:58.643

Can 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

Answers

23

Jelly, 5 bytes

ṢŒ!QY

Try it online!

Explanation

Ṣ         Sort
 Œ!       All permutations
   Q      Unique
    Y     Join by linefeeds

Luis Mendo

Posted 2016-11-16T00:33:04.720

Reputation: 87 464

26And... we have 100000 posts! Congrats! – ETHproductions – 2016-11-16T00:43:41.977

1@ETHproductions Heh! Thanks! :-) – Luis Mendo – 2016-11-16T00:44:11.020

1Congrats from my side as well :) @ETHproductions how did you get to that result? I am just curious... – geisterfurz007 – 2016-11-16T11:10:13.560

5@geisterfurz007 Click the "share" link at the bottom of the post. That has ID of the post in the URL. – Martin Ender – 2016-11-16T12:16:10.093

1Oh so it is the 100000th post of ppcg! I thought Luis Mendo was at that number already. My bad. Thanks for the explanation! – geisterfurz007 – 2016-11-16T12:32:31.953

1It's quite fitting for the 100000th post to solve "print sorted unique permutations of x" with code sort(unique(permutations(x))) – anatolyg – 2016-11-16T15:27:46.983

1+1 only for being the 100'000th post! :) – RudolfJelin – 2016-11-16T20:10:01.020

1Wait, @LuisMendo, did you just made it to PGCC history and you were not using MATL??? :( :( :( :( :P – Brain Guider – 2016-11-17T18:26:16.687

1

@AnderBiguri :-D The truth is I had no idea about the post number. Anyway, MATL is 99999

– Luis Mendo – 2016-11-17T19:18:09.513

12

05AB1E,  4  3 bytes

Updated, since an update to œ broke the old version,
which also saved a byte as suggested by Magic Octopus Urn.

œê»

Try it online!

Explanation

œ     # get all permutations of input
 ê    # sort and remove duplicates
  »   # join list by newlines

Emigna

Posted 2016-11-16T00:33:04.720

Reputation: 50 798

œê» is fine for non-legacy. – Magic Octopus Urn – 2019-05-01T17:17:34.420

@MagicOctopusUrn: It is actually required for both versions as œ now returns a list of string in both. – Emigna – 2019-05-02T19:53:39.000

10

CJam, 5 bytes

Thanks to @EriktheOutgolfer for a correction (q instead of r)

qe!N*

Try it online!

Explanation

q        e# Read input as a string
 e!      e# Unique permutations, sorted
   N*    e# Join by newline. Implicitly display

Luis Mendo

Posted 2016-11-16T00:33:04.720

Reputation: 87 464

10

Python 3.5, 79 bytes

def f(s,w=''):
 s or print(w)
 for c in sorted({*s}):t=s*1;t.remove(c);f(t,w+c)

A function that takes input as a list of characters and outputs by printing.

Recursively makes every distinct permutation by taking each possible next character alphabetically out of the remaining distinct characters, and appending it to the output in progress w. Then, we recurse with this character removed. Once the input is emptied, we print w.

xnor

Posted 2016-11-16T00:33:04.720

Reputation: 115 687

Take in a list of chars, not a string. – xnor – 2016-11-17T16:32:11.087

10

MATL, 4 bytes

Y@Xu

Try it online!

Explanation

Y@    % Implicit input. Push 2D array of all permutations, each on a row, sorted
Xu    % Unique rows. Implicitly display

Luis Mendo

Posted 2016-11-16T00:33:04.720

Reputation: 87 464

8

Pyth - 5 bytes

jS{.p

Try it online here.

j        Join. Implictly joins on newlines.
 S       Sort
  {      Uniquify
   .p    All permutations, implicitly run on input.

Maltysen

Posted 2016-11-16T00:33:04.720

Reputation: 25 023

Is S really needed? – Luis Mendo – 2016-11-16T00:50:23.293

@LuisMendo It's needed if the input isn't already sorted. – isaacg – 2016-11-16T00:54:32.097

1@isaacg Thanks! I just realized I need that in my Jelly answer as well – Luis Mendo – 2016-11-16T00:58:14.940

@LuisMendo whoops. – Maltysen – 2016-11-16T01:12:04.213

6

Haskell, 46 bytes

import Data.List;unlines.sort.nub.permutations

2 bytes saved thanks to nimi

poi830

Posted 2016-11-16T00:33:04.720

Reputation: 1 265

1You don't need a name for the function, so you can drop the f=. – nimi – 2016-11-16T08:38:18.337

5

J, 19 bytes

/:~@~.@:{~!@#A.&i.#

Test case

   f =: /:~@~.@:{~!@#A.&i.#
   f 'buzz'
buzz
bzuz
bzzu
ubzz
uzbz
uzzb
zbuz
zbzu
zubz
zuzb
zzbu
zzub

Explanation

This is a 4-train:

                     /- ~ --- /:
               /- @ -^- ~.
  /- ~ --- @: -^- {
  |
  |            /- !
--<     /- @ --^- #
  |     |
  \-----<      /- A.
        >- & --^- i.
        \- #

Basically:

/:~@~.@:{~!@#A.&i.#
          !  A.&     get permutations
           @#   i.#  of range (0..length)
        {~           map indices to chars in string
      @:             then
    ~.               unique
   @                 then
/:~                  sort

Conor O'Brien

Posted 2016-11-16T00:33:04.720

Reputation: 36 228

I think [:~.i.@!@#A./:~ should save you a few bytes – miles – 2016-12-24T23:00:25.303

4

JavaScript (Firefox 30+), 129 124 bytes

f=(a,i=-1)=>a[1]?[for(x of a.sort())if(a.indexOf(x)==++i)f([...a.slice(0,i),...a.slice(i+1)]).replace(/^/gm,x)].join`
`:a[0]

Not too bad for a language with no permutation built-ins...

ETHproductions

Posted 2016-11-16T00:33:04.720

Reputation: 47 880

I converted this to operate on strings; despite taking 23 bytes just to sort the characters into order I still got the job done in 120 bytes. – Neil – 2016-11-16T11:02:22.177

3

Mathematica, 34 23 bytes

Print@@@Permutations@#&

The input must be a list of characters.

Explanation

Permutations@

Find all permutations of the input, sorted and duplicate-free.

Print@@@

Print them one by one.

JungHwan Min

Posted 2016-11-16T00:33:04.720

Reputation: 13 290

3

Python 3.5, 81 bytes:

from itertools import*;lambda i:'\n'.join(sorted({*map(''.join,permutations(i))}))

Really...81 bytes when the next longest answer is 48 bytes...sigh. Well, I will try this golf this more as much as I can, but golfing tips are still very much appreciated.

Also, here is the shortest solution I could get in Python 2 at 86 bytes:

from itertools import*;lambda f:'\n'.join(sorted({''.join(i)for i in permutations(f)}))

Apparently in Python 2, [*...] returns a Syntax Error, and since permutations returns itertools.permutations object at 0x..., the next shortest way (that I know) of extracting the unique permutations is using {''.join(i)for i in permutations(f)} where f is the input string.

Finally, note that these are both lambda functions and thus must be called in the format print(<Function Name>(<Input String>)).

R. Kap

Posted 2016-11-16T00:33:04.720

Reputation: 4 730

3

Brachylog, 9 bytes

:pfdo~@nw

Try it online!

Explanation

:pf         Find all outputs of p - Permute with the main Input as input
   d        Remove Duplicates
    o       Order
     ~@n    Concatenate into a single string with linebreaks as separator
        w   Write to STDOUT

Fatalize

Posted 2016-11-16T00:33:04.720

Reputation: 32 976

3

Perl 6,  49  44 bytes

String as input

*.comb.permutations.sort».join.squish.map: *.put

List of characters as input

*.permutations.sort».join.squish.map: *.put

Expanded

*\              # Whatever lambda
# .comb\        # split into a list of characters
.permutations\  # returns a list of lists
.sort\
».join\         # join the second level lists
.squish\        # remove adjacent repeated values
.map: *.put     # print each on its own line

Brad Gilbert b2gills

Posted 2016-11-16T00:33:04.720

Reputation: 12 713

2every time I see perl 6 code I wonder why I haven't installed it yet – Gabriel Benamy – 2016-11-17T01:48:53.947

@GabrielBenamy There is an irc bot that runs Perl 6 code on the freenode.net #perl6 channel. – Brad Gilbert b2gills – 2016-11-18T21:13:41.227

You can do ».say instead of .map: *.put – Jo King – 2018-07-30T23:10:36.107

1@JoKing Technically ».say is allowed to do them in any order, and at one time it was purposely done out of order. – Brad Gilbert b2gills – 2018-08-01T17:35:45.197

3

Brachylog (v2), 5 bytes

pᵘoẉᵐ

Try it online!

Find nique permutations of input, sort them, ap riteln (write with newline) over that array.

sundar - Reinstate Monica

Posted 2016-11-16T00:33:04.720

Reputation: 5 296

2

Python 3, 77 85 bytes

Now sorts!

import itertools as i
for a in sorted(set(i.permutations(input()))):print("".join(a))

Aryaman

Posted 2016-11-16T00:33:04.720

Reputation: 161

1To shorten this, you could do from itertools import* as opposed to import itertools as i. You'd be able to save a byte by replacing i.permutations by permutations. – 0WJYxW9FMN – 2016-11-16T20:50:01.743

Using {*...} instead of set(...) saves you two more bytes. – movatica – 2019-04-30T21:04:45.033

2

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 selects only the -unique items, and finally sorts 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

AdmBorkBork

Posted 2016-11-16T00:33:04.720

Reputation: 41 581

If you are willing to go 3.0 You can change |select -u|sort to |sort -u. Pretty sure 2.0 does not have that. – Matt – 2016-11-16T19:58:58.360

@Matt Thanks - you're correct. That was introduced in v3. – AdmBorkBork – 2016-11-16T21:32:22.227

2

JavaScript (ES6), 119 bytes

f=(s,t=[...s].sort().join``,p=``)=>t?t.replace(/./g,(c,i)=>t.indexOf(c)==i?f(s,t.slice(0,i)+t.slice(i+1),p+c):``):p+`\n`

Where \n represents the literal newline character. Port of @ETHproduction's answer to use strings instead of arrays. Reversing the output, or moving the trailing newline to the beginning, saves 3 bytes.

Neil

Posted 2016-11-16T00:33:04.720

Reputation: 95 035

1

R, 113 bytes

x=scan(,"");cat(sort(unique(apply(matrix(x[permute:::allPerms(l<-length(x))],,l),1,paste,collapse=""))),sep="\n")

Reads input from stdin. The permute package is assumed to be installed in order to call the allPerms function.

Will add an explanation as I get home from work.

Billywob

Posted 2016-11-16T00:33:04.720

Reputation: 3 363

1

Java 302 300 bytes

import java.util.*;class M{public static void main(String[]a){for(Object s:p(new TreeSet(),"",a[0]))System.out.println(s);}static Set p(Set l,String p,String s){int n=s.length(),i=0;if(n>1)for(;i<n;p(l,p+s.charAt(i),s.substring(0,i)+s.substring(++i,n)));else if(!l.contains(p+=s))l.add(p);return l;}}

Ungolfed & test code:

Try it here.

import java.util.*;
class M{
  static Set p(Set l, String p, String s){
    int n = s.length(),
        i = 0;
    if(n > 1){
      for(; i < n; p(l, p + s.charAt(i), s.substring(0, i) + s.substring(++i, n)));
    } else if(!l.contains(p+=s)){
      l.add(p);
    }
    return l;
  }

  public static void main(String[] a){
    for(Object s : p(new TreeSet(), "", a[0])){
      System.out.println(s);
    }
  }
}

Input: test
Output:

estt
etst
etts
sett
stet
stte
test
tets
tset
tste
ttes
ttse

Kevin Cruijssen

Posted 2016-11-16T00:33:04.720

Reputation: 67 575

1The permutations are supposed to be alphabetically sorted – Ikaros – 2016-11-16T13:53:30.063

@Ikaros Thanks, should be fixed now. – Kevin Cruijssen – 2016-11-16T14:06:05.593

1

Racket 82 bytes

(sort(remove-duplicates(map list->string(permutations(string->list s)))) string<?)

Ungolfed:

(define(f s)
 (sort
  (remove-duplicates
   (map
    list->string
    (permutations
     (string->list s))))
  string<?))

Testing:

(f "buzz")

Ouput:

'("buzz" "bzuz" "bzzu" "ubzz" "uzbz" "uzzb" "zbuz" "zbzu" "zubz" "zuzb" "zzbu" "zzub")

rnso

Posted 2016-11-16T00:33:04.720

Reputation: 1 635

0

Groovy, 69 Bytes

{(it as List).permutations().unique().sort().each{println it.join()}}

Magic Octopus Urn

Posted 2016-11-16T00:33:04.720

Reputation: 19 422

0

Ruby, 51 bytes

->s{puts s.chars.permutation.map(&:join).uniq.sort}

Lee W

Posted 2016-11-16T00:33:04.720

Reputation: 521

how to we can run it? – بارپابابا – 2016-11-17T05:51:15.023

puts s.chars.permutation().map(&:join).uniq 43 Byte – بارپابابا – 2016-11-17T05:59:50.127

That doesn't work. You need to sort the output, and you can't refer to s without prior definition. – Lee W – 2016-11-17T15:36:34.620

0

Actually, 8 bytes

Golfing suggestions welcome! Try it online!

;l@╨♂Σ╔i

Ungolfing

     Implicit input s.
;l   Get len(s).
@╨   Get all len(s)-length permutations of s.
♂Σ   Sum them all back into strings.
╔    uniq() the list of strings.
i    Flatten the list of strings.
     Implicit print the stack, separated by newlines.

Sherlock9

Posted 2016-11-16T00:33:04.720

Reputation: 11 664

0

Pip, 8 bytes

7 bytes of code, +1 for -n flag.

SSUQPMa

Takes a string as a command-line argument. Try it online!

Pip's scanner breaks runs of uppercase letters into two-letter chunks. So this code is SS UQ PM a--i.e. SortString(UniQue(PerMutations(a))), with a being the command-line arg. The -n flag ensures the result list is newline-separated. That's all there is to it.

DLosc

Posted 2016-11-16T00:33:04.720

Reputation: 21 213

0

K (oK), 14 bytes

Solution:

?x@<x@:prm@#x:

Try it online!

Explanation:

Use the built-in permutation function, prm, to generate permutations of length of the input, apply these permutations to the input, sort alphabetically and then take distinct values.

?x@<x@:prm@#x: / the solution
            x: / store input as x
           #   / count length of x
       prm@    / apply (@) function prm
    x@:        / apply indices to x and save result back into x
   <           / indices to sort ascending
 x@            / apply to x
?              / take distint

streetster

Posted 2016-11-16T00:33:04.720

Reputation: 3 635

0

Japt v2.0a0 -R, 5 bytes

á â n

Try it

Embodiment of Ignorance

Posted 2016-11-16T00:33:04.720

Reputation: 7 014

û is the centre pas method; I think you meant n ;) – Shaggy – 2019-04-29T09:19:09.947

@Shaggy I just put sort in the searchbar in your interpreter and clicked the first one I found. But á seems to give each permutation in alphabetic order already – Embodiment of Ignorance – 2019-04-30T02:25:42.763

Oop, that's a typo; should be ü. I'll fix it tomorrow. The permutations of "buzz" happen to be sorted because the word itself is - try it with "zzub" instead, for example. – Shaggy – 2019-04-30T19:17:27.867

@Shaggy, I see, updated answer with n (it's easier to type) – Embodiment of Ignorance – 2019-04-30T20:00:09.850

0

Perl 5 -MList::Util=uniq -F, 68 bytes

$"=',';@b=sort@F;map{say if"@b"eq join$",sort/./g}uniq glob"{@b}"x@b

Try it online!

Xcali

Posted 2016-11-16T00:33:04.720

Reputation: 7 671

0

C++ (gcc), 132 128 bytes

#include<bits/stdc++.h>
using namespace std;int main(){string s;for(cin>>s;cout<<s<<endl,next_permutation(s.begin(),s.end()););}

Try it online!

movatica

Posted 2016-11-16T00:33:04.720

Reputation: 635

0

Clam, 9 bytes

p_D`Sq@~Q

Explanation

          - Implicit Q = first input
p         - Print...
 _        - Sorted ascending value (alphabetical order)
  D       - Distinct from...
   `Sq    - Joined (map(q=>q.join(""))
      @~Q - Permutations of Q

Skidsdev

Posted 2016-11-16T00:33:04.720

Reputation: 9 656