Código Golf: Jugar Cubos


El desafío

El código más corto por conteo de caracteres, que dará salida a la serie playing bricks tower de acuerdo con la entrada del usuario.

La entrada será una serie de números (positivo, negativo y cero) que representa la altura de la torre de cubo actual siguiendo su índice. Una altura de 0 significa que no hay torre y está espaciada.

Una torre de cubos se compone de cubos apilados. Si el número de entrada en el índice actual es positivo, los cubos suben, si el número de entrada es negativo, los cubos bajan. Un solo cubo se dibuja usando las 4 líneas siguientes:

   __
 /__ /|
|   | |
|___|/

Los cubos son 3D - esto significa que se esconden entre sí cuando dos torres se colocan una al lado de la otra, generando una perspectiva falsa.

Se puede suponer que toda la entrada es válida y sin errores - Cada número está separado con un espacio en blanco en una sola línea, con al menos un número.

Casos de prueba

Input:
    2 -3 -2 1 2 -1
Output:
       __              __
     /__ /|          /__ /|
    |   | |        _|   | |
    |___|/|      /__|___|/|
    |   | |__  _|   |   | |__
    |___|/__ /__|___|___|/__ /|
        |   |   | |     |   | |
        |___|___|/|     |___|/
        |   |   | |
        |___|___|/
        |   | |
        |___|/

Input:
    1 2 3 4 -2 4 3 2 1
Output:
                   __      __ 
                 /__ /|  /__ /|
               _|   | | |   | |__
             /__|___|/| |___|/__ /|
           _|   |   | | |   |   | |__
         /__|___|___|/| |___|___|/__ /|
       _|   |   |   | | |   |   |   | |__
     /__|___|___|___|/| |___|___|___|/__ /|
    |   |   |   |   | |_|   |   |   |   | |
    |___|___|___|___|/__|___|___|___|___|/
                    |   | |
                    |___|/|
                    |   | |
                    |___|/

Input:
    1 3 3 7 0 -2 -2
Output:
                   __
                 /__ /|
                |   | |
                |___|/| 
                |   | | 
                |___|/| 
                |   | | 
                |___|/| 
           __  _|   | | 
         /__ /__|___|/| 
        |   |   |   | | 
        |___|___|___|/| 
       _|   |   |   | | 
     /__|___|___|___|/| 
    |   |   |   |   | |    __  __
    |___|___|___|___|/   /__ /__ /|
                        |   |   | |
                        |___|___|/|
                        |   |   | |
                        |___|___|/

El recuento de códigos incluye la entrada/salida (es decir, el programa completo).

Author: LiraNuna, 2009-10-23

13 answers

Perl 157 caracteres

Esta entrada fue inspirada por la entrada Ruby de gnibbler, incluyendo la parte sobre incrustar el cubo en el código. También gracias a Kinopiko por enseñarme la versión 4 arg de substr.

@O=($/.$"x99)x99;map{for$n(0..$_-1,$_..-1){map{substr$O[50-2*$n+$_],$W+4/$_,6,
(_,"__"
,"/__ /|",
"|   | |",
"|___|/")[$_]}1..4}$W+=4}@ARGV;print grep/\S/,@O

Explicación:

Línea 1: Elige dónde van los cubos
Líneas 2-5: Poner cubos donde los cubos van, imprimir

 40
Author: mob,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-26 20:11:31

Ruby - 233

Cadenas mutables;) Sin límites arbitrarios de "99". pfft: p
Tuvo que perder la imagen del cubo en la fuente aunque

S=gets.split.map{|x|x.to_i}<<0
S.max.downto(S.min){|y|e=" ";q=e*3;r=e*3
S.map{|x|a=0,x;if(w=a.min)<=y&&x!=0&&y<z=a.max
r[-3,4]="|   | |";q[-3,4]="|___|/"+(y>w ?"|":e)else(z=z!=y)?q+=e*4:q[-2,4]="/__ /|"
r+=z ?e*4:"__  "end}
puts r,q}

Ruby-243

Borra el espacio extra que puse allí para obtener la bonita imagen del cubo

S=gets.split.map{|x|x.to_i}<<0
S.max.downto(S.min){|y|e=" ";q=e*3;r=e*3
S.map{|x|a=0,x;if(w=a.min)<=y&&x!=0&&y<=z=a.max
if z==y;r+="__  "
 q[-2,3]="/__ /|"else
r[-3,4]="|   | |"
q[-3,4]="|___|/"+(y>w ?e:"|")end
else r+=e*4;q+=e*4 end}
puts r,q}
$ echo 1 3 7 3 3 |ruby pc.rb
           __              
         /__ /|            
        |   | |            
        |___|/|            
        |   | |            
        |___|/|            
        |   | |            
        |___|/|            
       _|   | |__  __      
     /__|___|/__ /__ /|    
    |   |   |   |   | |    
    |___|___|___|___|/|    
   _|   |   |   |   | |    
 /__|___|___|___|___|/|    
