¡Encuentra todos los anagramas y los subanagramas también!

13

Esta pregunta se basa en gran medida en esta pregunta , pero debería plantear una serie de dificultades adicionales.

Tu tarea

Debe escribir un programa o función que, al recibir una cadena, imprima todos los anagramas posibles de la misma. A los fines de esta pregunta, un anagrama es una cadena que contiene el mismo carácter que la cadena original, pero no es la cadena original. Un subanagrama es un anagrama de una subcadena de una cadena ingresada. Los anagramas y subanagramas no tienen que ser o contener palabras reales.

Entrada

Puede aceptar una cadena, que puede ser de cualquier longitud> 0, por cualquier método de entrada estándar. Puede contener caracteres ASCII.

Salida

Puede generar todos los anagramas y subanagramas posibles de la cadena ingresada de cualquier manera estándar. No debe generar la misma cadena dos veces, ni generar una cadena igual a la entrada.

Otras reglas

Las lagunas estándar no están permitidas

Puntuación

Este es el , gana menos bytes.

Grifo
fuente
¿Es la cadena vacía un posible anagrama?
Trauma digital
¿Se permite la salida de la cadena / sustrings originales?
CalculatorFeline
@CalculatorFeline "No debe generar la misma cadena dos veces, ni generar una cadena igual a la entrada".
Jonathan Allan
@ DigitalTrauma, "Puede aceptar una cadena, que puede ser de cualquier longitud> 0 , por cualquier método de entrada estándar". (énfasis agregado)
Gryphon
44
Algunos casos de prueba serían útiles
Sr. Xcoder

Respuestas:

8

05AB1E , 7 bytes

Œ€œ˜Ù¹K

Una función que acepta una cadena de entrada y deja una lista de cadenas en la pila. Como programa completo, se imprime una representación de la lista.

Pruébalo en línea!

¿Cómo?

        - 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
fuente
Y ... lograste algo aún más corto.
Gryphon
Es el mismo algoritmo, solo menos bytes.
Jonathan Allan
Sí, el cambio de idioma fue todo, pero sigue siendo impresionante.
Gryphon
@ ais523 ¡Parece que me equivoqué tanto!
Jonathan Allan
@ ais523 Creo que está arreglado.
Jonathan Allan
9

Brachylog (2), 7 bytes

{sp}ᶠdb

Pruébalo en línea!

Explicación

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

fuente
¿Qué significa el (2)?
Gryphon
@Gryphon (afaik) hay 2 versiones de branchylog, esto está usando V2.
John Hamilton
1
Ok, no estaba seguro si era el número de versión o un posible conteo de bytes usando un método diferente y posiblemente ilegal.
Gryphon
1
Esa es la segunda vez que me preguntan ahora. Supongo que tendré que empezar a escribirlo como (v2).
7

Jalea , 9 bytes

ẆŒ!€;/QḟW

Un enlace monádico que acepta una lista y devuelve una lista de todos los sub-anagramas distintos, excepto la entrada en sí.

Pruébalo en línea! (el pie de página imprime la lista resultante uniéndose a las nuevas líneas).

¿Cómo?

ẆŒ!€;/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
fuente
4

Pyth, 12

-{.n.pM.:Q)]

Prueba en línea .

         Q       # input
       .: )      # all substrings
    .pM          # all permutations of all substrings
  .n             # flatten
 {               # deduplicate
-          ]Q    # subtract (list of) (implicit) input
Trauma digital
fuente
@ ais523 Redone - Creo que es correcto ahora.
Trauma digital
3

Japt , 10 bytes

à má c â Å

Pruébalo en línea!

Tengo que usar à, áy âtodo en una respuesta, en orden también. Qué casualidad...

Explicación

 à 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
fuente
1
Incluso lograste Å también.
Gryphon
1

Mathematica, 60 bytes

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

Permutationstoma un argumento numérico opcional que le indica cuántos de los valores de entrada usar para las permutaciones. Si le damos la longitud de la entrada, generará las permutaciones para todos los subconjuntos de la entrada sin duplicados. Todo lo que necesitamos hacer es eliminar la entrada.

Martin Ender
fuente
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));}

Versión modificada de mi respuesta aquí , donde p("",s,l);ha sido reemplazada 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 gracias a @ OlivierGrégoire en mi respuesta vinculada.

Explicación de esta parte:

Pruébalo aquí.

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
fuente
0

Perl 6 , 75 bytes

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

Intentalo

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
fuente