Olvidé el día de la toalla

15

Olvidé el día de la toalla

Enlace de caja de arena

Script PHP para ambos ejemplos (error, formateando la cadena)

Se corrigió el script php, la entrada se explica por sí misma

Script PHP con más comentarios de entrada / comentarios $argvpara ver resultados diferentes

Como sabrán, el 25 de mayo es conocido como el Día de las Toallas , debido a los muchos usos que puede tener una toalla.

Un extracto simple del libro "La Guía del autoestopista galáctico" (personalmente tomé este libro como una "guía diaria" ) dice:

"Una toalla es lo más útil que un autoestopista interestelar puede tener. En parte, tiene un gran valor práctico".

Si necesita más información sobre toallas, consulte esta respuesta SE.scifi


El reto

Esperemos que hagas esto con una toalla usada como una manta para tus piernas.

Escriba un programa o función completa en cualquier lenguaje de programación válido que tenga dos entradas

size        Integer  : #The size
message     string   : #A sentence

¿Cómo dibujar una toalla con estos valores?

Primero usandosize :

Dibuje una toalla dependiendo del tamaño de entrada, para nuestra toalla

  width = 12*size

  #the line that has the "bar" its always present with different sizes

  Width is defined as:
  from the first | to the second | has to be equal to size*12 including both ||

      <-   width-> 
  [===|          |====]  
      | 12 chars ||   1  height starts here, just after the "bar"
      | SIZE = 1 ||   2
      |          ||   3   height = 5*size
      |          ||   4
      |          ||   5  height ends here just before the first line |=======|
      |==========||   # the lines with the # 
      |==========||   # are always fixed
      """"""""""""|   # it means, every towel
       |          |   # always has this 5 rows
       """"""""""""   # no matter the size

Segundo, dale el message

Tienes que darle un mensaje, ¿qué es una toalla sin un hermoso mensaje cosido en hilo dorado?

Ejemplo 1

  input: size=1, message="a simple message can stay with size"

  width = 12*size

  #the line that has the "bar" it's always present with different sizes
  #no words allowed at the bar level


  [===|          |====]  
      | a simple ||   1  height starts here, just after the "bar"
      | message  ||   2
      | can stay ||   3   height = 5*size
      | with size||   4
      |          ||   5  height ends here just before the first line |=======|
      |==========||   # the lines with the # 
      |==========||   # are always fixed
      """"""""""""|   # it means, every towel
       |          |   # always has this 5 rows
       """"""""""""   # no matter the size

Ejemplo 2

input size=2 
message="Don't Panic and bring a towel to SE Programming Puzzles and CodeGolf"

The size is 2
That means 24 width and 10 heigth

    <-    24 chars width  ->
[===|                      |====]
    | Don't Panic and bring||   1
    | a towel to SE        ||   2
    | Programming Puzzles  ||   3
    | and CodeGolf         ||   4
    |                      ||   5
    |                      ||   6
    |                      ||   7
    |                      ||   8
    |                      ||   9
    |                      ||   10
    |======================||   #  The lines with the "#"
    |======================||   #  always present and
    """"""""""""""""""""""""|   #  adapted to 
     |                      |   #  the towel width
     """"""""""""""""""""""""   #  

Criterios de respuesta aceptados

  • Este es codegolf, por lo que se aplican reglas normales.

Reglas

  • Usted está garantizado de que todas las cadenas de entrada se ajustarán al tamaño, por lo que no hay entrada como size=1; message="This string is just tooooooooooooooooooooo long to fit the width and height of your towel".

  • El formato de cadena depende de usted, por ejemplo, si desea centrar las subcadenas.

  • Los saltos de palabras no están permitidos.

Ediciones

Realmente lamento cualquier confusión, porque las toallas ansii que dibujé no coincidían con los parámetros, agregaron un script PHP para ambos ejemplos para que verifiquen los resultados esperados.

También gracias a todas las personas que votaron y consideraron mi primer desafío: D.

Francisco Hahn
fuente
Dame unos minutos para arreglarlo (acabo de ver esto). Lo que sucedió fue que hice un programa en php para dibujar la toalla, pero fue mucho más simple que el que presenté, tenía un programa para los ejemplos y olvidé modificarlo.
Francisco Hahn
@Lynn agregó una solución no protegida de php con ambos casos de prueba, perdón por cualquier confusión.
Francisco Hahn
¿Podemos elegir dónde van los saltos de línea?
Jakob
El salto de línea debe agregarse cuando current line + next wordexceda el límite permitido para su toalla @Jakob, según lo decida el script php que publiqué.
Francisco Hahn
¿Podemos tomar el ancho y / o la altura del texto como argumentos en lugar de calcularlos?
JoshM

Respuestas:

4

Pitón 2 , 223 210 209 204 bytes

def f(s,m):w=12*s-2;l='    |';print'[===|'+' '*w+'|====]';exec"j=(m+' ').rfind(' ',0,-~w);print l+'%*s||'%(w,m[:j]);m=m[j+1:];"*s*5;print(l+w*'='+'||\n')*2+' '*4+'"'*12*s+'|\n '+l+' '*w+'|\n    ','"'*12*s

Pruébalo en línea!

