Hai un libro da realizzare!


15

Lavori in una macchina da stampa virtuale vecchio stile. Per aiutarti a organizzare le lettere monospaziali più velocemente, decidi di rendere il programma più breve possibile per aiutarti. Data una stringa di testo e una dimensione di pagina, genera e genera ogni pagina del testo.

Esempi

Ad esempio, con una larghezza della pagina di 14, altezza 7 e del testo, ecco il tuo libro:

14, 7, "Fruits make an extremely good snack due to their utterly scrumptious sweetness. They are also very healthy for you."
+------------+
| Fruits     |
| make an    |
| extremely  |
| good snack |
| due to     |
+------------+

+------------+
| their      |
| utterly    |
| scrumptio- |
| -us        |
| sweetness. |
+------------+

+------------+
| They are   |
| also very  |
| healthy    |
| for you.   |
|            |
+------------+

Ecco l'impostazione di base della pagina:

|---i.e.14---|
+------------+ - 
| Xxxxxxxxxx | |
| Xxxxxxxxxx | i.  
| Xxxxxxxxxx | e. 
| Xxxxxxxxxx | 7
| Xxxxxxxxxx | | 
+------------+ - 

Poche cose

  1. C'è un margine di uno spazio tra i bordi della pagina e il testo.
  2. La larghezza e l'altezza includono i bordi della scatola, se non fosse chiaro.
  3. L'avvolgimento si verifica solo se una parola non può stare su una sola riga.
  4. Il programma deve essere in grado di produrre tutte le pagine necessarie e solo quelle.
  5. Il tuo programma deve supportare qualsiasi dimensione di pagina, non solo 14 per 7.
  6. Questo è il golf del codice, quindi vince la soluzione più piccola in byte (qualsiasi lingua).
  7. Non rovinare il divertimento. Ovviamente non sono ammesse scappatoie standard.

Oh, e, a proposito:

+------------+
| May the    |
| best book  |
| publisher  | 
| win. Good  |
| Luck!      |
+------------+

+------------+
| Best       |
| program    |
| so far:    | 
| Charcoal   |
|            |
+------------+

@rod Oops, risolto.
io ...

7
Se vuoi dire for example 14che èe.g.
FrownyFrog il


4
Dobbiamo gestire "tagli multipli" con una sola parola? (come scru-/-mpt-/-ious)
Arnauld il

1
@Arnauld Se una parola è abbastanza lunga, allora sì.
io ...

Risposte:


5

Python 2 , 306 304 283 279 byte

def f(w,h,s):
 b=[];w-=4;h-=2;H='+-'+'-'*w+'-+';x=l='';s=s.split()
 while s:
	W=s.pop(0)
	if W[w:]:W,s=W[:w-1]+'-',['-'+W[w-1:]]+s
	if len(l+W)<=w-(l>x):l+=' '*(l>x)+W
	else:b+=[l];l=W
 b+=[l]+[x]*h
 while any(b):print'\n'.join([H]+['| %-*s |'%(w,b.pop(0))for _ in' '*h]+[H,x,x])

Provalo online!


Penso che puoi usare L=lenper salvare 2 byte in totale ...
Chas Brown il

Cordiali saluti (non sono sicuro se ha bisogno di essere indirizzato) il caso di test che ho suggerito ( 7, 3, "Three Is The Magic Number!") produce una pagina vuota iniziale.
Jonathan Allan,

1
@JonathanAllan Grazie, risolto :)
TFeld il

3

Carbone , 105 83 byte

NθNηM⁺η²↑F⪪S «W›Lι⁻θ⁴«⊞υ⁺…ι⁻θ⁵-≔⁺-✂ι⁻θ⁵Lι¹ι»⊞υι»Fυ«¿‹Lι±ⅈ «M⁻⁻⁴ⅈθ¹¿¬﹪ⅉ⊕η«↙↙Bθη↘→»»ι

Provalo online! Link è a verbose versione del codice della deverbosifier non è in grado di gestire le e nilary operatori . Se le righe vuote iniziali fossero accettabili, potrei ridurlo a 76 byte:

≔⁻N⁴θMθ→NηF⪪S «W›Lιθ«⊞υ⁺…ι⊖θ-≔⁺-✂ι⊖θLι¹ι»⊞υι»Fυ«¿‹⁺ⅈLιθ «F¬﹪ⅉ⊕η«⸿↙↙B⁺θ⁴η»⸿»ι

Spiegazione:

NθNη

Inserisci la larghezza in qe l'altezza in h.

M⁺η²↑

Spostati in una posizione che attiverà il primo riquadro da disegnare, ma senza generare un margine superiore.

F⪪S «

Scorri tutte le parole nella stringa di input.

W›Lι⁻θ⁴«

Ripeti mentre una parola è troppo ampia per adattarsi a una casella.

⊞υ⁺…ι⁻θ⁵-

Spingi la maggior parte della parola che si adatta più un trattino finale.

≔⁺-✂ι⁻θ⁵Lι¹ι»

