ASCII-Bücherregale


27

Sie kennen diese stapelbaren Regale, die im Grunde genommen nur Holzkisten sind, die zusammen gestapelt werden können? Wir werden simulieren, wie man Bücherregale aus solchen mit ASCII-Grafik baut.

Unsere Bücher haben alle eine bequeme einheitliche Größe und sehen alle wie folgt aus:

|X|
|X|
|X|

Bei den Bücherregalen handelt es sich um einzelne Schachteln, die innen immer drei Zeichen hoch sind (genug für ein aufrecht stehendes Buch), die aus |Zeichen links und rechts, -Zeichen oben und unten bestehen und breit genug für XBücher sind (wo Xeine Eingabe erfolgt) ganze Zahl). Zum Beispiel ist hier ein Bücherregal der Größe 3:

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

weil man so 3bücher hineinstecken kann

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

Die Eingabe wird aus zwei streng positiven ganzen Zahlen bestehen, Xund Ywo Xist die Breite der Regale, die wir haben (gemessen in Büchern), und Ywie viele Bücher müssen wir stapeln. Wenn wir mehr Bücher haben, als in ein einzelnes Regal passen, müssen wir oben mehr Regale hinzufügen. Hier ist zum Beispiel die Eingabe 4 wide / 6 books:

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

Wenn Y % X > 0, was bedeutet, dass die Anzahl der Bücher kein ganzzahliges Vielfaches der Regalgröße ist, sollten sich die restlichen Bücher ganz oben links befinden (wie im Fall von 4 6oben) und der verbleibende Teil dieses Regals mit gefüllt sein Leerzeichen.

Eingang

  • Jeweils zwei streng positive ganze Zahlen in einem beliebigen Format>0 .
  • Sie können die Eingabe in beliebiger Reihenfolge vornehmen (z. B. zuerst die Größe der Regale, dann die Anzahl der Bücher oder umgekehrt). Bitte geben Sie bei Ihrer Einsendung die Eingabereihenfolge an.
  • Sie können davon ausgehen, dass keine Eingabe größer ist als die Standardgröße [int](oder eine entsprechende Größe) Ihrer Sprache .

Ausgabe

Die daraus resultierende ASCII-Kunstdarstellung der Bücher und Bücherregale.

Regeln

  • Führende oder nachfolgende Zeilenumbrüche oder Leerzeichen sind optional, sofern die Zeichen selbst korrekt ausgerichtet sind.
  • Es ist entweder ein vollständiges Programm oder eine Funktion zulässig. Bei einer Funktion können Sie die Ausgabe zurückgeben, anstatt sie zu drucken.
  • Fügen Sie nach Möglichkeit einen Link zu einer Online-Testumgebung hinzu, damit andere Benutzer Ihren Code ausprobieren können!
  • Standardlücken sind verboten.
  • Dies ist daher gelten alle üblichen Golfregeln, und der kürzeste Code (in Byte) gewinnt.

Weitere Beispiele

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

Kann ich es so machen, dass das Regal mit der geringsten Anzahl an Büchern unten ist, so als würde es von oben nach unten
Goldener Schnitt

1
@GoldenRatio Nein, die Bücher müssen von unten nach oben und von links nach rechts gefüllt sein.
AdmBorkBork

Antworten:


14

JavaScript (ES6), 100 99 98 Bytes

