Encontre todos os anagramas e subanagramas também!

13

Esta questão é fortemente baseada nessa questão , mas deve apresentar várias dificuldades adicionais.

Sua tarefa

Você deve escrever um programa ou função que, ao receber uma string, imprima todos os anagramas possíveis. Para os fins desta pergunta, um anagrama é uma sequência que contém o mesmo caractere que a sequência original, mas não é a sequência original. Um subanagrama é um anagrama de uma substring de uma string inserida. Anagramas e subanagramas não precisam ser ou conter palavras reais.

Entrada

Você pode aceitar uma string, que pode ter qualquer tamanho> 0, por qualquer método de entrada padrão. Pode conter caracteres ASCII.

Resultado

Você pode emitir todos os anagramas e subanagramas possíveis da string inserida de qualquer maneira padrão. Você não deve produzir a mesma sequência duas vezes ou produzir uma sequência igual à entrada.

Outras regras

Brechas padrão não são permitidas

Pontuação

Isso é , menos bytes ganhos.

Gryphon
fonte
A string vazia é um possível anagrama?
Digital Trauma
É permitida a saída da string / sustrings originais?
CalculatorFeline
@CalculatorFeline "Você não deve produzir a mesma sequência duas vezes ou produzir uma sequência igual à entrada."
Jonathan Allan
@DigitalTrauma, "Você pode aceitar uma string, que pode ter qualquer tamanho> 0 , por qualquer método de entrada padrão". (ênfase adicionada)
Gryphon
4
Alguns casos de teste seria útil
Mr. Xcoder

Respostas:

8

05AB1E , 7 bytes

Œ€œ˜Ù¹K

Uma função que aceita uma string de entrada e deixa uma lista de strings na pilha. Como um programa completo, uma representação da lista é impressa.

Experimente online!

Quão?

        - push input
Π      - all substrings
 €œ     - for €ach: all permutations
   ˜    - flatten
    Ù   - de-duplicate
     ¹  - push 1st input onto top of stack
      K - pop a,b; push a without any b's (remove the copy of the input from the list)
        - as a full program: implicit print of the top of the stack
Jonathan Allan
fonte
E ... você conseguiu algo ainda mais curto.
Gryphon
É o mesmo algoritmo, apenas menos bytes.
Jonathan Allan
Sim, a mudança de idioma foi tudo, mas ainda é impressionante.
Gryphon
@ ais523 Parece que eu entendi errado!
Jonathan Allan
@ ais523 Eu acho que é fixo.
Jonathan Allan
9

Braquilog (2), 7 bytes

{sp}ᶠdb

Experimente online!

Explicação

{sp}ᶠdb
{  }ᶠ    Find all
  p        permutations of
 s         a substring of {the input}
     d   Remove duplicates (leaving the list otherwise in the same order)
      b  Remove the first (the input itself)

fonte
O que significa o (2)?
Gryphon
@Gryphon (afaik) existem 2 versões do branchylog, isso está usando V2.
John Hamilton
1
Ok, não tinha certeza se era o número da versão ou uma possível contagem de bytes usando um método diferente e possivelmente ilegal.
Gryphon
1
Essa é a segunda vez que me perguntam agora. Acho que vou ter que começar a escrever como (v2).
7

Geléia , 9 bytes

ẆŒ!€;/QḟW

Um link monádico que aceita uma lista e retorna uma lista de todos os subanagramas distintos, exceto a própria entrada.

Experimente online! (o rodapé imprime a lista resultante unindo-se a novas linhas.)

Quão?

ẆŒ!€;/QḟW - Link: list of characters, s
Ẇ         - all contiguous sublists of s
 Œ!€      - all permutations for €ach sublist now a list of lists of lists)
     /    - reduce by:
    ;     -   concatenation (flattens the list by one level)
      Q   - de-duplicate (gets the unique entries)
        W - wrap s in a list (otherwise filtering will attempt to remove characters)
       ḟ  - filter discard from left if in right (remove the one equal to the input)
Jonathan Allan
fonte
4

Pyth, 12

-{.n.pM.:Q)]

Teste online .

         Q       # input
       .: )      # all substrings
    .pM          # all permutations of all substrings
  .n             # flatten
 {               # deduplicate
-          ]Q    # subtract (list of) (implicit) input
Trauma Digital
fonte
@ ais523 Refeito - acho que está correto agora.
Digital Trauma
3

Japonês , 10 bytes

à má c â Å

Experimente online!

Eu tenho que usar à, áe âtudo em uma resposta, em ordem também. Que coincidência...

Explicação

 à má c â Å
Uà má c â s1  // Ungolfed
              // Implicit: U = input string
Uà            // Take all combinations of characters in the input string.
   má         // Map each combination to all of its permutations.
      c       // Flatten into a single array.
        â     // Uniquify; remove all duplicates.
          s1  // Remove the first item (the input) from the resulting array.
              // Implicit: output resulting array, separated by commas
ETHproductions
fonte
1
Você também conseguiu Å.
Gryphon
1

Mathematica, 60 bytes

DeleteCases[""<>#&/@Permutations[c=Characters@#,Tr[1^c]],#]&

Permutationsusa um argumento numérico opcional que informa quantos valores de entrada usar para as permutações. Se atribuirmos o comprimento da entrada, ela gerará as permutações para todos os subconjuntos da entrada sem duplicatas. Tudo o que precisamos fazer é remover a entrada.

Martin Ender
fonte
1

Java 8, 313 312 306 bytes

import java.util.*;s->{Set l=new HashSet();for(int z=s.length(),i=0,j;i<z;i++)for(j=i;j<z;p("",s.substring(i,j+++1),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+++1,n),l));}

Versão modificada da minha resposta aqui , ondep("",s,l); foi substituída porfor(int z=s.length(),i=0,j;i<z;i++)for(j=i;j<z;p("",s.substring(i,j+++1),l));

-6 bytes graças a @ OlivierGrégoire na minha resposta vinculada.

Explicação desta parte:

Experimente aqui.

for(int l=s.length(),i=0,j;i<l;i++)
                               // Loop (1) from 0 to the length of the String (exclusive)
  for(j=i+1;j<=l;              //  Loop (2) from 1 to the length of the String (exclusive)
    p("",                      //   Call the permutation-method,
    s.substring(i,j+++1),l));  //   with a substring from `i` to `j` (inclusive)
                               //  End of loop (2) (implicit / single-line body)
                               // End of loop (1) (implicit / single-line body)
Kevin Cruijssen
fonte
0

Perl 6 , 75 bytes

{unique(flat $_,.comb.combinations.skip».permutations.map(*».join)).skip}

Tente

Expandido:

{                    # bare block lambda with implicit parameter 「$_」

  unique(            # return each (sub)anagram once

    flat             # unstructure the following (List of Lists into flat List)
      $_,            # the input (so we can skip it at the end)

      .comb          # split the input into graphemes
      .combinations  # get all the combinations
      .skip\         # skip the first empty combination
      ».permutations # get all the permutations of each combination
      .map(*».join)  # join the inner permutations

  ).skip             # skip the first value (the input)
}
Brad Gilbert b2gills
fonte