Rak Buku ASCII


27

Anda tahu rak-rak yang bisa ditumpuk yang pada dasarnya hanya kotak kayu yang bisa ditumpuk bersama? Kita akan mensimulasikan membangun beberapa rak buku dari yang memiliki seni ASCII.

Buku kami semua nyaman seragam dalam ukuran, dan semua terlihat seperti berikut ini:

|X|
|X|
|X|

Rak buku adalah kotak tersendiri, selalu tiga karakter di bagian dalam (cukup untuk membuat buku berdiri tegak), terdiri dari |karakter di kiri dan kanan, -karakter untuk atas dan bawah, dan cukup lebar untuk muat Xbuku (di mana Xada input bilangan bulat). Misalnya, berikut ini rak buku berukuran 3:

|---------|
|         |
|         |
|         |
|---------|

karena Anda dapat memasukkan 3buku ke dalamnya seperti itu

|---------|
||X||X||X||
||X||X||X||
||X||X||X||
|---------|

Masukan akan menjadi dua bilangan bulat yang benar-benar positif, Xdan Y, di mana Xlebar rak yang kita miliki (diukur dalam buku), dan Yberapa banyak buku yang harus kita susun. Jika kita memiliki lebih banyak buku daripada yang muat di satu rak, kita perlu menambahkan lebih banyak rak ke atas. Sebagai contoh, ini adalah input 4 wide / 6 books:

|------------|
||X||X|      |
||X||X|      |
||X||X|      |
|------------|
|------------|
||X||X||X||X||
||X||X||X||X||
||X||X||X||X||
|------------|

Jika Y % X > 0, artinya jumlah buku bukan kelipatan bilangan bulat dari ukuran rak, sisa buku harus berada pada posisi paling atas paling kiri (seperti dalam kasus dengan 4 6, di atas) dan sisa bagian dari rak yang diisi dengan spasi.

Memasukkan

  • Dua bilangan bulat yang benar-benar positif dalam format apa pun , masing-masing >0.
  • Anda dapat mengambil input dalam urutan apa pun (mis., Ukuran rak terlebih dahulu, lalu jumlah buku, atau sebaliknya). Silakan sebutkan dalam kiriman Anda, pesanan input.
  • Anda dapat dengan aman berasumsi bahwa input tidak akan lebih besar dari [int]ukuran default bahasa Anda (atau setara).

Keluaran

Representasi seni ASCII yang dihasilkan dari buku dan rak buku.

Aturan

  • Leading atau trailing newlines atau whitespace semuanya opsional, asalkan karakternya berbaris dengan benar.
  • Program lengkap atau fungsi dapat diterima. Jika suatu fungsi, Anda dapat mengembalikan output daripada mencetaknya.
  • Jika memungkinkan, harap sertakan tautan ke lingkungan pengujian online agar orang lain dapat mencoba kode Anda!
  • Celah standar dilarang.
  • Ini adalah sehingga semua aturan golf biasa berlaku, dan kode terpendek (dalam byte) menang.

Contoh lebih lanjut

6 wide / 2 books
|------------------|
||X||X|            |
||X||X|            |
||X||X|            |
|------------------|

2 wide / 6 books
|------|
||X||X||
||X||X||
||X||X||
|------|
|------|
||X||X||
||X||X||
||X||X||
|------|
|------|
||X||X||
||X||X||
||X||X||
|------|

4 wide / 9 books
|------------|
||X|         |
||X|         |
||X|         |
|------------|
|------------|
||X||X||X||X||
||X||X||X||X||
||X||X||X||X||
|------------|
|------------|
||X||X||X||X||
||X||X||X||X||
||X||X||X||X||
|------------|

Dapatkah saya membuatnya sehingga rak dengan jumlah buku paling sedikit ada di bagian bawah, jadi seperti itu mengisi atas ke bawah
Golden Ratio

1
@GoldenRatio Tidak, buku harus diisi dari bawah ke atas, kiri ke kanan.
AdmBorkBork

Jawaban:


14

JavaScript (ES6), 100 99 98 byte

Mengambil lebar wdan jumlah buku bdalam sintaks currying (w)(b).

