16
\$\begingroup\$

Despite having 17 questions tagged , we still don't have this question, so here it is.

Your Task

You must write a program or function that, when receiving a string, prints out all possible anagrams of it. For the purposes of this question, an anagram is a string that contains the same character as the original string, but is not an exact copy of the original string. An anagram does not have to be or contain actual words.

Input

You may accept the string, which may be of any length > 0, by any standard input method. It may contain any ASCII characters.

Output

You may output all of the possible anagrams of the inputted string in any standard way. You must not output the same string twice, or output a string equal to the input.

Other Rules

Standard Loopholes are disallowed

Scoring

This is , least bytes wins.

\$\endgroup\$
  • \$\begingroup\$ May we abide by the normal "program or function" standard? \$\endgroup\$ – Jonathan Allan Jun 11 '17 at 22:58
  • \$\begingroup\$ @JonathanAllan I think if its not explicitly mentioned, you may submit a program or a function. I've generally left that implicit in my questions with no problems \$\endgroup\$ – Digital Trauma Jun 11 '17 at 23:00
  • \$\begingroup\$ Yes, of course either a program or a function will work fine. \$\endgroup\$ – Gryphon Jun 11 '17 at 23:01
  • \$\begingroup\$ Closely related \$\endgroup\$ – FryAmTheEggman Jun 12 '17 at 3:35
  • \$\begingroup\$ @gryphon how are you editing things \$\endgroup\$ – Foxy Jun 16 '17 at 0:59

16 Answers 16

9
\$\begingroup\$

05AB1E, 3 bytes

œÙ¦

A function that leaves the stack with a list of the anagrams on top (and as its only item). As a full program prints a representation of that list.

Try it online!

How?

    - push input
œ   - pop and push a list of all permutations (input appears at the head)
 Ù  - pop and push a list of unique items (sorted by first appearance)
  ¦ - pop and push a dequeued list (removes the occurrence of the input)
    - As a full program: implicit print of the top of the stack
\$\endgroup\$
  • \$\begingroup\$ Should have guessed 05AB1E would be excessively short. \$\endgroup\$ – Gryphon Jun 11 '17 at 23:25
4
\$\begingroup\$

Ruby, 45 bytes

->x{(x.chars.permutation.map(&:join)-[x])|[]}

Try it online!

