¡Cultiva un Treemote!

12

Este es mi amigo Thomas. Es mitad árbol, mitad emoticon.

|    |
| :D |
|    |

Esta solo. ¡Hagámosle algunos amigos!


Dado un emoticon basado en texto como entrada (por ejemplo ಠ_ಠ, :P, >_>, no 😀, 🤓o 🐦), salida de la treemote correspondiente.

La longitud de una mota de árbol es cuántos caracteres tiene (básicamente, la mayoría de las funciones de longitud incorporadas para las cadenas). Entonces ಠ_ಠtiene longitud 3.

La sintaxis para una treemote de longitud nes la siguiente:

|< 2+n spaces>| * ceil(n/2)
| <emote> | (note the spaces)
|< 2+n spaces>| * ceil(n/2)

Por lo tanto, cualquier treemote de longitud 3 se vería así:

|     |
|     |
| ಠ_ಠ |
|     |
|     |

Tiene ceil(n/2)segmentos de tronco separados por nueva línea a cada lado, cada uno con 2 + nespacios en el interior.

Desafío: dado el emoticón basado en texto, genere la mota de árbol correspondiente.


Otras reglas:

  • Este es el , lo que significa que quiero que escribas un código corto.
  • Lagunas estándar no permitidas.
  • Debe admitir caracteres que no sean ascii a menos que su idioma no pueda manejarlos.

Casos de prueba:

^_^

|     |
|     |
| ^_^ |
|     |
|     |

\o/

|     |
|     |
| \o/ |
|     |
|     |


(✿◠‿◠)

|        |
|        |
|        |
| (✿◠‿◠) |
|        |
|        |
|        |


D:

|    |
| D: |
|    |


( ͡° ͜ʖ ͡°)


|             |
|             |
|             |
|             |
|             |
|             |
| ( ͡° ͜ʖ ͡°) |
|             |
|             |
|             |
|             |
|             |
|             |
Rɪᴋᴇʀ
fuente
¿Se permiten nuevas líneas al final?
R. Kap
Suponemos que los emoticones 1-char no existen?
Adám
Por "emoticón basado en texto", ¿se refiere al emoticón ascii?
Downgoat
@Downgoat no. Ver el ಠ_ಠcaso de prueba.
Rɪᴋᴇʀ
66
Tal vez agregar un caso de prueba con una longitud diferente a 3 ...
SuperJedi224

Respuestas:

4

05AB1E , 27 25 bytes

Código:

g©Ìð×"|ÿ|
"®;îש„| ¹s¶®J

Explicación:

g                  # Push the length of the input string.
 ©                 # Copy that to the register.
  Ì                # Increment by 2.
   ð×              # Multiply by spaces.
     "|ÿ|\n"       # ÿ is used for interpolation and push the string "|spaces|\n".
                   #
 ®                 # Retrieve the value from the register.
  ;î               # Divide by 2 and round up.
    ×              # Multiply that by "|spaces|".
     ©             # Copy this into the register.
      „|           # Push the string "| ".
         Â         # Bifurcate, pushing the string and the string reversed.
          ¹s       # Push input and swap.
            ¶      # Push a newline character.
             ®J    # Retrieve the value from the register and join everything in the stack.
                   # Implicitly output this.

Utiliza la codificación CP-1252 . Pruébalo en línea! .

Adnan
fuente
La entrada ( ͡° ͜ʖ ͡°)devuelve resultados divertidos.
Shaun Wild
@ShaunWild Sí, es un caso de prueba extraño, porque ( ͡° ͜ʖ ͡°)tiene 11 caracteres de largo, pero parece tener 8 caracteres de largo.
Adnan
4

Python 3.5, 76 75 73 bytes:

Gracias a Blue por un consejo que ahorró 2 bytes! )