w=>g=(b,s=`|${'-'.repeat(w*3)}|
`,r=s.replace(/---/g,_=>b&&b--?'|X|':'   '))=>(b?g(b)+s:s)+r+r+r+s

Diformat dan dikomentari

w =>                                // main function: takes width 'w' as input, returns 'g'
  g = (                             // g = recursive function with:
    b,                              //   - b = number of books
    s = `|${'-'.repeat(w * 3)}|\n`, //   - s = top/bottom of shell, filled with '-'
    r = s.replace(                  //   - r = pattern of the current row of books,
      RegExp('---', 'g'),           //         using 's' as a template and updating
      _ => b && b-- ? '|X|' : '   ' //         'b' while building it
    )                               // NB: 'r' must be defined in the scope of 'g',
  ) =>                              //     otherwise it would be overwritten by
    (                               //     subsequent calls
      b ?                           // if there are remaining books:
        g(b) + s                    //   do a recursive call and append shell top
      :                             // else:
        s                           //   just append shell top
    ) + r + r + r + s               // append book rows and shell bottom

Uji kasus


9

Bash (+ utilitas), 130, 108, 106 byte

Satu, terus menerus, pipeline shell untuk membuat rak buku Anda.

Changelog:

  • Dioptimalkan ekspresi sed pertama sedikit, -12 byte (Thx @Riley!)
  • Diganti printf + seqdengan mentah printf, -10 byte
  • Refactored ekspresi sed kedua, -2 byte

Golf

printf %$2s\\n|fold -$1|sed "s/ /|X|/g;:;/.\{$[$1*3]\}/!s/$/ /;t;h;s/./-/gp;x;p;p;p;x"|sed 's/.*/|&|/'|tac

$./shelf 6 8
|------------------|
||X||X|            |
||X||X|            |
||X||X|            |
|------------------|
|------------------|
||X||X||X||X||X||X||
||X||X||X||X||X||X||
||X||X||X||X||X||X||
|------------------|

Cobalah secara Online!

Bagaimana itu bekerja

$./shelf 2 3

printf %$2s\\n- menghasilkan n karakter spasi putih, satu per buku (ditampilkan sebagai _)

___

fold -$1 - lipat dengan panjang rak

__
_

sed "s/ /|X|/g;"- ganti _dengan X, tambahkan sampul buku

|X||X|
|X|

:;/.\{$[$1*3]\}/!s/$/ /;t- bantalan kanan dengan spasi (ditampilkan sebagai _)

|X||X|
|X|___

h;s/./-/gp;x;p;p;p;x- rangkap tiga setiap baris, dan tambahkan ---sebelum dan sesudahnya.

------
|X||X|
|X||X|
|X||X|
------
------
|X|   
|X|   
|X|   
------

sed 's/.*/|&|/'|tac- bungkus garis masuk | |, balikkan dengan tac

|------|
||X|   |
||X|   |
||X|   |
|------|
|------|
||X||X||
||X||X||
||X||X||
|------|

Pada sed pertama Anda dapat menggunakan label tanpa nama, dan talih-alih bAnda tidak perlu {}. Anda dapat melewati s/./-/gkarena sudah -s. Cobalah secara Online!
Riley

@Riley Itu saran yang bagus, terima kasih!
zeppelin

6

Python 2, 133 113 105 byte

Saya yakin ada cara yang lebih baik ...

X,Y=input()
k='|'+'---'*X+'|'
while Y:g=Y%X or X;print k+'\n'+('|'+'|X|'*g+'   '*(X-g)+'|'+'\n')*3+k;Y-=g

Masukan diambil width, books

-20 byte terima kasih kepada @ovs karena memperhatikan fungsi lambda yang tidak perlu!
-8 byte terima kasih kepada @ovs untuk mempersingkat input.


X,Y=input()adalah cara yang lebih singkat untuk mengambil nilai.
Ovs

@ovs Oh, tunggu, saya meletakkannya di sana untuk percobaan pertama saya. Aduh. Tangkapan yang bagus, terima kasih!
HyperNeutrino

