Ho dimenticato il giorno degli asciugamani


15

Ho dimenticato il giorno degli asciugamani

Link sandbox

Script PHP per entrambi gli esempi (errore, formattazione della stringa)

Script php corretto, l'input è autoesplicativo

Script PHP con più commenti / commenti $argvdi input per vedere risultati diversi

Come forse saprai, il 25 maggio è ben noto come Towel Day , a causa dei molti usi che un asciugamano può avere.

Un semplice estratto del libro "The Hitchhiker's Guide to the Galaxy" (personalmente ho preso questo libro come "guida di tutti i giorni" ) afferma:

"Un asciugamano è la cosa più enormemente utile che un autostoppista interstellare può avere. In parte ha un grande valore pratico."

Se hai bisogno di maggiori informazioni sugli asciugamani, controlla questa risposta SE.scifi


La sfida

Spero che lo farai con un asciugamano usato come una coperta per le gambe.

Scrivi un programma o una funzione completi in qualsiasi linguaggio di programmazione valido che accetta due input

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

Come disegnare un asciugamano con questi valori?

Primo utilizzosize :

Disegna un asciugamano a seconda delle dimensioni, per il nostro asciugamano

  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

Secondo, dagli il message

Devi dargli un messaggio, cos'è un asciugamano senza un bel messaggio cucito in filo d'oro?

Esempio 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

Esempio 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
     """"""""""""""""""""""""   #  

Criteri di risposta accettati

  • Questo è codegolf quindi si applicano le normali regole.

Regole

  • Si garantisce che tutte le stringhe di input si adattano alle dimensioni, quindi nessun input simile size=1; message="This string is just tooooooooooooooooooooo long to fit the width and height of your towel".

  • Il formato della stringa dipende da te, ad esempio se vuoi centrare le sottostringhe.

  • Le interruzioni di parola non sono consentite.

Le modifiche

Mi dispiace davvero per qualsiasi confusione, perché gli asciugamani ansii che disegno non corrispondono ai parametri, ho aggiunto uno script PHP per entrambi gli esempi per verificare gli output previsti.

Grazie anche a tutte le persone che hanno votato e considerato la mia prima sfida: D.


Dammi qualche minuto per risolverlo (ho appena visto questo). Quello che è successo è che ho fatto un programma su php per disegnare l'asciugamano ma era molto più semplice di quello che ho presentato, avevo un programma per gli esempi e mi sono dimenticato di modificarlo.
Francisco Hahn,

@Lynn ha aggiunto una soluzione php ungolfed con entrambi i casi di test, mi dispiace per qualsiasi confusione.
Francisco Hahn,

Possiamo scegliere dove vanno le interruzioni di linea?
Jakob,

L'interruzione di riga deve essere aggiunta quando current line + next wordsupererà il limite consentito per il tuo asciugamano @Jakob come decide lo script php che ho pubblicato.
Francisco Hahn,

possiamo prendere la larghezza e / o l'altezza del testo come argomenti invece di calcolarli?
JoshM,

Risposte:


4

Python 2 , 223 210 209 204 byte

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

Provalo online!


2

JavaScript (Node.js) , 375 byte

Questo è il peggior invio che otterrai, ma almeno ho provato xD che la metà dei byte sono spazi

(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}
`

Provalo online!


2

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

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}
`

Provalo online!


Spiegazione :

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.

2

Carbone , 79 byte

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

Provalo online! Il collegamento è alla versione dettagliata del codice. Spiegazione:

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

Calcola la dimensione dell'asciugamano.

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

Disegna l'asciugamano.

F⪪S «

Scorri ogni parola del messaggio.

×⸿›⁺ⅈLι⁻δ² ι

Stampa ogni parola senza straripare la larghezza.


Meraviglioso, e grazie per aver dedicato del tempo alla sfida.
Francisco Hahn,

1

V , 142 , 128 , 121 , 119 byte

: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Á|

Provalo online!


1
Questo è il tipo di codice che mi piacerebbe dire "Ehi, se lo fai thispuoi salvare n Bytes" .... ma non posso ... ancora: D.
Francisco Hahn,
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.