def i(n):q=len(n);z=('|'+' '*(2+q)+'|\n')*-(-q//2);print(z+'| '+n+' |\n'+z)

¡Pruébelo en línea! (Ideona)

Además, aquí hay una versión de Python 2.7.5 no competitiva ya que es mucho más larga a 87 bytes .

def i(n):q=len(n.decode('utf-8'));z=('|'+' '*(2+q)+'|\n')*-(-q/2);print z+'| '+n+' |\n'+z

Esto se debe a que la codificación predeterminada de Python 2 es ascii, y por lo tanto, los caracteres que se encuentran fuera del rango de puntos unicode 128 cuentan como más de 1 byte ( list('ಠ')rendimientos ['\xe0', '\xb2', '\xa0']). La única solución que se me ocurrió para esto fue decodificar primero la entrada usando utf-8, y luego seguir con esta utf-8cadena decodificada.

¡Prueba esta versión de Python 2 en línea! (Ideona)

R. Kap
fuente
Puede deshacerse de los elementos parentes (- (- q // 2)) por 2 bytes. Creo que puede guardar 2 bytes más cambiando a Python 2.7. No necesita el segundo / in //, y solo un espacio en la declaración de impresión.
Azul
@Blue Sí, tienes razón, puedo eliminar ese segundo par de paréntesis. Sin embargo, yo no necesito el segundo /en //hacer el ceil división.
R. Kap
como decía, en Python 2.7 la división entera se realiza con 1 /
Azul
@Blue Oh, supuse que estabas diciendo que no necesito eso en Python 3. Bueno, en ese caso, cambiaré a Python 2. ¡Gracias por los consejos! :)
R. Kap
@Blue Si ese es el caso, ¿cómo se hace la división flotante en Python 2?
R. Kap
3

Dyalog APL , 37 34 33 bytes

{↑'|'{⍺⍵⍺}¨b,(⊂⍵),b←' '/⍨⌈0.5×≢⍵}

Usuarios de Chrome: ver nota al pie *

Casos de prueba

      f←{↑'|'{⍺⍵⍺}¨b,(⊂⍵),b←' '/⍨⌈0.5×≢⍵}

      f,'☺' ⍝ the , is necessary to create a 1 char string instead of a character scalar
|   |
| ☺ |
|   |
      f':D'
|    |
| :D |
|    |
      f'^_^'
|     |
|     |
| ^_^ |
|     |
|     |

* Chrome muestra incorrectamente los dos caracteres ≢⍵(U + 2262, U + 2375) como ≢⍵(U + 2261, U + 0338, U + 2375) en lugar de como ̸≡⍵(U + 0338, U + 2262, U + 2375), así que aquí hay un Versión de pantalla para Chrome:{↑'|'{⍺⍵⍺}¨b,(⊂⍵),b←' '/⍨⌈0.5×̸̸≡⍵}

Adán
fuente
1
+1 por tener emoticones dentro de su propio código {⍺⍵⍺} ¨b
Value Ink
3
Ah, {⍺⍵⍺}¨bes el emoticón "programador APL en su quinta taza de café dando un pulgar hacia arriba".
Lynn
2

V, 60 57 bytes

I| A |ByWo=ceil(len(""")/2.0)
 dF.d0kwviWr Yu@-pH@-P

Desafortunadamente, V no tiene casi nada en términos de operaciones matemáticas. Las funciones de división y techo aumentaron drásticamente el recuento de bytes.

Como esto contiene un montón de desagradables no imprimibles, aquí hay un hexdump reversible:

00000000: 497c 201b 4120 7c1b 4279 576f 123d 6365  I| .A |.ByWo.=ce
00000010: 696c 286c 656e 2822 1222 2229 2f32 2e30  il(len("."")/2.0
00000020: 290d 201b 6446 2e64 306b 7776 6957 7220  ). .dF.d0kwviWr 
00000030: 5975 402d 7048 402d 50                   Yu@-pH@-P

Explicación:

I| A |                                #Add surrounding bars
      B                               #Move back
       yW                             #Yank a word
         o                            #Open a new line
          <C-r>=                      #Evaluate

          <C-r>"                      #Insert the yanked text into our evaluation
ceil(len("      ")/2.0)<cr>           #Evaluate ceil(len(text)/2) and insert it

 dF.                                  #Append a space and delete backward to a (.)
                                      #By default, this will be in register "-
    d0                                #Delete this number into register a
      kw                              #Move up, and forward a word
        viWr                          #Replace the emoticon with spaces
             Yu                       #Yank this line, and undo 
                                      #(so we can get the emoticon back)
               @-p                    #Paste this text "- times.
                  H                   #Move to the beginning
                   @-P                #Paste this text "- times behind the cursor.
James
fuente
¿Cuántos bytes habría sido si hubiera operadores matemáticos?
Adnan
@Adnan Es difícil de decir, ya que no sé exactamente cómo se verán. ¿Optimistamente diría alrededor de 30 bytes?
James
2

Vitsy, 43 bytes

IV2m3mz4m2m
3mV\D4m
V1+2/\[1m]
' || '
}}ZaO

Explicación:

IV2m3mz4m2m

I            Grab the length of the input string.
 V           Save that value to a global final variable.
  2m         Call the method at line index 2.
    3m       Call the method at line index 3.
      z      Push the entire input to the stack.
       4m    Call the method at line index 4.
         2m  Call the method at line index 2.

3mV\D4m

3m           Call the method at line index 3.
  V          Push the global variable to the stack.
   \D        Duplicate the top item on the stack that many times.
     4m      Call the method at line index 4.

V1+2/\[1m]

V            Push the global variable to the stack.
 1+          Add one to the top value.
             REASONING: We want ceil(V/2), and since repeat commands follow the floor value of repeats, we want ceil(V/2)+.5, so we add one to make this work right.
   2/        Divide by two.
     \[1m]   Call method 1 that top value of the stack times.

' || '

' || '       Push ' || ', the string, to the stack.

}}ZaO

}}           Push the bottom item of the stack to the top twice.
  Z          Output everything in the stack.
   aO        Output a newline.

Pruébalo en línea!

Tenga en cuenta que, debido a un error en TIO, la entrada con caracteres Unicode no funcionará. Tendrás que usar la versión local en su lugar para esos. Gracias @ Dennis!

Addison Crump
fuente
1

Pyke, 31 bytes

"||
"1dQlO*:Ql_2f_*iO"|  |"2Q:i

Pruébalo aquí!

Gracias @ R.Kap por guardar un byte con el truco de división de piso

Azul
fuente
1

Ruby, 57 bytes

Utiliza trucos de división de enteros y aprovecha las peculiaridades de la putsfunción de Ruby .

->e{s=e.size+1;puts k=[?|+' '*-~s+?|]*(s/2),"| #{e} |",k}
Tinta de valor
fuente
1

JavaScript ES6, 83 78 bytes

e=>(a=`| ${" ".repeat(n=e.length)} |
`.repeat(Math.ceil(n/2)))+`| ${e} |
${a}`
Conor O'Brien
fuente
No necesita el f=, eso le ahorra 2 bytes. Ahorre otros 2 bytes moviéndose edentro de la plantilla y aafuera. Guarde otros 2 bytes insertando espacios en lugar de agregar 2 a la repetición. Ahorre otro grupo de bytes utilizando el desplazamiento de bits para dividir entre 2.
Neil
No creo que esto funcione, solo intenta imprimir el código fuente de la repetición
Bálint
Inténtalo de nuevo, lo arreglé @ Bálint
Conor O'Brien
1

> <> , 103 bytes

i:0(?\
}$&1[\~rl:::2%+*:2,
1-:?!\" "$
]{\  \~
?!\$}1-:
~&\
?!\l$:@-[l2)
~]\
}}\" || "
?!\ol
8.>]l?!;ao2

Pruébalo en línea!

Esta solución se basa en la observación de que cada línea consiste | <x> |, dónde <x>está el patrón en la línea media y el mismo número de espacios en las otras líneas.

Después de leer la entrada (longitud n) de STDIN, el programa empuja n*(n+(n%2))espacios. La pila se rueda la mitad de las veces. A continuación, todos menos los npersonajes son arrastrados a una nueva pila, dejando una pila de pilas que consisten en nespacios o en el patrón en sí (solo en la pila central). En el paso de salida, el contenido de la pila actual se imprime, rodeado por |y |.

Sok
fuente
1

C, 89 bytes

f;main(int c,char**a){for(c=strlen(*++a)+1;f<(c|1);)printf("|%*s |\n",c,f++==c/2?*a:"");}

Sin embargo, no estoy seguro de si manejará un emoticón no ASCII ...

aragaer
fuente
¿Puedes probarlo con los emoticones no ASCII?
Rɪᴋᴇʀ
Probado y el resultado no fue bueno: strlencuenta los bytes hasta el primer byte cero y, como resultado, los emoticones no ASCII se consideran mucho más amplios de lo que son.
aragaer
1

PowerShell v3 +, 72 bytes

param($a)$b=("| "+(" "*($l=$a.length))+" |`n")*($l+1-shr1);"$b| $a |";$b

Toma la cadena de entrada $a. Se construye $bcomo (la cadena vacía terminada en tubería (con $a.lengthespacios en el medio) y una nueva línea final) repetida (longitud + 1 desplazada a la derecha un bit, es decir, dividida por dos y tope) veces. Luego genera las copias de $b, la cadena de entrada con sus propias canalizaciones, y finalmente las copias de $bnuevo.

Requiere v3 + para el -shroperador de bit-shift .

Ejemplos

PS C:\Tools\Scripts\golfing> .\grow-a-treemote.ps1 '>:-|'
|      |
|      |
| >:-| |
|      |
|      |


PS C:\Tools\Scripts\golfing> .\grow-a-treemote.ps1 '>:`-('
|       |
|       |
|       |
| >:`-( |
|       |
|       |
|       |
AdmBorkBork
fuente
1

Pyth, 30 bytes

Me sorprende que una tarea tan fácil no se implemente en Pyth.

Ls[K\|dbdK)j++J*/hlQ2]sym;QyQJ

Pruébalo en línea!

Monja permeable
fuente
1

TSQL, 96 88 bytes

DECLARE @ varchar(100)='^_^'

PRINT STUFF(REPLICATE('|'+SPACE(2+LEN(@))+'|
',LEN(@)*2-1),LEN(@)*(LEN(@)+5)-3,LEN(@),@)

¡Prueba en línea!

t-clausen.dk
fuente