1
@ovs Terima kasih, maka masukan diambil seperti X, Y, bukan?
HyperNeutrino

2
Saya pikir Anda dapat menyimpan dua byte dengan mendefinisikan '|'sebagai variabel.
Ørjan Johansen

6

Batch, 261 byte

@set/an=~-%1%%%2+1,b=%1-n
@set s=
@set t=
@for /l %%i in (1,1,%2)do @call set t=---%%t%%&if %%i gtr %n% (call set s=%%s%%   )else call set s=%%s%%X
@for %%s in ("|%t%|" "|%s:X=|X|%|" "|%s:X=|X|%|" "|%s:X=|X|%|" "|%t%|")do @echo %%~s
@if %b% gtr 0 %0 %b% %2

Gunakan trik saya dari jawaban Batch saya untuk Ayo bermain tenis untuk dengan mudah mencetak banyak |karakter.


5

Haskell , 100 byte

x#ymengembalikan string untuk lebar xdan ybuku.

s?n=[1..n]>>s
x#y|x<y=x#(y-x)++x#x|w<-"---"?x,b<-"|X|"?y++"   "?(x-y)=[w,b,b,b,w]>>=('|':).(++"|\n")

Cobalah online!

Fungsi / operator utama adalah #. Ketika x<ymembagi buku menjadi y-xdan x, kemudian berulang. Kapan x>=y, wdan bdua tipe garis, minus |s luar dan baris baru.

Operator helper s?nmerangkai nsalinan string s.


5

PowerShell , 149 134 byte

param($w,$b)$s="|$('-'*$w*3)|"
if($a=$b%$w){,$s+,"|$('|X|'*$a)$(' '*3*($w-$a))|"*3+$s}
if($b-=$a){(,$s+,"|$('|X|'*$w)|"*3+$s)*($b/$w)}

Cobalah online!

Mengambil input $wdan input $b. Setel string $smenjadi salah satu rak horizontal. Lalu kami memiliki dua ifpernyataan.

Yang pertama memeriksa apakah kami memiliki buku "sisa". Jika demikian, kami menampilkan rak, (jumlah buku plus jumlah spasi) *3, dan rak lainnya.

Selanjutnya, kami melihat apakah kami masih memiliki buku yang tersisa setelah menghapus sisanya ( $a). Jenis penyiapan yang sama, kecuali kami menggunakan $wsejumlah buku. Karena pada titik ini, $bdijamin kelipatan $w(karena kami menghapus sisanya, $a), kita tidak perlu khawatir tentang pembulatan.

Menghapus [math]::Floor()panggilan, menghemat 15 byte

Semua string ini ditinggalkan di jalur pipa, dan tersirat Write-Outputterjadi saat penyelesaian program.


4

CJam , 62 61 byte

q~1a*W$/W$f{0e]}{{"|X|"S3*?}%s__'-3*W$*_}%1m>W%"|
|"*"||"\*o;

Mengambil input sebagai width books

Cobalah online!

Penjelasan

q~           Read and eval input (pushes width W and books B to the stack)
1a*          Push an array containing  the number 1 B times
W$/          Split it into chunks of size W
W$f{0e]}     Pad each chunk to width W by adding 0's to the right (the last chunk might be 
              shorter than W)
{            Apply the following to each chunk:
 {            Apply the following to each number in the chunk:
  "|X|"S3*?    Push "|X|" if the number is 1, or "   " if it's 0
 }%           (end of block)
 s            Stringify (joins with no separator)
 __           Duplicate twice (each shelf is 3 identical lines)
 '-3*W$*_     Push a string containing '-' repeated 3×W times, then duplicate it
}%           (end of block)
              At this point we have an array containing sequences of 3 identical lines 
              each followed by two lines of -'s
1m>          Rotate the array 1 to the right; brings the final line of -'s to the start
W%           Reverse the array, so that the top shelf is the partially empty one
"|\n|"*      Join the array with the string "|\n|", to build the sides of the shelves
"||"\*       Join the string "||" with the shelf string (adds the first and last | chars)
o            Print the result
;            Pop and discard W

4

Python 3, 142 byte