|   |   |   |   |   | |    
|___|___|___|___|___|/  
 39
Author: gnibbler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-23 21:08:39

Python-249

El segundo bucle for se sangra con tab

S=map(int,raw_input().split())+[0]
for y in range(max(S),min(S)-1,-1):
 q=r=e=" "*4
 for x in S:
    w=x*(x<0);z=x*(x>0)
    if w<=y<z:r=r[:-3]+"|   | |";q=q[:-3]+"|___|/"+" |"[y>w]
    elif(y==z)*x:q=q[:-2]+"/__ /|";r+="__  "
    else:q+=e;r+=e
 print r+"\n"+q

Python-393

S=map(int,raw_input().split())+[0]
for Y in range(max(S),min(S)-1,-1):
 Q=R="";B=s=t=" "*4;N=0
 for y in S:
  if(y>0)*(y==Y)+(Y==0)*(y<0):
   q="_  _";r=" /__";s="_   ";t=" /| "
   if(N<y>0)+(N==0):q="   _"
   if y<N>0:q="| |_";r="|/__"
  elif(y>Y>=0)+(y<=Y<0):q="|   ";r="|___";s="| | ";t="|/"+("| "[(y==Y<0)+(Y==0)])+" "
  else:q=s;r=t;s=t=B
  Q+=q;R+=r;N=y
 print Q.rstrip()+"\n"+R.rstrip()
 6
Author: gnibbler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-23 12:26:34

Ruby, 261 258 250 242

c=[]
n=99
$F.map{|e|e=e.to_i
c<<(e<0?[e,-1]:[0,e-1])}
m=[]
x=0
c.map{|d|x+=4
k,l=d
(k+n..l+n).map{|y|y*=2
[[3,3,2,'__'],[2,1,6,'/__ /|'],[1,0,7,'|   | |'],[0,0,6,'|___|/']].map{|e|a,b,c,s=e
(m[y+a]||=' '*79)[x+b,c]=s}}}
puts m.compact.reverse

Ejecutar con ruby -n -a v2.rb

Esta entrada está ligeramente sobrediseñada, ya que puede comenzar y terminar pilas en cualquier nivel, no solo en 0. No hay manera de especificar esto en la "versión de competencia", pero si reemplaza las primeras 4 líneas con c=eval $_;n=99, entonces cae a 203 bytes y puede hacer:

[[-3,3],[-3,-2],[2,3],[-3,-3],[-2,-1],[3,3],[2,2],[1,1],[0,0]]
           __      __          __                                                  
         /__ /|  /__ /|      /__ /|                                                
        |   | | |   | |     |   | |__                                              
        |___|/| |___|/|     |___|/__ /|                                            
        |   | | |   | |         |   | |__                                          
        |___|/| |___|/          |___|/__ /|                                        
        |   | |                     |   | |__                                      
        |___|/|                     |___|/__ /|                                    
        |   | |            __           |   | |                                    
        |___|/|          /__ /|         |___|/                                     
        |   | |__       |   | |                                                    
        |___|/__ /|     |___|/|                                                    
        |   |   | |    _|   | |                                                    
        |___|___|/|  /__|___|/                                                     
        |   |   | | |   | |                                                        
        |___|___|/  |___|/   
 6
Author: DigitalRoss,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-24 05:42:19

Befunge-93 (demasiados caracteres)

Muy poco optimizada. Mi primer programa Befunge. =]

>~:88+`v6 >11p>:!|v                 g13$<       v            $<
 000090#8 + >      >68*31p  v >     1-:!|!:-1g14<p+g11g13+g12g 14<
   __  :* *      5 ^       < > 31pvvp16<>:41p1- 31g1+g :68*-!#^_ ^
 /__ /||\-6      >>1-:       |^8   < $<|       `g16 $<   <
|   | |>-*8 ^ ^ p11-2g11-1$  <    >31g   11g+:::51g` |   1
|___|/   8^0     >#-#<           v    ^<             >51p^
        <  <         |`0:       p 56 p34:p30:p26:p25:p22:p21:p20:*68<
^  v95:< 6^ *2:*  -10<           >21g4+21p 11
1  >*-   |            >     > 31g51gg,31g21g-3-!#v_v
1   >$ ^v<                 | ,+55-g16p15+1:g15   <
|!-*48 <~> ^                ^           p13+1g13   <
>   ^                      @
 6
Author: strager,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-27 19:12:50

