Esquema de palabras con sus letras

14

Para los propósitos del desafío actual de "delinear" una palabra significa rodearla sucesivamente con sus propias letras, comenzando con la última, y ​​finalmente reemplazar la palabra original en el centro con espacios:

       oooooo 
       onnnno 
on ->  on  no 
       onnnno
       oooooo

Tarea:

Dada una lista de palabras, que consiste solo en letras minúsculas y / o mayúsculas en inglés, delinea cada palabra y muestra todos los bloques resultantes uno al lado del otro horizontalmente, separados por una columna de espacio único, alineados verticalmente en el centro de los bloques.

Puede escribir un programa completo o una función.

Entrada:

Una lista de palabras, o si lo prefiere, una cadena delimitada por espacio u otro símbolo

Salida:

La representación ASCII de los bloques para las palabras resumidas. Se permiten espacios en blanco iniciales / finales.

Casos de prueba:

Input 1: ["code", "golf"] (or "code golf")
Output 1:

    cccccccccccc gggggggggggg
    cooooooooooc goooooooooog
    coddddddddoc gollllllllog
    codeeeeeedoc golfffffflog
    code    edoc golf    flog
    codeeeeeedoc golfffffflog
    coddddddddoc gollllllllog
    cooooooooooc goooooooooog
    cccccccccccc gggggggggggg

Input 2: ["I", "am", "just", "a", "man"]  (or "I am just a man")
Output 2: 

           jjjjjjjjjjjj
           juuuuuuuuuuj     mmmmmmmmm
    aaaaaa jussssssssuj     maaaaaaam
III ammmma justtttttsuj aaa mannnnnam
I I am  ma just    tsuj a a man   nam  
III ammmma justtttttsuj aaa mannnnnam
    aaaaaa jussssssssuj     maaaaaaam 
           juuuuuuuuuuj     mmmmmmmmm 
           jjjjjjjjjjjj

Criterios ganadores:

El código más corto en bytes en cada idioma gana. Le agradeceré mucho si comenta / explica su código y enfoque.

Galen Ivanov
fuente
¿Podemos suponer que hay al menos una palabra?
PurkkaKoodari
@ Pietu1998 Sí, siempre habrá al menos una palabra
Galen Ivanov el
1
@Kevin Cruijssen Transpose?
Galen Ivanov el

Respuestas:

7

Lienzo , 22 20 bytes

l *;±21*{;l└*e⟳} ]r⤢

Pruébalo aquí!

Explicación:

{                 ]    map over the inputs
 l *                     array of length spaces - the canvas of the current word
    ;                    get the word back on top
     ±                   reverse it
      21*                repeat each character twice
         {      }        for each character
          ;l└              push the height of the item below (the canvas)
             *             repeat the character that many times vertically
              e            and encase the canvas in that char column
               ⟳           and rotate it clockwise for encasing the next time
                 ∙      push another space as the separator of words
                   r   center the words
                    ⤢  and transpose the final output (as everything was built vertically)
dzaima
fuente
5

Carbón , 35 bytes

FA«≔LιθMθ↑Fθ«B⁻׳θ⊗κ⊕⊗⁻θκ§ικ↘»M⊕⊗θ→

Pruébalo en línea! El enlace es a la versión detallada del código. Explicación:

FA«

Pase sobre la lista de entrada.

≔Lιθ

Obtenga la longitud de la palabra actual.

Mθ↑

Muévase a la esquina superior izquierda del contorno resultante.

Fθ«

Bucle una vez para cada personaje.

B⁻׳θ⊗κ⊕⊗⁻θκ§ικ

Dibuja un cuadro con la altura, el ancho y el carácter apropiados.

↘»

Muévase a la esquina superior izquierda del siguiente cuadro.

M⊕⊗θ→

Moverse al siguiente esquema.

Neil
fuente
4

Haskell , 188 183 174 171 167 bytes

-9 -13 bytes gracias a Laikoni .