Nimmt die Breite wund die Anzahl der Bücher bin der Currysyntax auf (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

Formatiert und kommentiert

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

Testfälle


9

Bash (+ Dienstprogramme), 130, 108106 Bytes

Eine einzelne, fortlaufende Shell-Pipeline zum Rendern Ihrer Bücherregale.

Änderungsprotokoll:

  • Optimierter erster sed Ausdruck ein bisschen, -12 Bytes (Thx @Riley!)
  • Ersetzt printf + seqdurch einen printfunformatierten Wert von -10 Byte
  • Der zweite sed-Ausdruck, -2 Bytes, wurde überarbeitet

Golf gespielt

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

Probieren Sie es online!

Wie es funktioniert

$./shelf 2 3

printf %$2s\\n- generiere n Leerzeichen, eines pro Buch (angezeigt als _)

___

fold -$1 - um die Regallänge falten

__
_

sed "s/ /|X|/g;"- Ersetzen _durch X, Hinzufügen von Buchumschlägen

|X||X|
|X|

:;/.\{$[$1*3]\}/!s/$/ /;t- Rechter Block mit Leerzeichen (angezeigt als _)

|X||X|
|X|___

h;s/./-/gp;x;p;p;p;x- Verdreifachen Sie jede Zeile und fügen Sie ---davor und danach hinzu.

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

sed 's/.*/|&|/'|tac- Zeilen einwickeln | |, mit tac umkehren

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

Im ersten Schritt können Sie ein namenloses Label verwenden, und tstattdessen bbrauchen Sie das nicht {}. Sie können die überspringen, s/./-/gda sie bereits -s sind. Probieren Sie es online!
Riley

@ Riley Das ist ein ausgezeichneter Rat, danke!
Zeppelin

6

Python 2, 133 113 105 Bytes

Ich bin sicher, es gibt einen besseren Weg ...

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

Die Eingabe wird übernommen width, books

-20 Bytes dank @ovs für das Erkennen einer unnötigen Lambda-Funktion!
-8 Bytes dank @ovs für die Verkürzung der Eingabe.


X,Y=input()ist ein kürzerer Weg, um die to-Werte zu nehmen.
Ovs

@ovs Oh warte, das habe ich für meinen ersten Versuch dort abgelegt. Hoppla. Netter Fang, danke!
HyperNeutrino

1
@ovs Danke, also wird die Eingabe als genommen X, Y, oder?
HyperNeutrino

2
Ich denke, dass Sie zwei Bytes sparen können, indem Sie '|'als Variable definieren.
Ørjan Johansen

6

Batch, 261 Bytes

@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

Benutzt meinen Trick aus meiner Batch-Antwort auf Lass uns Tennis spielen, um auf einfache Weise viele |Charaktere zu drucken .


5

Haskell , 100 Bytes

x#yGibt den String für width xund ybooks zurück.

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

Probieren Sie es online!

Die Hauptfunktion / Operator ist #. Wenn x<yes die Bücher in y-xund xaufteilt, dann rekursiv. Wenn x>=y, wund bsind die beiden Linientypen, abzüglich die äußeren |s und die Neue - Zeile.

Der Hilfsoperator s?nverknüpft nKopien der Zeichenfolge 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)}

Probieren Sie es online!

Nimmt Eingabe $width und $books. Legt fest, dass die Zeichenfolge $seines der horizontalen Regale ist. Dann haben wir zwei ifAussagen.

Der erste prüft, ob wir "Rest" Bücher haben. Wenn ja, geben wir das Regal, die (Anzahl der Bücher plus Anzahl der Leerzeichen) *3und ein anderes Regal aus.

Als nächstes prüfen wir, ob noch Bücher übrig sind, nachdem die Reste entfernt wurden ( $a). Dieselbe Art von Einrichtung, außer dass wir die $wAnzahl der Bücher verwenden. Da zu diesem Zeitpunkt $bgarantiert ein Vielfaches von $w(da wir den Rest entfernt haben $a) ist, müssen wir uns keine Gedanken über Rundungen machen.

Entfernt , um den [math]::Floor()Anruf, spart 15 Bytes

Alle diese Zeichenfolgen verbleiben in der Pipeline und werden Write-Outputbeim Abschluss des Programms implizit ausgeführt .


4

CJam , 62 61 Bytes

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

Übernimmt die Eingabe als width books

Probieren Sie es online!

Erläuterung

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 Bytes

Ich arbeite immer noch daran. bist für die Anzahl der Bücher und wfür die Regalbreite.

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

Willkommen bei PPCG! Dies funktioniert bei mir nur, wenn R=b%wes in die nächste Zeile verschoben wird. Sie sollten auch in der Lage sein, das Leerzeichen um diese drei =zu entfernen , um einige Bytes zu sparen.
Business Cat

Willkommen bei PPCG!
AdmBorkBork

Sie können d+3*p+d if R!=0 else ''mitR and d+3*p+d or''
shooqie

@shooqie Ich bin gespannt, wie sich dies auf das Ergebnis auswirken könnte d+3*p+d?
Juan Meleiro

1
Sie können einige Bytes sparen, indem Sie alle Definitionen mit Semikolons in eine Zeile setzen.
L3viathan

3

AHK, 208 Bytes

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%

