Find all the Anagrams!

17

3

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.

Gryphon

Posted 2017-06-11T22:43:13.913

Reputation: 6 697

May we abide by the normal "program or function" standard? – Jonathan Allan – 2017-06-11T22:58:54.363

@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 – Digital Trauma – 2017-06-11T23:00:23.697

Yes, of course either a program or a function will work fine. – Gryphon – 2017-06-11T23:01:23.800

Closely related – FryAmTheEggman – 2017-06-12T03:35:58.393

@gryphon how are you editing things – Foxy – 2017-06-16T00:59:12.543

Umm, I'm hitting the edit button under them. It's not that hard. – Gryphon – 2017-07-05T12:06:49.947

Answers

10

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

Jonathan Allan

Posted 2017-06-11T22:43:13.913

Reputation: 67 804

Should have guessed 05AB1E would be excessively short. – Gryphon – 2017-06-11T23:25:27.350

4

Ruby, 45 bytes

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

Try it online!

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

ymbirtt

Posted 2017-06-11T22:43:13.913

Reputation: 1 792

The |[] seems unnecessary? – canhascodez – 2017-06-12T18:55:51.500

@sethrin, not quite. The spec says that duplicates should be removed. |[] is shorter than .uniq. – ymbirtt – 2017-06-13T05:44:57.280

3

pyth, 8 4

-{.p

Online test.

  .pQ     # all permutations of the (implicit) input string
 {        # de-duplicate
-    Q    # subtract (implicit) input

Digital Trauma

Posted 2017-06-11T22:43:13.913

Reputation: 64 644

Great golfing job. Congrats on tying the very impressive 05AB1E answer. – Gryphon – 2017-06-11T23:47:10.557

1Sorry, but this outputs the same string twice if there is the same character in the input two times. Please fix that. – Gryphon – 2017-06-11T23:49:26.653

Thanks for fixing that. Too bad about it upping your byte count though. – Gryphon – 2017-06-12T00:29:35.173

I came up with the same answer but also forgot to de-duplicate. Great minds think alike? – Tornado547 – 2017-11-28T16:23:09.723

3

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

ETHproductions

Posted 2017-06-11T22:43:13.913

Reputation: 47 880

Congrats on stealing the win. +1 – Gryphon – 2017-06-11T23:03:16.763

1@Gryphon Not so fast, I'd be shocked if this isn't 3 bytes in 05AB1E... – ETHproductions – 2017-06-11T23:05:45.040

I did mean for now. It's not like i'm marking you as accepted yet. – Gryphon – 2017-06-11T23:07:06.183

If @Dennis does this in Jelly, it'll probably be like 2 bytes. One does not simply outgolf Dennis. – Gryphon – 2017-06-11T23:07:45.407

@JonathanAllan just tied you. – Gryphon – 2017-06-11T23:12:08.370

Unfortunately, k only removes the first occurrence of the string from the array; if a character appears more than once in the input then the array will contain multiple copies of the input. Try abb.

– Shaggy – 2017-06-11T23:23:00.100

Good catch @Shaggy. Unfortunately I will have to disqualify this. The 05AB1E answer is only 3 bytes anyway. – Gryphon – 2017-06-11T23:27:38.500

1The 3 byte prediction was good, but is there a 2?! – Jonathan Allan – 2017-06-11T23:31:51.347

@Shaggy Gosh darn it, I thought á removed duplicates... – ETHproductions – 2017-06-12T01:05:33.330

3

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

Luis Mendo

Posted 2017-06-11T22:43:13.913

Reputation: 87 464

3

Haskell, 48 40 bytes

import Data.List
a=tail.nub.permutations

Try it online!

Saved 8 bytes thanks to Leo's tail tip.

Cristian Lupascu

Posted 2017-06-11T22:43:13.913

Reputation: 8 369

2You 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! – Leo – 2017-06-12T16:18:23.103

@Leo Great, thanks! – Cristian Lupascu – 2017-06-12T18:01:15.067

2

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

Luis Mendo

Posted 2017-06-11T22:43:13.913

Reputation: 87 464

@JonathanAllan Thanks, corrected – Luis Mendo – 2017-06-11T22:50:18.127

@Gryphon Well, 7 after Jonathan's very appropripate correction ;-) – Luis Mendo – 2017-06-11T22:53:12.193

I have now answered that question. – Gryphon – 2017-06-11T22:54:22.503

Umm, the TIO is still outputting the original string for me? – Gryphon – 2017-06-11T22:55:14.037

@Gryphon Sorry, it should be working now. I'm clearly too tired for this; going to bed :-P – Luis Mendo – 2017-06-11T22:59:21.983

2

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"]

Jonathan Allan

Posted 2017-06-11T22:43:13.913

Reputation: 67 804

Impressive. Will there be an explanation, because I don't Jelly? – Gryphon – 2017-06-11T22:57:25.423

Yes, of course! – Jonathan Allan – 2017-06-11T22:59:17.447

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 :/ – Jonathan Allan – 2017-06-11T23:16:42.970

2

Mathematica, 47 bytes

Drop[StringJoin/@Permutations[Characters@#],1]&

J42161217

Posted 2017-06-11T22:43:13.913

Reputation: 15 931

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. – Gryphon – 2017-06-11T23:01:01.560

StringJoin/@Rest@Permutations@Characters@#& is 43 bytes. – jcai – 2017-06-12T00:38:24.327

2

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).

nore

Posted 2017-06-11T22:43:13.913

Reputation: 436

If only python was a golfing language, eh. – Gryphon – 2017-06-12T00:29:15.633

1

Outputting as ('a', 'b', 'c') should be fine, this pyth answer does (basically).

– pizzapants184 – 2017-06-12T07:32:52.370

2

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)

Kevin Cruijssen

Posted 2017-06-11T22:43:13.913

Reputation: 67 575

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 :( – Olivier Grégoire – 2017-06-12T14:13:42.737

@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? – Kevin Cruijssen – 2017-06-12T14:37:46.340

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 :( – Olivier Grégoire – 2017-06-12T14:56:15.233

1Another 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. – Olivier Grégoire – 2017-06-12T15:02:39.893

@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. – Kevin Cruijssen – 2017-06-12T15:09:35.353

1

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)

Brad Gilbert b2gills

Posted 2017-06-11T22:43:13.913

Reputation: 12 713

1

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
}

Michiel uit het Broek

Posted 2017-06-11T22:43:13.913

Reputation: 131

1

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)

streetster

Posted 2017-06-11T22:43:13.913

Reputation: 3 635

0

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')
)

darrylyeo

Posted 2017-06-11T22:43:13.913

Reputation: 6 214

0

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!

Xcali

Posted 2017-06-11T22:43:13.913

Reputation: 7 671

You may want to add an explanation. – Gryphon – 2017-11-27T21:39:34.660