Bạn đã có một cuốn sách để làm!


15

Bạn làm việc tại một báo in ảo, lỗi thời. Để giúp bạn sắp xếp các chữ cái đơn cách nhanh hơn, bạn quyết định thực hiện chương trình ngắn nhất có thể để giúp bạn. Đưa ra một chuỗi văn bản và kích thước trang, tạo và xuất từng trang của văn bản.

Ví dụ

Ví dụ: với chiều rộng trang là 14, chiều cao 7 và một số văn bản, đây là cuốn sách của bạn:

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.   |
|            |
+------------+

Đây là thiết lập trang cơ bản:

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

Một vài thứ

  1. Có một lề một khoảng giữa các cạnh trang và văn bản.
  2. Chiều rộng và chiều cao bao gồm các cạnh hộp, nếu điều đó không rõ ràng.
  3. Sự kết hợp chỉ xảy ra nếu một từ không thể vừa trên một dòng.
  4. Chương trình cần có khả năng xuất ra nhiều trang nếu cần và chỉ có nhiều trang.
  5. Chương trình của bạn phải hỗ trợ bất kỳ kích thước trang nào, không chỉ 14 trên 7.
  6. Đây là mã golf, vì vậy giải pháp nhỏ nhất tính bằng byte (bất kỳ ngôn ngữ nào) đều thắng.
  7. Đừng phá hỏng cuộc vui. Sơ hở tiêu chuẩn rõ ràng là không được phép.

Oh, và bằng cách này:

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

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

@rod Rất tiếc, đã sửa.
tôi ..

7
Nếu bạn muốn nói for example 14điều đóe.g.
FrownyFrog


4
Chúng ta có cần xử lý 'nhiều vết cắt' trên một từ không? (thích scru-/-mpt-/-ious)
Arnauld

1
@Arnauld Nếu một từ đủ dài, thì có.
tôi ..

Câu trả lời:


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])

Hãy thử trực tuyến!


Tôi nghĩ bạn có thể sử dụng L=lenđể tiết kiệm tổng cộng 2 byte ...
Chas Brown

FYI (không chắc chắn nếu nó cần giải quyết) trường hợp thử nghiệm mà tôi đề xuất ( 7, 3, "Three Is The Magic Number!") mang lại một trang trống hàng đầu.
Jonathan Allan


3

Than , 105 83 byte

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

Hãy thử trực tuyến! Liên kết là phiên bản dài dòng của mã mà deverbosifier không thể xử lý toán tử nilary . Nếu các dòng trống hàng đầu được chấp nhận, tôi có thể giảm xuống còn 76 byte:

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

Giải trình:

NθNη

Nhập chiều rộng vào qvà chiều cao vào h.

M⁺η²↑

Di chuyển đến một vị trí sẽ kích hoạt hộp đầu tiên được rút ra, nhưng không tạo ra lề trên.

F⪪S «

Lặp lại tất cả các từ trong chuỗi đầu vào.

W›Lι⁻θ⁴«

Lặp lại trong khi một từ quá rộng để vừa với một hộp.

⊞υ⁺…ι⁻θ⁵-

Đẩy càng nhiều từ sẽ phù hợp cộng với dấu gạch nối.

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

Tiền tố một dấu gạch nối với phần còn lại của từ.

⊞υι»

Đẩy phần còn lại của từ.

Fυ«

Lặp lại tất cả các từ gạch nối.

¿‹Lι±ⅈ

Kiểm tra xem từ phù hợp với dòng hiện tại.

 «

Nếu vậy thì in một khoảng trắng.

M⁻⁻⁴ⅈθ¹

Nếu không di chuyển đến đầu dòng tiếp theo.

¿¬﹪ⅉ⊕η

Kiểm tra xem chúng tôi cần một hộp mới.

«↙↙Bθη↘→»»

Nếu vậy thì vẽ hộp.

ι

Cuối cùng, in từ.


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

Hãy thử trực tuyến!



2

JavaScript (ES8), 242 byte

Cảm ơn @ Tvde1 đã báo cáo lỗi

(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)

Hãy thử trực tuyến!

Đã bình luận

(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

Hãy thử văn bản ví dụ của bạn với 127, một số dòng / từ bị đảo ngược.
Tvde1

1
@ Tvde1 Cảm ơn bạn đã báo cáo điều này. Bây giờ nó sẽ được sửa chữa .
Arnauld

1

Thạch , 93 byte

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

Một chương trình đầy đủ dùng ba đối số ( text, width, height) mà in các trang.

Hãy thử trực tuyến! NB Quá kém hiệu quả để chạy ví dụ từ OP trong giới hạn 60 giây.

( 97 byte nếu dòng trống giữa các trang thực sự là một yêu cầu)

Làm sao?

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,"-")."+
";

Chạy với php -nr '<code>' <width> <height> '<text>'hoặc thử nó trực tuyến .

Khi sử dụng trang web của chúng tôi, bạn xác nhận rằng bạn đã đọc và hiểu Chính sách cookieChính sách bảo mật của chúng tôi.
Licensed under cc by-sa 3.0 with attribution required.