Es gibt ein paar Dinge, die mich vom Golfspielen abhalten:

  • AutoHotkey verfügt nicht über eine integrierte Wiederholfunktion
  • Sie können die übergebenen Argumente ( %1%& %2%) nicht direkt in mathematischen Funktionen verwenden, da diese die Eingabe von Variablen oder Zahlen erwarten und davon ausgehen 1, dass die Zahl die erste und nicht der Variablenname ist
  • Ich bin nicht sehr gut im Golfen

Eine leichter zu lesende Version der oben genannten sieht so aus:

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%

Wenn a Loopkeine Klammern verwendet {}, ist nur die nächste Zeile Teil der Schleife. Wenn Sie den Wert einer Variablen mit :=anstelle von =festlegen, können Sie die Escape-Zeichen für das Prozentzeichen löschen. Tilde n ist das Newline-Zeichen.


3

Java 7, 230 224 222 Bytes

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

Erläuterung:

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

Testcode:

Probieren Sie es hier aus.

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));
  }
}

Ausgabe:

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


@ OlivierGrégoire Wenn man bedenkt, dass ich das vor ungefähr 1,5 Jahren gepostet habe, wundert es mich nicht, dass es ziemlich umfangreich golfen kann. ;)
Kevin Cruijssen

Ow ... Ich hatte das Datum nicht überprüft: Ich sah nur, dass diese Frage aktiv war und dass ein vollständiger anderer Algorithmus für Java möglich war. Mein schlechtes ...
Olivier Grégoire

@ OlivierGrégoire Kein Problem, und gut gemacht mit deiner Antwort. :) Es fühlt sich fast nostalgisch an, auf diese Antwort zurückzublicken, als ich noch die Testfälle und die Ausgabe zur Antwort hinzufügte und alles in Java 7 beantwortete, weil ich Java 8 noch nicht verstand. 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}

Weniger Golf-Testskript:

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

Ausgabe:

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, alternativ

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 Bytes

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

Probieren Sie es online!

Habe vorgehabt, dieses in den letzten Tagen auszuprobieren. Jetzt, wo ich endlich Zeit habe, gibt es bereits eine kürzere Antwort auf Python. Na ja, gerade als Alternative gepostet.

Eingabe als Breite, Bücher


1

SOGL , 64 Bytes

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

Erklärung: Erste Funktion:

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

zweite Funktion:

           →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|"]]

Diese Funktion erwartet eine Zahl (Anzahl der Bücher) auf dem Stapel und gibt die Bücher des Bücherregals aus

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

Weiter unten angegebenes Beispiel ist e = 3 (Bücherregalbreite) und b = 8 (Buchmenge)

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

Dies ist die oberste / unterste Zeile des Bücherregals und bleibt immer auf dem ersten Teil des Stapels (halb leeres Bücherregal).

Erster Hauptteil

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

Und der letzte Teil

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";

Online Version


0

Canvas , 33 Bytes

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

Probieren Sie es hier aus!

Erklärung (einige Zeichen wurden ersetzt, um einfarbiger auszusehen):

|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 Bytes

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

Nimmt die Breite bzw. die Anzahl der Bücher als Befehlszeilenargumente. Probieren Sie es online!

Erläuterung

Wir führen eine Schleife aus, um die Regale einzeln von oben nach unten zu drucken. Bei jeder Iteration aktualisieren wir b(die Anzahl der zu ydruckenden Bücher) durch Subtrahieren (die Anzahl der auf dieser Iteration gedruckten Bücher). Wenn b0 erreicht wird, wird die Schleife beendet.

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)

Da dies ein wenig kompliziert ist, ist hier ein Beispiel für die erste Iteration, wenn 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|   |"];"|---------|"]

was dann druckt als

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

0

Pyth , 56 Bytes

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

Akzeptiert die Regalbreite und die Anzahl der Bücher als separate Argumente in dieser Reihenfolge. Versuchen Sie es online hier oder überprüfen alle Testfälle auf einmal hier .

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

Viertens (viertens) , 622 Bytes (minimiert (Kommentare, Einrückungen, Wortnamen mit einem Zeichen entfernen) auf 303 Bytes)

Mein erstes Spiel mit 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

Probieren Sie es online!

Ausgabe

| ------------------ |
|| 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 ||
| ------------ |
Durch die Nutzung unserer Website bestätigen Sie, dass Sie unsere Cookie-Richtlinie und Datenschutzrichtlinie gelesen und verstanden haben.
Licensed under cc by-sa 3.0 with attribution required.