Masih mengerjakannya. buntuk 'jumlah buku' dan wuntuk lebar rak.

def s(b,w):
 R=b%w
 B='|\n'
 I='|'
 X='|X|'
 d=I+3*w*'-'+B
 f=I+X*w+B
 p=I+R*X+3*(w-R)*' '+B
 print(R and d+3*p+d or" ")+b//w*(d+3*f+d))

Selamat datang di PPCG! Ini tidak berfungsi untuk saya kecuali R=b%wdipindahkan ke baris berikutnya. Selain itu, Anda harus dapat menghapus spasi di sekitar ketiganya =untuk menghemat beberapa byte.
Bisnis Cat

Selamat datang di PPCG!
AdmBorkBork

Anda dapat menggantinya d+3*p+d if R!=0 else ''denganR and d+3*p+d or''
shooqie

@shooqie Saya ingin tahu, bagaimana ini bisa mengevaluasi hasil d+3*p+d?
Juan Meleiro

1
Anda dapat menyimpan beberapa byte dengan meletakkan semua definisi dalam satu baris menggunakan titik koma.
L3viathan

3

AHK, 208 byte

AutoTrim,Off
w=%1%
b=%2%
f:=Mod(b,w)
Loop,%w%
s=%s%---
s=|%s%|`n
If (f>0) {
Loop,%f%
t=%t%|X|
Loop,% w-f
t=%t% ` ` `
t=|%t%|`n
t:=s t t t s
}
Loop,%w%
r=%r%|X|
r=|%r%|`n
Loop,% (b-f)/w
t:=t s r r r s
Send,%t%

Ada beberapa hal yang membuat saya frustrasi karena bermain golf lebih lanjut:

  • AutoHotkey tidak memiliki fungsi pengulangan bawaan
  • Anda tidak bisa langsung menggunakan argumen yang diteruskan dalam ( %1%& %2%) dalam fungsi matematika karena mereka mengharapkan input variabel atau angka dan itu akan menganggap yang tidak terhapuskan 1menjadi nomor satu daripada nama variabel
  • Saya tidak pandai bermain golf

Versi yang lebih mudah dibaca di atas terlihat seperti ini:

AutoTrim,Off
w=%1%
b=%2%
f:=Mod(b,w)

Loop,%w%
   s=%s%---
s=|%s%|`n

If (f>0) {
   Loop,%f%
      t=%t%|X|
   Loop,% w-f
      t=%t% ` ` `
   t=|%t%|`n
   t:=s t t t s
}

Loop,%w%
   r=%r%|X|
r=|%r%|`n

Loop,% (b-f)/w
   t:=t s r r r s

Send,%t%

Jika a Looptidak menggunakan tanda kurung {}, maka hanya baris berikutnya yang merupakan bagian dari loop. Jika menyetel nilai variabel menggunakan :=alih-alih =, Anda bisa menjatuhkan karakter keluar tanda persen. Tilde n adalah karakter baris baru.


3

Java 7, 230 224 222 byte

String c(int w,int b){String r="",n="|\n",z="|";int i=0,j,k,t=b%w<1?w:b%w,x=b/w+(t!=w?1:0);for(;i++<w;z+="---");z+=n;for(i=0;i<x;i++){r+=z;for(j=0;j++<3;r+=n){r+="|";for(k=0;k<w;r+=i<1&k++>=t?"   ":"|X|");}r+=z;}return r;}

Penjelasan:

