Fammi una torta!


15

Questa è una torta:

_========_
|        |
+________+
|        |
+________+
|        |
+________+

È largo 8, alto 3 e profondo 1.

È necessario scrivere un programma che crea una torta da 3 ingressi. Il primo input controlla quanti caratteri di sottolineatura sono presenti al centro e =in alto. Ecco la prima torta con una larghezza di 10 anziché 8:

_==========_
|          |
+__________+
|          |
+__________+
|          |
+__________+

Il secondo input controlla quanto è alta la torta. Ecco la seconda torta con un'altezza di 4 anziché 3:

_==========_
|          |
+__________+
|          |
+__________+
|          |
+__________+
|          |
+__________+

Nota la ripetizione dei livelli.

Il terzo input controlla quanto è profondo. Questo solo quanti | |s includere nella parte superiore. Ecco la terza torta con una profondità di 2 anziché 1:

_==========_
|          |
|          |
+__________+
|          |
+__________+
|          |
+__________+
|          |
+__________+

È possibile stampare spazi vuoti finali. Casi test:

Ingresso: 3, 3,3

Produzione:

_===_
|   |
|   |
|   |
+___+
|   |
+___+
|   |
+___+

(Spero di non avere mai questa torta)

Ingresso: 3, 2,1

Produzione:

_===_
|   |
+___+
|   |
+___+

Ingresso: 5, 5,5

Produzione:

_=====_
|     |
|     |
|     |
|     |
|     |
+_____+
|     |
+_____+
|     |
+_____+
|     |
+_____+
|     |
+_____+

Gli input saranno sempre numeri interi positivi?
Nick Clifford,

@NickClifford sì.

Sono consentite le nuove righe finali?
Shaggy,


@Shaggy, suppongo di sì, è di default su Meta.
programmatore

Risposte:


9

V , 25 , 20 byte

2é_Àé=ÙÒ|èÙÒ+È_ÀäkÀÄ

Provalo online!

hexdump:

00000000: 32e9 5fc0 e93d d9d2 7ce8 d9d2 2bc8 5fc0  2._..=..|...+._.
00000010: e46b c0c4                                .k..

Grazie a @ nmjmcman101 per aver salvato tre byte e ricordandomi un vecchio operatore che ha salvato altri due byte.

Spiegazione:

a, bec sono i tre argomenti.

2é_                   " Insert two '_' characters
   Àé=                " Insert 'a' '=' characters between them
      Ù               " Duplicate this line
       Ò|             " Replace this whole line with '|'s
         è            " *Hollow* this line (replace all the middle characters with spaces)
          Ù           " Duplicate this line
           Ò+         " Replace this whole line with '+'s
             È_       " *Hollow* this line again, but use '_' instead of spaces
               Àäk    " Make 'b' copies of this line and the line above it
                  ÀÄ  " Make 'c' copies of this line

Penso che puoi sostituirlo Ò r|$.con Ò|èper alcuni byte. Provalo online!
nmjcman101,

@ nmjcman101 Oh amico, ho completamente dimenticato che èesistesse. Ho dovuto scervellarmi per ricordare cosa fa. Ma è davvero intelligente! In effetti, usando la variante maiuscola, È<char>probabilmente è possibile salvare qualche byte in più in qualche altro posto. Grazie per avermi ricordato! :)
DJMcMayhem

4

Carbone , 34 26 byte

Nγ←×γ_↑+↑N_×γ=‖BOγF⁻N¹C⁰±²

Provalo online! Il collegamento è alla versione dettagliata del codice. Accetta i parametri in ordine larghezza, profondità, altezza. Spiegazione:

Nγ          Input the width.
←×γ_        Print a set of _s that go at the bottom of each layer.
↑+          Print one of the +s that go on the left.
↑N          Input the depth and print that many left |s.
_           Print the top left _.
×γ=         Print the =s along the top.
‖BOγ        Copy the left column to the right.
F           Repeat:
 ⁻ ¹         One time fewer than:
  N           Input of the height:
    C⁰±²        Copy the whole cake up 2 characters.

2

Mathematica, 167 byte