Despite having a built-in, the word "permutation" is really long :(

\$\endgroup\$
  • \$\begingroup\$ The |[] seems unnecessary? \$\endgroup\$ – canhascodez Jun 12 '17 at 18:55
  • \$\begingroup\$ @sethrin, not quite. The spec says that duplicates should be removed. |[] is shorter than .uniq. \$\endgroup\$ – ymbirtt Jun 13 '17 at 5:44
3
\$\begingroup\$

MATL, 7 bytes

tY@1&X~

Try it online!

Explanation

t     % Implicitly input a string, say of length n. Duplicate
Y@    % All permutations. May contain duplicates. Gives a 2D char array of 
      % size n!×n with each permutation in a row
1&X~  % Set symmetric difference, row-wise. Automatically removes duplicates.
      % This takes the n!×n char array and the input string (1×n char array)
      % and produces an m×n char array containing the rows that are present 
      % in exactly one of the two arrays
      % Implicitly display
\$\endgroup\$
3
\$\begingroup\$

pyth, 8 4

-{.p

Online test.

  .pQ     # all permutations of the (implicit) input string
 {        # de-duplicate
-    Q    # subtract (implicit) input
\$\endgroup\$
  • \$\begingroup\$ Great golfing job. Congrats on tying the very impressive 05AB1E answer. \$\endgroup\$ – Gryphon Jun 11 '17 at 23:47
  • 1
    \$\begingroup\$ Sorry, but this outputs the same string twice if there is the same character in the input two times. Please fix that. \$\endgroup\$ – Gryphon Jun 11 '17 at 23:49
  • \$\begingroup\$ Thanks for fixing that. Too bad about it upping your byte count though. \$\endgroup\$ – Gryphon Jun 12 '17 at 0:29
  • \$\begingroup\$ I came up with the same answer but also forgot to de-duplicate. Great minds think alike? \$\endgroup\$ – Tornado547 Nov 28 '17 at 16:23
3
\$\begingroup\$

Japt, 6 bytes

á â kU

Try it online!

Explanation

 á â kU
Uá â kU   // Ungolfed
          // Implicit: U = input string
Uá        // Take all permutations of U.
   â      // Remove duplicates.
     kU   // Remove U itself from the result.
          // Implicit: output resulting array, separated by commas
\$\endgroup\$
  • \$\begingroup\$ Congrats on stealing the win. +1 \$\endgroup\$ – Gryphon Jun 11 '17 at 23:03
  • 1
    \$\begingroup\$ @Gryphon Not so fast, I'd be shocked if this isn't 3 bytes in 05AB1E... \$\endgroup\$ – ETHproductions Jun 11 '17 at 23:05
  • \$\begingroup\$ I did mean for now. It's not like i'm marking you as accepted yet. \$\endgroup\$ – Gryphon Jun 11 '17 at 23:07
  • \$\begingroup\$ If @Dennis does this in Jelly, it'll probably be like 2 bytes. One does not simply outgolf Dennis. \$\endgroup\$ – Gryphon Jun 11 '17 at 23:07
  • 1
    \$\begingroup\$ The 3 byte prediction was good, but is there a 2?! \$\endgroup\$ – Jonathan Allan Jun 11 '17 at 23:31
3
\$\begingroup\$

Haskell, 48 40 bytes

import Data.List
a=tail.nub.permutations

Try it online!

Saved 8 bytes thanks to Leo's tail tip.

\$\endgroup\$
  • 2
    \$\begingroup\$ You can use tail instead of delete x, since the original string will always come first in the list of permutations. This will let you switch to a point-free solution, and then to an unnamed function, lots of bytes to be saved! \$\endgroup\$ – Leo Jun 12 '17 at 16:18
  • \$\begingroup\$ @Leo Great, thanks! \$\endgroup\$ – Cristian Lupascu Jun 12 '17 at 18:01
2
\$\begingroup\$

CJam, 8 bytes

l_e!\a-p

Try it online!

Explanation

l    e# Read string from input
_    e# Duplicate
e!   e# Unique permutations. Gives a list of strings
\    e# Swap
a    e# Wrap in a singleton array
-    e# Set difference. This removes the input string
p    e# Pretty print the list
\$\endgroup\$
  • \$\begingroup\$ @JonathanAllan Thanks, corrected \$\endgroup\$ – Luis Mendo Jun 11 '17 at 22:50
  • \$\begingroup\$ @Gryphon Well, 7 after Jonathan's very appropripate correction ;-) \$\endgroup\$ – Luis Mendo Jun 11 '17 at 22:53
  • \$\begingroup\$ I have now answered that question. \$\endgroup\$ – Gryphon Jun 11 '17 at 22:54
  • \$\begingroup\$ Umm, the TIO is still outputting the original string for me? \$\endgroup\$ – Gryphon Jun 11 '17 at 22:55
  • \$\begingroup\$ @Gryphon Sorry, it should be working now. I'm clearly too tired for this; going to bed :-P \$\endgroup\$ – Luis Mendo Jun 11 '17 at 22:59
2
\$\begingroup\$

Mathematica, 47 bytes

Drop[StringJoin/@Permutations[Characters@#],1]&
\$\endgroup\$
  • \$\begingroup\$ I was waiting for one of these, but I was pretty sure it wasn't going to win. Kinda surprised there isn't just one built in. \$\endgroup\$ – Gryphon Jun 11 '17 at 23:01
  • \$\begingroup\$ StringJoin/@Rest@Permutations@Characters@#& is 43 bytes. \$\endgroup\$ – jcai Jun 12 '17 at 0:38
2
\$\begingroup\$

Jelly, 4 bytes

Œ!QḊ

A monadic link taking a list of characters and returning a list of lists of characters - all distinct anagrams that are not equal to the input.

Try it online! (the footer forms a program that joins the list by newlines and prints to avoid the otherwise smashed representation).

How?

Œ!QḊ - Link: list of characters     e.g. "text"
Œ!   - all permutations of the list      ["text","tetx","txet","txte","ttex","ttxe","etxt","ettx","extt","extt","ettx","etxt","xtet","xtte","xett","xett","xtte","xtet","ttex","ttxe","tetx","text","txte","txet"]
  Q  - de-duplicate                      ["text","tetx","txet","txte","ttex","ttxe","etxt","ettx","extt","xtet","xtte","xett"]
   Ḋ - dequeue (the first one = input)          ["tetx","txet","txte","ttex","ttxe","etxt","ettx","extt","xtet","xtte","xett"]
\$\endgroup\$
  • \$\begingroup\$ Impressive. Will there be an explanation, because I don't Jelly? \$\endgroup\$ – Gryphon Jun 11 '17 at 22:57
  • \$\begingroup\$ Yes, of course! \$\endgroup\$ – Jonathan Allan Jun 11 '17 at 22:59
  • \$\begingroup\$ I took it off ages ago, hence why I had the "(4?)" in the header and the text about removing Y if functions were allowed... I see you just reversed my edit to the question though :/ \$\endgroup\$ – Jonathan Allan Jun 11 '17 at 23:16
2
\$\begingroup\$

Python 3, 85 76 63 bytes

As a function, and returning strings as list of characters (thanks to @pizzapants184 for telling me it is allowed):

from itertools import*
lambda z:set(permutations(z))-{tuple(z)}

As a function:

from itertools import*
lambda z:map("".join,set(permutations(z))-{tuple(z)})

85 bytes as a full program:

from itertools import*
z=input()
print(*map("".join,set(permutations(z))-{tuple(z)}))

Could be reduced a bit if outputting strings as ('a', 'b', 'c') is allowed (I am not sure it is).

\$\endgroup\$
  • \$\begingroup\$ If only python was a golfing language, eh. \$\endgroup\$ – Gryphon Jun 12 '17 at 0:29
  • 1
    \$\begingroup\$ Outputting as ('a', 'b', 'c') should be fine, this pyth answer does (basically). \$\endgroup\$ – pizzapants184 Jun 12 '17 at 7:32
2
\$\begingroup\$

Java 8, 245 239 237 bytes

import java.util.*;s->{Set l=new HashSet();p("",s,l);l.remove(s);l.forEach(System.out::println);}void p(String p,String s,Set l){int n=s.length(),i=0;if(n<1)l.add(p);else for(;i<n;p(p+s.charAt(i),s.substring(0,i)+s.substring(++i,n),l));}

-6 bytes thanks to @OlivierGrégoire.

Typical verbose Java.. I see a lot of <10 byte answers, and here I am with 200+ bytes.. XD

Explanation:

Try it here.

import java.util.*;         // Required import for the Set and HashSet

s->{                        // Method (1) with String parameter and no return-type
  Set l=new HashSet();      //  Set to save all permutations in (without duplicates)
  p("",s);                  //  Determine all permutations, and save them in the Set
  l.remove(s);              //  Remove the input from the Set
  l.forEach(                //  Loop over the Set
    System.out::println);   //   And print all the items
}                           // End of method (1)

// This method will determine all permutations, and save them in the Set:
void p(String p,String s,Set l){
  int n=s.length(),         //  Length of the first input String
      i=0;                  //  And a temp index-integer
  if(n<1)                   //  If the length is 0:
    l.add(p);               //   Add the permutation input-String to the Set
  else                      //  Else:
    for(;i<n;               //   Loop over the first input-String
      p(                    //    And do a recursive-call with:
        p+s.charAt(i),      //     Permutation + char
        s.substring(0,i)+s.substring(++i,n),l)
                            //     Everything except this char
      );                    //   End of loop
}                           // End of method (2)
\$\endgroup\$
  • \$\begingroup\$ Use l.forEach(System.out::println); instead of your printing loop. Also, I don't like Set being defined at the class level without its enclosing class, a lambda defined no one knows where and a method. This just too much for me. I can understand the imports being separated from the rest, but there is nothing self-contained there, it looks more like a collection of snippets than anything else. I'm sorry, but for the first time in PCG, I give -1 :( \$\endgroup\$ – Olivier Grégoire Jun 12 '17 at 14:13
  • \$\begingroup\$ @OlivierGrégoire First of all thanks for the tip for the forEach. As for the class-level Set, what is the alternative? Post the entire class including main-method? Post the entire class excluding the main-method, but including the class itself, interface and function name? \$\endgroup\$ – Kevin Cruijssen Jun 12 '17 at 14:37
  • \$\begingroup\$ I'd write a full class. That's the smallest self-contained I can find. No need to add the public static void main, just say "the entry method is...". The thing is that your answer as it currently is breaks all the "self-contained" rules. I'm not against binding the rules, but breaking? Yeah, I mind :( \$\endgroup\$ – Olivier Grégoire Jun 12 '17 at 14:56
  • 1
    \$\begingroup\$ Another idea: pass the Set as parameter? The helper function, I can totally understand that, but it's defining the Set outside of everything that makes me tick. \$\endgroup\$ – Olivier Grégoire Jun 12 '17 at 15:02
  • \$\begingroup\$ @OlivierGrégoire Ok, went for your second suggestion. Indeed makes more sense as well, so I will use that from now on. Thanks for the honest feedback. \$\endgroup\$ – Kevin Cruijssen Jun 12 '17 at 15:09
1
\$\begingroup\$

Perl 6,  39  38 bytes

*.comb.permutations».join.unique[1..*]

Try it

*.comb.permutations».join.unique.skip

Try it

Expanded

*               # WhateverCode lambda (this is the parameter)
.comb           # split into graphemes
.permutations\  # get all of the permutations
».join          # join each of them with a hyper method call
.unique         # make sure they are unique
.skip           # start after the first value (the input)
\$\endgroup\$
1
\$\begingroup\$

C++, 142 bytes

#include<algorithm>
void p(std::string s){auto b=s;sort(begin(s),end(s));do if(s!=b)puts(s.data());while(next_permutation(begin(s),end(s)));}

ungolfed

#include <algorithm>

void p(std::string s)
{
    auto b = s;                    // use auto to avoid std::string
    sort(begin(s), end(s));        // start at first permutation
    do
      if (s != b)                  // only print permutation different than given string
        puts(s.data());
    while (next_permutation(begin(s), end(s))); // move to next permutation
}
\$\endgroup\$
1
\$\begingroup\$

K (oK), 13 bytes

Solution:

1_?x@prm@!#x:

Try it online!

Explanation:

Evaluation is performed right-to-left.

1_?x@prm@!#x: / the solution
           x: / store input in variable x
          #   / count length of x, #"abc" => 3
         !    / range, !3 => 0 1 2
     prm@     / apply (@) function permutations (prm) to range
   x@         / apply (@) these pumuted indixes back to original input
  ?           / return distinct values
1_            / drop the first one (ie the original input)
\$\endgroup\$
0
\$\begingroup\$

JavaScript (ES6), 101 bytes

Adopted from a past answer of mine.

S=>(R=new Set,p=(s,m='')=>s[0]?s.map((_,i)=>p(a=[...s],m+a.splice(i,1))):R.add(m),_=p([...S]),[...R])

f=
S=>(R=new Set,p=(s,m='')=>s[0]?s.map((_,i)=>p(a=[...s],m+a.splice(i,1))):R.add(m),_=p([...S]),[...R])


console.log(
  f('ABC'),
  f('ABCD'),
  f('ABCC'),
  f('AABBC')
)

\$\endgroup\$
0
\$\begingroup\$

Perl 5, 89 + 2 (-F) = 91 bytes

$,=$_;$"=",";map{say if!$k{$_}++&&$,ne$_&&(join"",sort@F)eq join"",sort/./g}glob"{@F}"x@F

Try it online!

\$\endgroup\$
  • \$\begingroup\$ You may want to add an explanation. \$\endgroup\$ – Gryphon Nov 27 '17 at 21:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.