String c(int w, int b){                // Method with two integer parameters and String return-type
  String r = "",                       //  The return-String
         n = "|\n",                    //  Part that's used multiple times in the code
         z = "|";                      //  Shelf part of the book-boxes
  int i = 0, j, k,                     //  Indexes used in the for-loops
      t = b%w < 1 ? w : b%w,           //  Books on top shelf
      x = b/w + (t != w ? 1 : 0);      //  Amount of shelves
  for(; i++ < w; z += "---"); z += n;  //  Create the shelf-part ("|---|"; with w times "---")
  for(i = 0; i < x; i++){              //  Loop over the rows
    r += z;                            //   Append the result with the shelf-part
    for(j = 0; j++ < 3; ){             //   Loop three times (the height of the books & boxes)
      r += "|";                        //    Append the result-String with "|"
      for(k = 0; k < w;                //    Loop over the columns
          r +=                         //     And append the result-String with:
           i < 1                       //      If this is the first row:
           & k++ >= t ?                //      And the current column is larger or equal to the amount of books in the top shelf
             "   "                     //       Use an empty space
           :                           //      Else:
             "|X|"                     //       Use the book-part
            );                         //    End of columns loop
         r += n;                       //    Append the result-String with a "|" and a new-line
       }                               //   End of the loop of three
      r += z;                          //   Append the result-String with the shelf-part
    }                                  //  End of rows loop
    return r;                          //  Return the result-String
 }                                     // End of method

Kode uji:

Coba di sini.

class M{
  static String c(int w,int b){String r="",n="|\n",z="|";int i=0,j,k,t=b%w<1?w:b%w,x=b/w+(t!=w?1:0);for(;i++<w;z+="---");z+=n;for(i=0;i<x;i++){r+=z;for(j=0;j++<3;r+=n){r+="|";for(k=0;k<w;r+=i<1&k++>=t?"   ":"|X|");}r+=z;}return r;}

  public static void main(String[] a){
    System.out.println(c(6, 2));
    System.out.println(c(2, 6));
    System.out.println(c(4, 9));
  }
}

Keluaran:

|------------------|
||X||X|            |
||X||X|            |
||X||X|            |
|------------------|

|------|
||X||X||
||X||X||
||X||X||
|------|
|------|
||X||X||
||X||X||
||X||X||
|------|
|------|
||X||X||
||X||X||
||X||X||
|------|

|------------|
||X|         |
||X|         |
||X|         |
|------------|
|------------|
||X||X||X||X||
||X||X||X||X||
||X||X||X||X||
|------------|
|------------|
||X||X||X||X||
||X||X||X||X||
||X||X||X||X||
|------------|

1
Saya tidak tahu caranya, tetapi kelihatannya seperti lambda dan .repeatsungguh, sangat membantu dalam tantangan ini .
Olivier Grégoire

@ OlivierGrégoire Mengingat saya memposting ini sekitar 1,5 tahun yang lalu, saya tidak terkejut bisa bermain golf secara substansial. ;)
Kevin Cruijssen

Ow ... Saya belum memeriksa tanggalnya: Saya hanya melihat bahwa pertanyaan ini aktif dan bahwa algoritma lengkap lainnya untuk Java dimungkinkan. Buruk saya ...
Olivier Grégoire

@ OlivierGrégoire Tidak masalah, dan dilakukan dengan baik dengan jawaban Anda. :) Hampir terasa nostalgia melihat kembali jawaban ini ketika saya masih menambahkan test case dan output ke jawabannya, dan menjawab semuanya di Java 7, karena saya belum mengerti Java 8. XD
Kevin Cruijssen

2

PowerShell, 109 byte

param($w,$b)for(;$b;$b-=$c){if(!($c=$b%$w)){$c=$w}($l="|$('-'*$w*3)|")
,"|$('|X|'*$c)$(' '*($w-$c)*3)|"*3
$l}

Skrip uji yang kurang golf:

$f = {

param($w,$b)
for(;$b;$b-=$c){
    if(!($c=$b%$w)){$c=$w}
    ($l="|$('-'*$w*3)|")
    ,"|$('|X|'*$c)$(' '*($w-$c)*3)|"*3
    $l
}

}

@(
    ,(6, 2, 
    "|------------------|",
    "||X||X|            |",
    "||X||X|            |",
    "||X||X|            |",
    "|------------------|")

    ,(2, 6,
    "|------|",
    "||X||X||",
    "||X||X||",
    "||X||X||",
    "|------|",
    "|------|",
    "||X||X||",
    "||X||X||",
    "||X||X||",
    "|------|",
    "|------|",
    "||X||X||",
    "||X||X||",
    "||X||X||",
    "|------|")

    ,(4, 9,
    "|------------|",
    "||X|         |",
    "||X|         |",
    "||X|         |",
    "|------------|",
    "|------------|",
    "||X||X||X||X||",
    "||X||X||X||X||",
    "||X||X||X||X||",
    "|------------|",
    "|------------|",
    "||X||X||X||X||",
    "||X||X||X||X||",
    "||X||X||X||X||",
    "|------------|")
) | % {
    $w,$b,$expected = $_
    $result = &$f $w $b
    "$result"-eq"$expected"
    $result
}