Prefisso un trattino al resto della parola.

⊞υι»

Spingi il resto della parola.

Fυ«

Passa sopra tutte le parole sillabate.

¿‹Lι±ⅈ

Controlla se la parola si adatta alla riga corrente.

 «

In tal caso, stampare uno spazio.

M⁻⁻⁴ⅈθ¹

Altrimenti, passa all'inizio della riga successiva.

¿¬﹪ⅉ⊕η

Controlla se abbiamo bisogno di una nuova scatola.

«↙↙Bθη↘→»»

In tal caso, disegna la casella.

ι

Infine, stampa la parola.


2

Perl 5 , 203 182 + 1 ( -a) = 183 byte

$t=($\=-3+shift@F)-2;$h=shift@F}{say$_='+'.'-'x$\.'-+';map{$_="";{$_.=shift@F;s/.{$t}\K..+/-/&&unshift@F,-$&;$_.=$";y///c+length$F[0]<$\&&redo}printf"| %-$\s|
",$_}3..$h;say;@F&&redo

Provalo online!



2

JavaScript (ES8), 242 byte

Grazie a @ Tvde1 per aver segnalato un bug

(s,w,h)=>s.split` `.map(g=s=>l=(l+s)[W=w-5]?s[l&&A(l),l='',w-4]?g('-'+s.slice(W),A(s.slice(0,W)+'-')):s:l?l+' '+s:s,n=o=l='',h-=2,b=`+${'-'.repeat(w-2)}+
`,A=s=>o+=(!n|n++%h?'':b+`
`+b)+`| ${s.padEnd(w-3)}|
`)&&(g=s=>A(s)&&n%h?g(''):b+o+b)(l)

Provalo online!

Commentate

(s, w, h) =>                        // given s = string, w = width, h = height
  s.split` `                        // get all words by splitting the string on spaces
  .map(g = s =>                     // for each word s:
    l = (l + s)[W = w - 5] ?        //   if the word is too long for the current line:
      s[ l && A(l),                 //     append the line (if not empty)
         l = '',                    //     clear the line
         w - 4 ] ?                  //     if the word itself doesn't fit:
        g(                          //       do a recursive call with:
          '-' + s.slice(W),         //         a hyphen + the next part
          A(s.slice(0, W) + '-')    //         and append the current part + a hyphen
        )                           //       end of recursive call
      :                             //     else:
        s                           //       initialize a new line with this word
    :                               //   else:
      l ?                           //     if the current line is not empty:
        l + ' ' + s                 //       append a space + the word
      :                             //     else:
        s,                          //       initialize a new line with this word
    n = o = l = '',                 //   n = line counter, o = output, l = line
    h -= 2,                         //   adjust h
    b = `+${'-'.repeat(w - 2)}+\n`, //   b = border + linefeed
    A = s =>                        //   A = function that updates the output o:
      o += (                        //     append to o:
        !n | n++ % h ?              //       if we haven't reached an end of page:
          ''                        //         an empty string
        :                           //       else:
          b + `\n` + b              //         bottom border + linefeed + top border
      ) +                           //       followed by
      `| ${s.padEnd(w - 3)}|\n`     //       left border + padded text + right border
  ) &&                              // end of map()
  (g = s =>                         // g = recursive function taking s:
    A(s) &&                         //   append s
    n % h ?                         //   if we haven't reached an end of page:
      g('')                         //     go on with an empty line
    :                               //   else:
      b + o + b                     //     return top border + output + bottom border
  )(l)                              // initial call to g() with the last pending line

Prova il testo di esempio con 12e 7, alcune righe / parole sono invertite.
Tvde1

1
@ Tvde1 Grazie per aver segnalato questo. Ora dovrebbe essere risolto .
Arnauld,

1

Gelatina , 93 byte

1,⁴Ṭị⁾+-W,`
ṣ⁶µḊṖs⁴_6¤j⁾--;@Ḣ;Ṫḟ0s⁴_©4¤µ€ẎŒṖK€€µL€>®ẸµÐḟṪ;€⁶x®¤ḣ€®s⁵_2¤Zz⁶x®¤j@€€⁾| ,U¤j@€¢ẎY

Un programma completo di prendere tre argomenti ( text, width,height ) che stampa le pagine.

Provalo online! NB Troppo inefficiente per eseguire l'esempio dall'OP entro il limite di 60 secondi.

( 97 byte se la riga vuota tra le pagine è effettivamente un requisito)

Come?

1,⁴Ṭị⁾+-W,` - Link 1, make header & footer: no arguments
  ⁴         - program's 2nd argument, width
1           - literal one
 ,          - pair = [1,width]
   Ṭ        - untruth = [1,0,0,...,0,0,1] (a 1 at index 1 and index width; 0 elsewhere)
     ⁾+-    - literal list of characters = "+-"
    ị       - index into (1-based & modular) = "+--...--+"
        W   - wrap = ["+---...--+']
          ` - use as both arguments of the dyad:
         ,  - pair = [["+---...--+'],["+---...--+']]

ṣ⁶µḊṖs⁴_6¤j⁾--;@Ḣ;Ṫḟ0s⁴_©4¤µ€ẎŒṖK€€µL€>®ẸµÐḟṪ;€⁶x®¤ḣ€®s⁵_2¤Zz⁶x®¤j@€€⁾| ,U¤j@€¢ẎY

 - Main link. This is long so splitting it up into parts like so:
ṣ⁶µ "A" µ€ "B" µ "C" µÐḟ "D"
ṣ⁶                           - split 1st argument (text) at spaces
  µ "A" µ€                   - for €ach resulting word do "A" (get hyphenated parts)
           "B"               - do "B" (all ways to partition those joining with spaces)
                     µÐḟ     - filter discard if:
               µ "C"         -   do "C" (any parts are too long)
                         "D" - do "D" (format the resulting list into the page-format)

"A" = ḊṖs⁴_6¤j⁾--;@Ḣ;Ṫḟ0s⁴_©4¤ - Hyphenate: list, word     e.g. "Something"
      Ḋ                        - dequeue                        "omething"
       Ṗ                       - pop                            "omethin"
            ¤                  - nilad followed by link(s) as a nilad
         ⁴                     -   program's 2nd argument  e.g. 9  (width)
           6                   -   literal six                  6
          _                    -   subtract                     3
        s                      - split into chunks             ["ome","thi","n"]
              ⁾--              - literal list of characters     "--"
             j                 - join                           "ome--thi--n"
                   Ḣ           - head (word)                    "S"
                 ;@            - concatenate (sw@p arguments)   "Some--thi--n"
                     Ṫ         - tail (word)                    "g"
                    ;          - concatenate                    "Some--thi--ng"
                      ḟ0       - filter out zeros (tail yields 0 for words of length 1)
                             ¤  - nilad followed by link(s) as a nilad:
                         ⁴      -   program's 2nd argument      9
                            4   -   literal four                4
                          _     -   subtract                    5
                           ©    -   copy to register & yield    5
                        s       - split into chunks             ["Some-","-thi-","-ng"]

"B" = ẎŒṖK€€ - Line arrangements: list of lists of hyphen-parts / single words
      Ẏ      - flatten by one (make a list of words and hyphen-parts
             - e.g. [["Not"],["hyph-","-ena-","-ted"]] -> ["Not","hyph-","-ena-","-ted"]
       ŒṖ    - partition e.g. [1,2,3]->[[[1],[2],[3]],[[1],[2,3]],[[1,2],[3]],[[1,2,3]]]
         K€€ - join with spaces for €ach for €ach e.g. ["one","two"]->"one two"

"C" = L€>®Ẹ - Any part too long?: one of the list of lines from "B"
      L€    - length of €ach
         ®  - recall from the register (width minus 4)
        >   - greater than (vectorises) - 1 if so 0 if not
          Ẹ - any truthy? (1 if any too long)

"D" = Ṫ;€⁶x®¤ḣ€®s⁵_2¤Zz⁶x®¤j@€€⁾| ,U¤j@€¢ẎY - Format as pages: list of valid arrangements
      Ṫ                                     - tail (last valid partition is greediest)
            ¤                               - nilad followed by links as a nilad:
         ⁶                                  -   literal space character
           ®                                -   recall from register (width minus 4)
          x                                 -   repeat elements
       ;€                                   - concatenate to €ach
               ®                            - recall from register (width minus 4)
             ḣ€                             - head €ach to index
                    ¤                       - nilad followed by links as a nilad:
                 ⁵                          -   program's 3rd argument, height
                   2                        -   literal two
                  _                         -   subtract
                     Z                      - transpose
                          ¤                 - nilad followed by link(s) as a nilad:

                       ⁶                    -   literal space character
                         ®                  -   recall from register (width minus 4)
                        x                   -   repeat elements

                      z                     - transpose with filler (repeated spaces)
                                    ¤       - nilad followed by link(s) as a nilad:
                               ⁾|<space>    -   literal list of characters = "| "
                                   U        -   upend = " |"
                                  ,         -   pair = ["| "," |"]
                           j@€€             - join for €ach for €ach (sw@p arguments)
                                        ¢   - call last link (1) as a nilad
                                     j@€    - join for €ach (sw@p arguments)
                                         Ẏ  - flatten by one
                                          Y - join with line feeds
                                            - implicit print

0

PHP, 299 byte

for($a=explode(" ",$argv[3]);$y|$e=strlen($d=$a[+$i++]);$x||print"|",$x|$e<$w?$e<$w-$x?$x+=$e+print" $d":$i-=!$x=!$y+=print str_pad("",$w-$x)." |
":$y+=print" ".substr($d,0,$w-2)."- |
".!$a[--$i]="-".substr($d,$w-2),$y>$argv[2]-2&&$y=!print"$t
")$y||$y=print$t=str_pad("+",2+$w=$argv[1]-3,"-")."+
";

Esegui con php -nr '<code>' <width> <height> '<text>'o o provalo online .

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.