e=[]:e
c#a=k c<$>k(c<$a!!0)a
k c s=c:s++[c]
f w=foldr(#)[p w]w
p=(' '<$)
s w=unlines.map unwords.foldr(zipWith(:))e$until(\a->all((p a>=).p)$f<$>w)(k=<<p.head)<$>f<$>w

Pruébalo en línea!

ovs
fuente
\a->and[p a>=p x|x<-f<$>w]puede ser \a->all((p a>=).p)$f<$>wy k c=(++[c]).(c:)puede ser k c s=c:s++[c].
Laikoni
3

Pyth, 34 33 bytes

Jsm+;uCjR*2HG_.iddm\ dQjCm.[lJd;J

Pruébalo en línea.

Elimina un montón de espacios en blanco adicionales, pero eso está permitido por el desafío.

Explicación

  • m... Qhace lo siguiente para cada palabra den la entrada Q:

    • m\ dasigna la palabra con x => " ", esencialmente creando la lista [" ", ..., " "]con tantos elementos como la palabra tiene letras.
    • .iddintercala la palabra consigo misma, repitiendo las letras de la palabra dos veces. _invierte esta cadena. wordse convierte ddrrooww.
    • ucomienza con G= la matriz de espacios, y aplica lo siguiente con cada letra en la cadena intercalada en H:
      • *2H repite el personaje dos veces.
      • jR... Gcoloca cada cadena Gentre el par de caracteres.
      • Cintercambia filas y columnas. Cuando estos tres pasos se realizan dos veces con el mismo carácter H, esto resume las líneas Gcon ese carácter.
    • Ahora tenemos las columnas para la palabra resumida d. +;antecede una columna de espacio.
  • saplana la matriz de columnas para cada palabra y la Jguarda en la variable J.
  • m... Jhace lo siguiente para cada columna de la salida:
    • .[lJd;rellena ambos lados de la columna con espacios para que la longitud de la columna sea igual al número de columnas. Esto siempre es suficiente relleno para alinear las columnas verticalmente.
  • Cconvierte las columnas en filas y june las filas con nuevas líneas.

Solución alternativa, 33 bytes.

j.tsm.[L\ l+dsQ+;uCjR*2HG_.iddm\ 

Pruébalo en línea.

Tenga en cuenta que hay un espacio final. Principalmente el mismo algoritmo, excepto que solo rellena columnas en la parte superior y luego se transpone con relleno de espacio.

PurkkaKoodari
fuente
3

R , 189 bytes

function(x,S=32,`+`=rbind,`*`=cbind)cat(intToUtf8(Reduce(`+`,Map(function(s,K=utf8ToInt(s),o=S-!K){for(i in rev(K))o=i+i*o*i+i
for(j in(0:(max(nchar(x))-nchar(s)))[-1])o=S*o*S
o+S},x))+10))

Pruébalo en línea!

Una colaboración entre digEmAll y yo en el chat .

function(x){
 S <- 32			# space
 `+` <- rbind			# alias for rbind
 `*` <- cbind			# alias for cbind
 outlineWord <- function(s){	# function to construct the outline for each word
  chars <- utf8ToInt(s)		# convert to code points
  output <- S - !chars		# replace each char with 32 (space)
  for(i in rev(chars))
   o <- i + i * o * i + i	# o <- rbind(i,cbind(i,o,i),i)
  for(j in(0:(max(nchar(x))-nchar(s)))[-1])
   o <- S * o * S		# pad with spaces
   o + S}			# return with an additional row of spaces between words
 outlines <- Map(outlineWord,x)	# apply outlineWord to each element of x
 outlines <- Reduce(`+`,outlines)# reduce by rbind
 outlines <- outlines+10	# add row of newlines
 cat(intToUtf8(outlines))	# convert back to strings and print
}
Giuseppe
fuente
187 con un alias obvio
J.Doe
@ J.Doe es el wiki de la comunidad, así que siéntete libre de editarlo en :-)
Giuseppe
1

05AB1E , 46 bytes

εg©;ò<Uyη央∍«®>∍}y𫩪®Xиª˜».º.∊}¶«».C.B€SζJ»

No estoy muy contento con eso, pero me alegro de que esté funcionando.

Pruébelo en línea o verifique todos los casos de prueba .

Explicación:

ε                             # Map `y` over the (implicit) input-list
 g                            #  Take the length of the current item
  ©                           #  Store it in the register (without popping)
   ;                          #  Halve it
    ò                         #  Ceil and cast to integer at the same time
     <                        #  Decrease it by 1
      U                       #  Pop and store it in variable `X`
 yη                           #  Take the prefixes of the current string `y`
   ε       }                  #  Map over these prefixes:
    ¤                         #   Take the last character of the string
     ®×                       #   Increase it to a size equal to the length from the register
       «                      #   Append it to the current prefix
        ®>                    #   Take the length from the register, and add 1
                             #   Shorten the string to that size
 y                            #  Push the string `y` again
  ð«                          #  Append a space
    ©                         #  Store it in the register (without popping)
     ª                        #  Append it at the end of the list of modified prefixes
      ®                       #  Push the string with space from the register again
       Xи                     #  Repeat it `X` amount of times
         ª                    #  Append them to the list
          ˜                   #  Flatten to remove the empty appended list if `X` was 0
           »                  #  Join by newlines
            .º.∊              #  Intersect mirror both horizontally and vertically
                }             # Close outer map
                 ¶«           # Append a newline after each (for the space delimiters)
                   »          # Join everything by newlines
                    .C        # Centralize it horizontally
                              # (too bad a centralize vertically isn't available..)
                      .B      # Split on newlines again
                        S    # Convert each line to a list of characters
                          ζ   # Zip, swapping rows/columns (with space filler by default)
                           J  # Join the loose characters of every line to a string again
                            » # Join the lines by newlines (and output implicitly)
Kevin Cruijssen
fuente