Keluaran:

True
|------------------|
||X||X|            |
||X||X|            |
||X||X|            |
|------------------|
True
|------|
||X||X||
||X||X||
||X||X||
|------|
|------|
||X||X||
||X||X||
||X||X||
|------|
|------|
||X||X||
||X||X||
||X||X||
|------|
True
|------------|
||X|         |
||X|         |
||X|         |
|------------|
|------------|
||X||X||X||X||
||X||X||X||X||
||X||X||X||X||
|------------|
|------------|
||X||X||X||X||
||X||X||X||X||
||X||X||X||X||
|------------|

PowerShell, 109 byte, alternatif

param($w,$b)for(;$b;$b-=$c){($l="|$('---'*$w)|")
,"|$('|X|'*($c=(($b%$w),$w-ne0)[0]))$('   '*($w-$c))|"*3
$l}

1

Python 2 , 120 118 byte

i,j=input()
a=j%i
n='|\n'
x='|'+'---'*i+n
print(x+('|'+'|x|'*a+' '*(i-a)*3+n)*3,'')[a<1]+(x+('|'+'|x|'*i+n)*3)*(j/i)+x

Cobalah online!

Berarti sudah mencoba yang satu ini selama beberapa hari terakhir. Sekarang saya akhirnya punya waktu untuk melakukannya, sudah ada jawaban Python yang lebih pendek. Oh well, baru diposting sebagai alternatif.

Input diambil sebagai lebar, buku


1

SOGL , 64 byte

be%→M"Q└ƨS‘*ač;┼→S%‘A |e3* -* |++M?tMSeM-9*@*a+┼Ot}be÷:?{teSa┼Ot

Penjelasan: Fungsi pertama:

   →M  define function M which pushes
b      the book amount
  %    mod
 e     the bookshelf width

fungsi kedua:

           →S  create function S (example input: 3)          [3]
"Q└ƨS‘         push the string "|||XXX|||" (the book)        [3, "|||XXX|||"]
      *        multiply by the number on stack (book count)  ["|||XXX||||||XXX||||||XXX|||"]
       a       push variable A (later defined "|||")         ["|||XXX||||||XXX||||||XXX|||", "|||"]
        č      chop into char array                          ["|||XXX||||||XXX||||||XXX|||", ["|", "|", "|"]]
         ;     swap top 2 on stack                           [["|", "|", "|"], "|||XXX||||||XXX||||||XXX|||"]
          ┼    horizontally append                           [["||X||X||X|", "||X||X||X|", "||X||X||X|"]]

fungsi ini mengharapkan nomor (jumlah buku) pada tumpukan dan menampilkan buku-buku rak buku

["||X||X||X|",
 "||X||X||X|",
 "||X||X||X|"]

Lebih jauh ke bawah contoh yang diberikan adalah e = 3 (lebar rak buku) dan b = 8 (jumlah buku)

%‘A              var A = "|||"                        
    |            push "|"                      ["|"]                
     e3*         push E * 3                    ["|", 9]             
         -*      push that many "-"es          ["|", "---------"]   
            |+   append "|"                    ["|", "---------|"]  
              +  prepend the "|"               ["|---------|"]      

ini adalah rak buku bagian atas / bawah dan selalu berada di tumpukan bagian pertama (rak buku setengah kosong)

Bagian utama pertama

M?               }               if the modulo != 0
  tM                             output the bookshelf top/bottom line
    S                            execute the S function width the modulo
     eM-                         push bookshelf width - modulo (empty space count)
        9*                       multiply by 9 (books are 3x3 so 3x3 spaces)
          @*                     get that many spaces
            a+                   append to that "|||"
              ┼                  horizontally append
               O                 output
                t                output the bookshelf top/bottom line