Haskell, 349 caracteres:

r=replicate
f=foldl
k=repeat
o n a s=r n a++s++k a
main=do{a<-getLine;let{n=map read$words a;u=f max 0 n;d=f min 0 n;i=r(2*(1+u-d))$r(4*length n+3)' '};putStr$unlines$f(\j(x,n)->f(\i y->[[if a=='x'then b else a|(a,b)<-zip m n]|(m,n)<-zip(o(2*(u-y))(k 'x')$map(o(4*x)'x')["xxx__xx","x/__ /|","|   | |","|___|/x"])i])j[1+min 0 n..max 0 n])i$zip[0..]n}
 5
Author: comingstorm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-23 10:26:43

Golfscript-154

Las nuevas líneas son significativas. Si usted no puede quitar la nueva línea final obtendrá un número extra impreso en la parte inferior! Hay una PESTAÑA entre - y 0

" "4*:s%{~}%0+: $):
;0=:g;{2,{:r;s {[
-   0
-]$(:b\(:t\;=!t!0t<1b>*2*+*[{s}[{"__  "}{-2<"/__ /|"}]r={-3<["|   | |""|___|/"["| "b!=]+]r=}]\=~+}%n}%
(:
g<!}do

Golfscript - 163

0`+" ":s%{~}%:A$):y;0=1-:g;{2,{:r;3s*A{[y- 0y-]$(:b\(:t\;=!:j;[{4s*}[{"__  "}{-2<"/__ /|"}]r={-3<["|   | |""|___|/"["| "b!=]+]r=}]0t=0t<1b>*2*+j*=~+}%n}%y(:y g>}do

Golfscript - 165

0`+" ":s%{~}%:A$):y;0=1-:g;{2,{:r;3s*A{[y- 0y-]$(:b\(:t\;=!:j;[
{4s*}.{"__  "
}{-2<"/__ /|"}
{-3<"|   | |"}
{-3<"|___|/"["| "b!=]+}]0t=2*0t<1b>*4*+r+j*=~+}%n}%y(:y g>}do
 5
Author: gnibbler,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-27 18:14:32

C, 287 caracteres

#define F(r)for(r=0;r<98;r++)
#define C(y,s)for(k=0;s[k];k++)b[49-i][w+k+y]=s[k];i++;
char k,i,j,w,t,b[98][99];main(c,v)char**v;{F(i)F(j)b[i][j]=32;
for(j=0;j<c;j++){i=2*atoi(v[j]);t=0;if(i>0)t=i,i=0;for(;i<t;i-=2){
C(0,"|___|/")C(0,"|   | |")C(1,"/__ /|")C(3,"__")}w+=4;}F(i)puts(b[i]);}

(este número de caracteres excluye dos nuevas líneas)

Esto se ejecuta como un programa de línea de comandos, como

./ cubos 1 2 3 4 5 0 1 3 2 -1 -10

Puedes intentar ejecutarlo aquí: http://codepad.org/tu4HDqSy (Esta versión está alterada porque codepad.org no permite argumentos de línea de comandos.)

Un consejo práctico para no jugar al golf es ejecutarlo a través de cpp y luego indent:

char                k        , i, j, w, t, b[98][99];
main(c, v)
    char          **v;
{
    for (i = 0; i < 98; i++)
        for (j = 0; j < 98; j++)
            b[i][j] = 32;
    for (j = 0; j < c; j++) {
        i = 2 * atoi(v[j]);
        t = 0;
        if (i > 0)
            t = i, i = 0;
        for (; i < t; i -= 2) {
            for (k = 0; "|___|/"[k]; k++)
                b[49 - i][w + k + 0] = "|___|/"[k];
            i++;
            for (k = 0; "|   | |"[k]; k++)
                b[49 - i][w + k + 0] = "|   | |"[k];
            i++;
            for (k = 0; "/__ /|"[k]; k++)
                b[49 - i][w + k + 1] = "/__ /|"[k];
            i++;
            for (k = 0; "__"[k]; k++)
                b[49 - i][w + k + 3] = "__"[k];
            i++;
        } w += 4;
    } for (i = 0; i < 98; i++)
        puts(b[i]);
}
 4
Author: 16 revsuser181548,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-24 01:36:17

Python (2.6), 1092 905 623 501 478 345 --> 318 caracteres

Todos los comentarios son bienvenidos!

r=range;p="  __","/__ /|","|   | |","|___|/"
l=map(int,raw_input().split())+[0];d=max(l)
g=[[" "]*(len(l)+1)*4 for i in r(d-min(l)+1)*2]
for i,e in enumerate(l):
 for x,y in sorted([(i*4,(d-e+y-(0,1)[e<0])*2)for y in r(0,e,(1,-1)[e<0])])[::-1]:
  for i in r(4):g[y+i][(x,x+1)[i<2]:x+6]=p[i]
for k in g:print ''.join(k)
 3
Author: ChristopheD,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-25 09:36:57

627 bytes de VB.NET 9 (sin contar las nuevas líneas)

Dim a As New List(Of Int32)
Dim b=InputBox("").Split(" ".ToCharArray)
For Each d In b
a.Add(Int32.Parse(d))
Next
Dim e=New String(){"|___|/","|   | |","/__ /|","__"}
Dim f=a.Min
Dim g=a.Max
Dim h=a.Count
Dim i As New List(Of String)
Dim j=(If(g>0,g,0)+If(f<0,-f,0))*2+1
For d=0To j
i.Add(Space(h*6))
Next
For d=f To g
If (d<>0) Then
For k=0To 3
Dim l=i(j)
Dim m=0
While m<h
If (d<0And a(m)<=d)Or(d>0And a(m)>=d) Then
Dim n=m*4+If(k>1,(k-2)*2+1,0)
l=l.Substring(0,n)&e(k)&l.Substring(n+e(k).Length)
i(j)=l
endif
m+=1
End While
j-=1
Next
j+=2
EndIf
Next
For Each d In i
Console.WriteLine(d)
Next
 2
Author: Anax,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-23 13:40:10

313 bytes de Ruby

c=gets.split.map{|n|n.to_i}+[0];l=[" "*(c.length*5)]*((c.max-c.min)*2+2)
c.each_index{|i|h=c[i];h==0&&next
(h<0?(h...0):(0...h)).to_a.each{|b|y=c.max*2+1-b*2;x=i*4;s=(x+7)..-1
4.times{|a|l[y-a]=l[y-a][0,x+[0,0,1,3][a]]+['|___|/','|   | |','/__ /|','__'
][a]+(l[y-a][[(x+6)..-1,s,s,s][a]]||'')}}};l.each{|e|puts e}

(Hay una nueva línea que no cuenta, solo está allí porque de lo contrario habría una línea muy larga allí.)

Utilicé el método obvio de hacer una matriz 2D de caracteres y pegar en los cubos de uno en uno, de abajo a arriba y de izquierda a derecha.

 1
Author: Jeremy Ruten,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-23 05:29:20

Lua, 453 caracteres

s=io.read("*l")x={}for v in s:gmatch("-?%d+")do x[#x+1]=tonumber(v)end m=math
u=unpack s=string c={s.byte("   __   /__ /||###|#||___|/ ",1,28)}t=m.max(0,u(x))-1
b=m.min(0,u(x))l=#x*4+3 a={}for n=b,t do for p,v in ipairs(x)do y=n<0 and v<=n
or n>=0 and v>n for i=1,4 do e=(t-n)*2+i a[e]=a[e]or{}for j=1,7 do
d=c[(i-1)*7+j]f=(p-1)*4+j a[e][f]=y and d~=32 and d or a[e][f] or 32 end
end end end for i,v in ipairs(a)do print((s.char(u(v)):gsub("#"," ")))end
 1
Author: gwell,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-23 17:40:08

PHP - 447 398

Sé que no es tan corto como los otros aquí, pero estoy contento con él;)

<?$g=$argv;unset($g[0]);$c=array('|___|/',' '=>'|   | |','/__ 
/|',3=>'__');$x=max(max($g),0);$m=$i=min(min($g),0);$row=$y=0;
while($x>=$i){$n=$row++*2;foreach ($c as $w=>$p){
$L[]=str_pad('',count($g)*4," ");$t='';$y=0;foreach ($g as $h)
{if((($h>=$i&&$i>0)||($h<$i&&$i<=0)))$L[$n]=substr_replace($L[$n],$p,4*$y+$w,
strlen($p));$y++;}$n++;}$i++;}array_splice($L,$n);krsort($L);
print implode("\n",$L);?>

Entrada / salida

   C:\development\code-golf>php cubes1.php 1 2 1 -5 -5 4 3 3
                       __
                     /__ /|
                    |   | |__  __
                    |___|/__ /__ /|
       __           |   |   |   | |
     /__ /|         |___|___|___|/|
   _|   | |__       |   |   |   | |
 /__|___|/__ /|     |___|___|___|/|
|   |   |   | |__  _|   |   |   | |
|___|___|___|/__ /__|___|___|___|/
            |   |   | |
            |___|___|/|
            |   |   | |
            |___|___|/|
            |   |   | |
            |___|___|/|
            |   |   | |
            |___|___|/|
            |   |   | |
            |___|___|/
 1
Author: ChronoFish,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-10-30 01:39:02