TFeld
fuente
2

JavaScript (Node.js) , 375 bytes

Esta es la peor presentación que obtendrás, pero al menos intenté xD. La mitad de los bytes son espacios.

(s,_,w=12*s-2,h=5*s)=>`
[===|${j=' '.repeat(w)}|====]
${[...Array(h)].map((g,i)=>_.split` `.reduce((a,b)=>((l=a.split`,`)[l.length-1]+b).length>w-1?a+','+b:a+' '+b,'').split`,`[i]).map(a=>`    |${a?(r=a.length)<w?a+' '.repeat(w-r):a:j}||    `).join`\n`+
`
    |${'='.repeat(w)}||    `.repeat(2)}
    ${y='"'.repeat(w+2)}|    
     |${j}|    
     ${y}
`

Pruébalo en línea!

Luis felipe De jesus Munoz
fuente
2

JavaScript (Node.js) , 347 345 343 337 334 328 326 bytes

b=>d=>`
[===|${M=" "[X="repeat"](c=12*b-2)}|====]
${[...Array(5*b)].map((a,b)=>d[Y="split"]` `.reduce((a,b)=>((l=a[Y]`,`)[l[Z="length"]-1]+b)[Z]>c-1?a+","+b:a+" "+b)[Y]`,`[b]).map(a=>`    |${a?(r=a[Z])<c?a+" "[X](c-r):a:" "[X](c)}||    `).join`
`+`
    |${"="[X](c)}||    `[X](2)}
    ${y='"'[X](c+2)}|
     |${M}|
     ${y}
`

Pruébalo en línea!


Explicacion:

b =>                                   // lambda function taking arg 1 : size
    d =>                               // arg 2 : message
        `                              // begin string template for drawing
[===|${                                // draw first part and now open literal 
        M = ' '[X='repeat'(c=12*b-2)]  // set 3 variables, M, X , c to be used again
    }|====]                            // close and draw the next part ====]
${[...Array(5*b)]                      // open and create an array of length 5 * b =width
.map(a,b=>                             // begin map function two args : a,b
        d[Y='split']` `                // use d(message), split at whitespace, set to Y
.reduce((a,b) =>                       // reduce to single value, arg 1 : a, arg 2 : b
        ((l = a[Y]`,`)                 // declare l and then find in l
        [l[Z='length']-1]              // set Z as length
        + b)                           // add value of b
        [Z]                            // find the length 
        > c-1 ?                        // check if it's less than c - 1
        a+','+b                        // then add `${a},${b}`
        : a + ' ' + b                  // otherwise `${a} ${b}`
        )[Y]`,`                        // close and split at comma
        [b]                            // use b again
        )                              // close
        .map(a =>                      // map over that arg 1 : a
                `    |${               // four space + | and open 
        a ?                            // if a is true or a truthy value
            (r=a[Z])                   // set value of r as a's length
            < c ?                      // check if it's less than c
                a+' '[X](c-r)          // then draw a + space repeated c-r times
                : a + ' '[X](c)        // else draw a + space repeated c times
            }                          // close
            ||    `                    // add || and 4 spaces and close
        )                              // end
        .join`
`                                      // and turn to string with new line as separator 
    +                                  // add to that
    `
    |{                                 // new line , 4 spaces and | 
        '='[X](c)}                     // repeat = c times
        ||    `[X](2)}                 // and repeat that 2 times
    ${                                 // new line + 4 space
    y = '"'[X](c+2)                    // repeat " c + 2 times and set to y
    }|                                 // close and add |
    |{                                 // add | and open
        M}|                            // put M and close and add |
    {y}                                // new line , 4 spaces and variable y
`                                      // end with new line.
Muhammad Salman
fuente
2

Carbón , 79 bytes

Nθ≔×⁵θε≔×¹²θδ←P←====[↓⁺³ε×"δ↖P↑⁺³ε←G↑²←⁻δ²↓²=↓↓↓¹×"δ↖↑⁺⁴ε====]F⪪S «×⸿›⁺ⅈLι⁻δ² ι

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

Nθ≔×⁵θε≔×¹²θδ

Calcule el tamaño de la toalla.

←P←====[↓⁺³ε×"δ↖P↑⁺³ε←G↑²←⁻δ²↓²=↓↓↓¹×"δ↖↑⁺⁴ε====]

Dibuja la toalla.

F⪪S «

Pase sobre cada palabra del mensaje.

×⸿›⁺ⅈLι⁻δ² ι

Imprima cada palabra sin desbordar el ancho.

Neil
fuente
Maravilloso, y gracias por tomarse su tiempo para el desafío.
Francisco Hahn
1

V , 142 , 128 , 121 , 119 bytes

:let @h=5*@a
:let @w=12*@a-2
O[===|@wá 4á=á]
:set tw=w
Vgq@hï{+@hjI    |kf|@hjjyt=pjp+@hjkl@wr=Ùjlr|Ù@w««r"YkP0xÁ|

Pruébalo en línea!

JoshM
fuente
1
Este es el tipo de código que me gustaría decir "Oye, si lo haces thispuedes guardar n Bytes" ... pero no puedo ... todavía: D.
Francisco Hahn