Dan bagian terakhir

be÷            floor divide book amout by width (full shelves)
   :?          if not 0 (a bug makes all loops execute once)
     {         repeat
      t        output the bookshelf top/bottom line
       eS      execute S with shelf width (full shelf)
         a┼    horizontally append "|||"
           O   output
            t  output the bookshelf top/bottom line


0

PHP> = 7.1, 138 Bytes

for([,$w,$b]=$argv;$i<ceil($b/$w)*5;)echo str_pad("|".str_repeat(["","|X|"][$t=($i+1)%5>1],$i++<5&&$b%$w?$b%$w:$w),$w*3+1,"- "[$t])."|\n";

Versi Online


0

Kanvas , 33 byte

|X|3*×⁷3×⇵-×|3*×╫│;22╋P
%?%⁸}÷[⁷⁸

Coba di sini!

Penjelasan (beberapa karakter telah diganti untuk terlihat lebih monospace):

|X|3*×⁷3×⇵-×|3*×╫│;22╋P  helper function. Prints a shelf with X books
|X|                      push "|X|"
   3*                    repeat it 3 times vertically
     ×                   repeat that horizontally by the item (X) below on the stack
      ⁷3×                push width * 3
         ⇵               ceiling divide that by 2
          -×             repeat "-" that many times
            |3*          repeat "|" vertically 3 times (aka "|¶|¶|")
               ×         prepend that to the dashes (aka ¼ of a bookshelf)
                ╫│       quad-palindromize with horizontal overlap of the remainder
                           taken before and vertical overlap of 1
                  ;      get the books on top
                   22╋   and at coordinates (2;2) in the shelf, place them in
                      P  print that whole thing

%?%⁸}÷[⁷⁸  
%?  }      if width%amount (!= 0)
  %⁸         execute the helper function with width%amount on the stack
     ÷[    repeat floor(width/amount) times
       ⁷     push width
        ⁸    execute the helper function

0

Pip -n , 45 byte

Wb-:yPPZ['-X3Xa"|X|"X(Yb%a|a).sX3Xa-yRL3]WR'|

Mengambil lebar dan jumlah buku, masing-masing, sebagai argumen baris perintah. Cobalah online!

Penjelasan

Kami menjalankan loop untuk mencetak rak satu per satu dari atas ke bawah. Pada setiap iterasi, kami memperbarui b(jumlah buku yang akan dicetak) dengan mengurangi y(jumlah buku yang dicetak pada iterasi itu). Ketika bmencapai 0, loop keluar.

Wb-:yPPZ['-X3Xa"|X|"X(Yb%a|a).sX3Xa-yRL3]WR'|
                                               a is 1st cmdline arg (shelf width); b is 2nd cmdline
                                                 arg (# books); s is space; y is ""
                                               Note that "" becomes zero in numeric contexts
Wb-:y                                          While b decremented by y is nonzero:
                       b%a|a                    b mod a, or a if that quantity is zero
                      Y                         Yank that value into y
                     (      )                   This is the number of books on the current shelf
               "|X|"                            Book-spine string
                    X                           Repeated y times
                                  a-y           Number of empty slots on the current shelf
                              sX3X              Three spaces for each slot
                             .                  Concatenate to the book-spines string
                                     RL3        Make a list of 3 copies of that string
         '-X3Xa                                 3*a hyphens
        [                               ]       Put that string and the above list in a list
                                         WR'|   Wrap all strings in the nested list in |
      PZ                                        Palindromize the outer list (adding a copy of the
                                                hyphens to the end of it)
     P                                          Print, joining all sublists on newlines (-n flag)

Karena itu sedikit terlibat, inilah contoh iterasi pertama ketika a = 3, b = 8:

Yb%a|a       2
"|X|"X ^     "|X||X|"
^ .sX3Xa-y   "|X||X|   "
^ RL3        ["|X||X|   ";"|X||X|   ";"|X||X|   "]
['-X3Xa ^ ]  ["---------";["|X||X|   ";"|X||X|   ";"|X||X|   "]]
^ WR'|       ["|---------|";["||X||X|   |";"||X||X|   |";"||X||X|   |"]]
PZ ^         ["|---------|";["||X||X|   |";"||X||X|   |";"||X||X|   |"];"|---------|"]

yang kemudian dicetak sebagai

|---------|
||X||X|   |
||X||X|   |
||X||X|   |
|---------|

0

Pyth , 56 byte

M++GHGV_fTs*V,]Q1.DEQjCg*5\|smgL\-*L3?d"|X|""   ".[*]1N0

Menerima lebar rak, jumlah buku sebagai argumen terpisah dalam urutan itu. Coba online di sini , atau verifikasi semua uji sekaligus di sini .

M++GHGV_fTs*V,]Q1.DEQjCg*5\|smgL\-*L3?d"|X|""   ".[*]1N0Q   Implicit: Q=1st arg, E=2nd arg
                                                            Trailing Q inferred
M                                                           Define a function, g(G,H):
 ++GHG                                                        Return G + H + G
                 .DEQ                                       Divmod E by Q, yields [E//Q, E%Q]
             ,]Q1                                           [[Q], 1]
           *V                                               Vectorised multiply the two previous results
                                                              This yields Q repeated E//Q times, then E%Q
          s                                                 Flatten
        fT                                                  Filter out falsey values (i.e. trailing 0 if present)
       _                                                    Reverse (to put partially filled shelf on top)
      V                                                     For N in the above:
                                                    ]1        [1]
                                                   *  N       Repeat the above N times
                                                 .[    0Q     Pad the above on the right with 0, to length Q
                             m                                Map the above, as d, using:
                                     ?d"|X|""   "               If d != 0, yield "|X|", else "   "
                                  *L3                           Multiply each char by 3
                                                                  Yields ['|||','XXX','|||'] or ['   ','   ','   ']
                              gL\-                              Use g to wrap each element in '-'
                            s                                 Flatten
                       g*5\|                                  Use g to add '|||||' to start and end of the above
                      C                                       Transpose
                     j                                        Join on newlines, implicit print

0

Keempat (gforth) , 622 byte (diminimalkan (hapus komentar, indentasi, nama kata 1-char) hingga 303 byte)

Main pertama saya dengan Forth :)

: bar 124 EMIT ;

: delimline ( width -- )
    bar
    3 * 0 DO 45 EMIT LOOP
    bar CR
;

: bookline ( width books -- )
    bar
    DUP 0 DO bar 88 EMIT bar LOOP
    2DUP = IF
        DROP DROP
    ELSE
        - 0 do 3 SPACES LOOP
    THEN
    bar CR
;

: shelf ( width books -- )
    DUP 0 = IF
        DROP DROP
    ELSE
        OVER delimline
        3 0 DO OVER OVER bookline LOOP
        DROP delimline
    THEN
;

: stack ( width books -- )
    CR
    OVER OVER OVER MOD shelf
    OVER /
    DUP 0 = IF
        DROP DROP
    ELSE 
        0 DO DUP DUP shelf LOOP
    THEN
;

6 2 stack
2 6 stack
3 5 stack
4 4 stack

Cobalah online!

Keluaran

| ------------------ |
|| X || X | |
|| X || X | |
|| X || X | |
| ------------------ |

| ------ |
|| X || X ||
|| X || X ||
|| X || X ||
| ------ |
| ------ |
|| X || X ||
|| X || X ||
|| X || X ||
| ------ |
| ------ |
|| X || X ||
|| X || X ||
|| X || X ||
| ------ |

| --------- |
|| X || X | |
|| X || X | |
|| X || X | |
| --------- |
| --------- |
|| X || X || X ||
|| X || X || X ||
|| X || X || X ||
| --------- |

| ------------ |
|| X || X || X || X ||
|| X || X || X || X ||
|| X || X || X || X ||
| ------------ |
Dengan menggunakan situs kami, Anda mengakui telah membaca dan memahami Kebijakan Cookie dan Kebijakan Privasi kami.
Licensed under cc by-sa 3.0 with attribution required.