Horneame un pastel!

15

Este es un pastel:

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

Tiene 8 de ancho, 3 de altura y 1 de profundidad.

Debe escribir un programa que haga un pastel a partir de 3 entradas. La primera entrada controla cuántos guiones bajos hay en el medio y =s en la parte superior. Aquí está el primer pastel con un ancho de 10 en lugar de 8:

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

La segunda entrada controla qué tan alto es el pastel. Aquí está el segundo pastel con una altura de 4 en lugar de 3:

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

Tenga en cuenta la repetición de las capas.

La tercera entrada controla qué tan profundo es. Eso es cuántos | |s incluir en la parte superior. Aquí está el tercer pastel con una profundidad de 2 en lugar de 1:

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

Puede imprimir espacios en blanco al final. Casos de prueba:

Entrada: 3, 3,3

Salida:

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

(Espero nunca tener este pastel)

Entrada: 3, 2,1

Salida:

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

Entrada: 5, 5,5

Salida:

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

fuente
¿Las entradas siempre serán enteros positivos?
Nick Clifford
@NickClifford sí.
¿Se permiten nuevas líneas al final?
Shaggy
3
Relacionado
dkudriavtsev
@ Shaggy supongo que sí, por defecto es sí en Meta.
programador

Respuestas:

9

V , 25 , 20 bytes

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

Pruébalo en línea!

Hexdump:

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

Gracias a @ nmjmcman101 por guardar tres bytes y recordarme a un operador anterior que guardó otros dos bytes.

Explicación:

a,, by cson los tres argumentos.

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
DJMcMayhem
fuente
Creo que puede reemplazar Ò r|$.con Ò|èalgunos bytes. Pruébalo en línea!
nmjcman101
@ nmjcman101 Oh hombre, olvidé por completo que èincluso existía. Tuve que estrujar mi cerebro para recordar lo que hace. ¡Pero eso es realmente inteligente! De hecho, el uso de la variante en mayúsculas, È<char>probablemente también puede guardar algunos bytes más en algunos otros lugares. ¡Gracias por recordarme! :)
DJMcMayhem
4

Carbón , 34 26 bytes

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

Pruébalo en línea! El enlace es a la versión detallada del código. Toma parámetros en el orden ancho, profundidad, altura. Explicación:

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.
Neil
fuente
2

Mathematica, 167 bytes

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]}]&
J42161217
fuente
2

PHP> = 7.1, 104 bytes

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

Versión en línea

Jörg Hülsermann
fuente
1
No está mal. Encontrado 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
Y otro de 3 bytes: $b=$i++<$t?$i>1:1+$_++%2.
Christoph
@Christoph Buena idea Gracias
Jörg Hülsermann
1

Japt , 51 47 bytes

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

Pruébalo en línea!

La entrada se toma en el orden ancho, alto, profundidad.

Luke
fuente
1

Jalea , 30 29 bytes

-1 byte que cambia de una adición a un XOR para traducir entre columnas externas e internas, permitiendo una búsqueda de 5 caracteres en lugar de tener dos _entradas.

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

Programa completo de tomar tres argumentos del programa de depth, height, widthy la impresión de la torta.

Pruébalo en línea!

¿Cómo?

ṬṚ;⁹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
Jonathan Allan
fuente
1

cc , 108 bytes

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

Pruébalo en línea!

R. Kap
fuente
1

Java 7 , 169 164 158 bytes

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

Pruébalo en línea!

Sin golf:

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;
}
PunPun1000
fuente
Puede guardar 1 byte poniendo u=t+u+"+\n" inside the for-loop: (u = t + u + "+ \ n; a [2] -> 1;) s + = t;`. Pero buena respuesta, +1 de mi parte.
Kevin Cruijssen
1

05AB1E , 33 31 bytes

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

Pruébalo en línea!

Explicación

'_'=¹×«Ć,'|¹ú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
kalsowerus
fuente
1

Lote de Windows, 211 180 163 bytes

Golfé un total de 48 bytes gracias 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=
stevefestl
fuente
1
1. El uso @en cada línea y después does ligeramente más corto que @echo off. 2. @call set w=%%w%%_evita setlocal enabledelayedexpansion. 3. Uso @for /l %%p in (2,1,%2). 4. En mi humilde opinión, debe agregar @set w=para que el código funcione más de una vez.
Neil
Estoy confundido por la última parte, si no agrego @set w=, ¿el código no funcionará más de una vez?
stevefestl
1
1. Tu @for /l %%p in (1,1,%1)doparece haber desaparecido. 2. Su pastel parece tener la altura incorrecta, al menos no parece coincidir con el caso de prueba cuando lo intento. 3. Si ejecuta el script dos veces en la misma sesión de comando, entonces el pastel se vuelve cada vez más ancho.
Neil
@Neil Todo está arreglado :)
stevefestl
1
¡Excelente! Solo algunas últimas cosas que noté: 1. No necesitas el @después del &. 2 Si cambia el segundo bucle a (2,1,%3)y el tercer bucle a (1,1,%2), creo que puede eliminar la echo +%w%+línea. 3. Si he contado correctamente, creo que deberías llenar wcon espacios en lugar de _s, ya que eso dará como resultado menos sustituciones. (¡De lo @call set w= %%w%%contrario , usaría el espacio es difícil de detectar!)
Neil
1

Haskell , 87 bytes

f w t d=["_=| +_\n"!!j|i<-0:([2..d]>>[2])++([1..t]>>[2,4]),j<-i:([1..w]>>[i+1])++[i,6]]
faubi
fuente
1
Buen trabajo dejando atrás la mayoría de los idiomas que no son de golf. Una declaración de infijo (w#t)d= ...guarda un byte.
Laikoni
1

SOGL V0.12 , 25 bytes

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

Pruébalo aquí!

Espera la entrada como ancho, profundidad y altura.

dzaima
fuente
¿Está permitido reordenar entradas? Parecen especificarse en un orden prescrito.
recursivo
1
@recursive Por lo general, está permitido y en ninguna parte la pregunta fuerza el pedido y la segunda respuesta más votada reordena las entradas y probablemente haya sido vista por el OP, por lo que supongo que está bien.
dzaima
1

Python 2, 124 122 120 105 92 bytes

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

-15 bytes utilizando STDIN en lugar de argumentos del programa

-13 bytes cambiando a Python 2 (para input()ing enteros y printsentencias)

-12 bytes de Caird Coinheringaahing

Pruébalo en línea!

Python 3, 124 122 120 105 bytes

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

Pruébalo en línea!

Si no se requiere un programa completo:

Python 3, 87 84 bytes

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

Pruébalo en línea!

pizzapants184
fuente
80 bytes
caird coinheringaahing
@cairdcoinheringaahing 78 bytes .
Jonathan Frech
0

Javascript (ES6), 161 157 bytes

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

Axarydax
fuente
0

JavaScript / ES6, 90 bytes

Acabo de escribir una solución aproximada y superé la respuesta JS existente por la friolera de 56 bytes. Luego jugué 11 bytes.

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

Aquí hay una demostración.

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

Nissa
fuente