c=Column;r=Row;t=Table;f=Flatten;c[c/@{r/@f[{{{"_",r@t["=",#],"_"}},t[{"|",r@t[" ",#],"|"},#3-1]},1],c/@f[{t[{r@{"|",r@t[" ",#],"|"},r@{"+",r@t["_",#],"+"}},#2]},1]}]&

2

PHP> = 7,1, 104 byte

for([,$w,$h,$t]=$argv;$i<2*$h+$t;)echo str_pad($e="_|+"[$b=$i++<$t?$i>1:1+$_++%2],$w+1,"= _"[$b])."$e
";

Versione online


1
Non male. Trovato 3 byte:for([,$w,$h,$t]=$argv;$i<2*$h+$t;)echo str_pad($e="_|+"[$b=$i++<$t?$i>1:2-($i-$t&1)],$w+1,"= _"[$b])."$e\n";
Christoph

1
E un altro 3 byte: $b=$i++<$t?$i>1:1+$_++%2.
Christoph,

@Christoph Bella idea Grazie
Jörg Hülsermann,


1

Japt , 51 47 byte

"_{ç'=}_"+WçA="
|{ç}|" +(B="
+{ç'_}+" +(´V çA+B

Provalo online!

L'input viene preso in ordine larghezza, altezza, profondità.


1

Gelatina , 30 29 byte

-1 byte che passa da un'aggiunta a una XOR per tradurre tra colonne esterne e interne, consentendo una ricerca di 5 caratteri anziché avere due _voci.

ṬṚ;⁹RḤṬḤ¤Wµ^9ẋ⁵;@;µZị“_+= |”Y

Programma completo prendendo tre argomenti del programma di depth, height, widthe la stampa la torta.

Provalo online!

Come?

ṬṚ;⁹RḤṬḤ¤Wµ^9ẋ⁵;@;µZị“_+= |”Y - Main link: depth, height (width is a program argument)
Ṭ                             - untruth   [0,0,0,...1] such that the length is the depth
 Ṛ                            - reverse   [1,0,0,...0]
        ¤                     - nilad followed by link(s) as a nilad:
   ⁹                          -   link's right argument, height
    R                         -   range   [1,2,3,...,height]
     Ḥ                        -   double  [2,4,6,...,2*height]
      Ṭ                       -   untruth [0,1,0,1,0,1,...,0,1] (length double height)
       Ḥ                      -   double  [0,2,0,2,0,2,...,0,2]
  ;                           - concatenate  [1,0,0,...,0,0,2,0,2,0,2,...,0,2]
                              -     ...this is the form of a column of cake!
         W                    - wrap in a list
          µ                   - monadic chain separation, call that c
           ^9                 - bitwise XOR c with 9 [8,9,9,...,9,9,11,9,11,9,11,...,9,11]
              ⁵               - program's 3rd argument, width
             ẋ                - repeat the augmented c width times
               ;@             - concatenate with a copy of c
                 ;            - concatenate a copy of c
                  µ           - monadic chain separation call that sideways cake
                   Z          - transpose the sideways cake to put it the right way up
                     “_+= |”  - literal ['_','+','=',' ','|'] (cake decoration)
                    ị         - index into (1 based and modular, so 8,9, and 11 are, mod 5,
                                            3, 4, and 1 yielding '=', ' ', and '_')
                            Y - join with new lines
                              - implicit print

1

dc , 108 byte

?sdstsw95P61sc[lwsf[lcPlf1-dsf0<a]dsax]dsbx[_]p[[124P32sclbx[|]pld1-dsd0<j]dsjx43P95sclbx[+]plt1-dst0<h]dshx

Provalo online!



1

Java 7 , 169 164 158 byte

String f(int...a){String s="_",t="|",u="+";for(;a[0]-->0;s+="=",t+=" ")u+="_";s=s+"_";t="\n"+t+"|";u=t+"\n"+u+"+";for(;a[2]-->1;)s+=t;for(;a[1]-->0;)s+=u;return s;}

Provalo online!

Ungolfed:

String f(int...a)                    // saves two bytes over int a, int b, int c
{
    String s="_", t="|", u="+";      // set up the start of each row

    for(; a[0]-->0; s+="=", t+=" ")  // Uses the goes-to operator to fill the row
        u+="_";                      

    s += "_\n";                      // adds the end of each row
    t += "|\n";              
    u = t + u + "+\n";               // and combining t into u

    for(; a[2]-->1; )                // add the top of the cake
        s += t;

    for(; a[1]-->0; )                // add the rest of the cake
        s += u;

    return s;
}

Puoi salvare 1 byte inserendo u=t+u+"+\n" inside the for-loop: (u = t + u + "+ \ n; a [2] -> 1;) s + = t;`. Ma bella risposta, +1 da parte mia.
Kevin Cruijssen

1

05AB1E , 33 31 byte

'_'=¹×«Ć,'|¹úRóG=}²F='+'_¹×«Ć,

Provalo online!

Spiegazione

'_'=¹×«Ć,'|¹úRóG=}²F='+'_¹×«Ć,   Main link. Args: w h d
'_                                Push literal '_'
  '=¹×                            Push '=' w times
      «Ć,                         Concat, enclose and print
         '|                       Push literal '|'
           ¹ú                     Pad with w spaces in front
             RĆ                   Reverse and ecnlose
               ³G }               d - 1 times do:
                 =                Print without consuming
                   ²F             h times do:
                     =            Print without consuming
                      '+          Push literal '+'
                        '_¹×      Push '_' w times
                            «Ć,   Concat, enclose and print

1

Lotto di Windows, 211 180 163 byte

Giocato a golf per un totale di 48 byte grazie a @Neil!

@for /l %%p in (1,1,%1)do @call set w= %%w%%
@echo _%w: ==%_
@for /l %%p in (2,1,%3)do @echo ^|%w%^|
@for /l %%p in (1,1,%2)do @echo ^|%w%^|&echo +%w: =_%+
@set w=

1
1. L'uso @su ciascuna riga e dopo doè leggermente più breve di @echo off. 2. @call set w=%%w%%_evita setlocal enabledelayedexpansion. 3. Usa @for /l %%p in (2,1,%2). 4. IMHO è necessario aggiungere in @set w=modo che il codice funzioni più di una volta.
Neil,

Sono confuso dall'ultima parte, se non aggiungo @set w=, il codice non funzionerà più di una volta?
stevefestl,

1
1. Il tuo @for /l %%p in (1,1,%1)dosembra essere scomparso. 2. La tua torta sembra avere un'altezza sbagliata, almeno non sembra corrispondere al caso del test quando lo provo. 3. Se esegui lo script due volte nella stessa sessione di comando, la torta diventa sempre più ampia.
Neil,

@Neil È tutto risolto :)
stevefestl

1
Grande! Solo alcune ultime cose che ho notato: 1. Non è necessario il @dopo il &. 2 Se cambiate il secondo loop in (2,1,%3)e il terzo loop in (1,1,%2)allora penso che sia possibile eliminare la echo +%w%+linea. 3. Se ho contato correttamente, penso che dovresti riempire wdi spazi anziché di _s, poiché ciò comporterà un minor numero di sostituzioni. (Vorrei usare @call set w= %%w%%altrimenti lo spazio è difficile da individuare!)
Neil,

1

Haskell , 87 byte

f w t d=["_=| +_\n"!!j|i<-0:([2..d]>>[2])++([1..t]>>[2,4]),j<-i:([1..w]>>[i+1])++[i,6]]

1
Bel lavoro lasciando indietro la maggior parte delle lingue non golf. Una dichiarazione infix (w#t)d= ...salva un byte.
Laikoni

1

SOGL V0.12 , 25 byte

e =*¼_Oe↕¼|.⌡Qe╔*¼+.H«{Q;

Provalo qui!

Prevede l'input come larghezza, profondità, quindi altezza.


È consentito riordinare gli input? Sembrano specificati in un ordine prestabilito.
ricorsivo il

1
@recursive Di solito è permesso e da nessuna parte la domanda forza l'ordinamento e la seconda risposta più votata riordina gli input e probabilmente è stata vista dall'OP, quindi presumo che vada bene.
dzaima,

1

Python 2, 124 122 120 105 92 byte

w,t,d=input()
a="\n|"+w*" "+"|"
print"_"+w*"="+"_"+(d-1)*a+t*(a+"\n+"+w*"_"+"+")

-15 byte usando STDIN invece degli argomenti del programma

-13 byte passando a Python 2 (per input()ing numeri interi eprint istruzione)

-12 byte da Caird Coinheringaahing

Provalo online!

Python 3, 124 122 120 105 byte

w,t,d=[int(input())for n in(1,2,3)]
a="\n|"+w*" "+"|"
print("_"+w*"="+"_"+(d-1)*a+t*(a+"\n+"+w*"_"+"+"))

Provalo online!

Se non è richiesto un programma completo:

Python 3, 87 84 byte

lambda w,t,d:"_"+w*"="+"_"+(d-1)*("\n|"+w*" "+"|")+t*("\n|"+w*" "+"|\n+"+w*"_"+"+")

Provalo online!



@cairdcoinheringaahing 78 byte .
Jonathan Frech,

0

Javascript (ES6), 161 157 byte

f=(w,h,d)=>{r=x=>x.repeat(w);_='_';m='+'+r(_)+'+';b='|'+r(' ')+'|';c=[_+r('=')+_];for(i=d-1;i--;)
c.push(b);for(i=h;i--;)
c.push(b+'\n'+m);return c.join`\n`}

console.log(f(8,3,1));




0

JavaScript / ES6, 90 byte

Ho appena scritto una soluzione approssimativa e mi è capitato di battere la risposta JS esistente di ben 56 byte. Quindi ho golf 11 byte.

(w,h,d,g=a=>a+a[1][r='repeat'](w)+a[0]+`
`)=>g('_=')+(l=g('| '))[r](d-1)+(l+g('+_'))[r](h)

Ecco una demo.

var F = (w,h,d,f=a=>a+a[1][r='repeat'](w)+a[0]+`
`)=>f('_=')+(l=f('| '))[r](d-1)+(l+f('+_'))[r](h);

console.log(F(prompt('width') || 3, prompt('height') || 3, prompt('depth') || 3));
console.log(F.toString().length);


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.