Take the 2-minute tour ×
Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Consider these seven ASCII train cars.

Engine (E)

            __
======      \/
| [] |=========
|              )
================
 O-O-O   O-O-O \\

Passenger car (P)

===============
| [] [] [] [] |
===============
 O-O       O-O

Boxcar (B)

===============
|-|-|  |  |-|-|
===============
 O-O       O-O

Tanker (T)

 _____---_____
(             )
===============
 O-O       O-O

Hopper (H)

_______________
\ | | | | | | /
===============
 O-O       O-O

Flatbed (F)

===============
 O-O       O-O

Caboose (C)

    =====
====|   |====
| []     [] |
=============
 O-O     O-O

Write a program that when given a sequence of the characters EPBTHFC, outputs it's ASCII train representation, using -- for the car couplings. The leftmost input characters become the rightmost train cars. The train is always facing right.

For example, an input of EEHTBPFC should produce

                                                                                                                __                __
    =====                                                                                           ======      \/    ======      \/
====|   |====                   ===============  ===============   _____---_____   _______________  | [] |=========   | [] |=========
| []     [] |                   | [] [] [] [] |  |-|-|  |  |-|-|  (             )  \ | | | | | | /  |              )  |              )
=============--===============--===============--===============--===============--===============--================--================
 O-O     O-O    O-O       O-O    O-O       O-O    O-O       O-O    O-O       O-O    O-O       O-O    O-O-O   O-O-O \\  O-O-O   O-O-O \\

Details

  • This is code golf; the shortest program wins.
  • Any sequence of one or more of the letters EPBTHFC is valid input.
  • Your program must be able to output all 7 car types exactly as they appear above.
  • Take input from the command line or directly from the user (e.g. message box). Output to stdout. (Quotes around input are fine.)
  • The height of the output should either be 6 or the maximum height needed for the train cars being drawn.
  • Do not put couplings (--) at the front of the first car or the back of the last car.
share|improve this question
1  
    
Will there always be an E at the front and could there be an E somewhere in the middle? –  Martin Büttner Jul 19 at 9:31
1  
"the shortest program wins." => do we count bytes or characters? –  xem Jul 19 at 11:08
1  
@xem, bytes unless otherwise specified –  Peter Taylor Jul 19 at 12:57
1  
Another related question: codegolf.stackexchange.com/q/4690/9498 –  Quincunx Jul 23 at 23:45

9 Answers 9

up vote 20 down vote accepted

Perl, 265 bytes

Since this entry contains bytes that do not correspond to printable ASCII characters, it cannot be copy-pasted here directly. Instead, I am providing it as a hex dump. Users on Unix-ish systems can reconstruct the script by feeding the following hex dump to the xxd -r command:

0000000: 7573 6520 436f 6d70 7265 7373 275a 6c69  use Compress'Zli
0000010: 623b 6576 616c 2075 6e63 6f6d 7072 6573  b;eval uncompres
0000020: 7320 2778 daad 9241 6b83 3014 c7ef f914  s 'x...Ak.0.....
0000030: ef10 6add f67c 5ed6 8b06 c646 476f dda1  ..j..|^....FGo..
0000040: 3723 c183 1d85 8212 c740 087e f625 a6a3  7#.......@.~.%..
0000050: b1f6 24fd 3de1 3d7f e8fb e790 b74a 74ed  ..$.=.=......Jt.
0000060: f9f4 c3e9 25cf a328 6310 a094 6b4c 8c78  ....%..(c...kL.x
0000070: 2569 5406 8a12 8cf8 c7ab 09b1 ff71 0222  %iT..........q."
0000080: 833d da02 b874 2981 c10d 3333 df74 39c1  .=...t)...33.t9.
0000090: f531 d6dc 0f03 8f9f 9666 a12d 7021 6e7a  .1.......f.-p!nz
00000a0: 6416 2807 228e dd99 3584 c40f cc52 53ac  d.(."...5....RS.
00000b0: 9160 82a2 4559 0bcd a22c ff2e 1cc1 0e63  .`..EY...,.....c
00000c0: 9d09 6f85 25b8 13b3 8470 3fe3 5c27 a1eb  ..o.%....p?.\'..
00000d0: df5a 7735 b44d 2b86 9eb6 5fef 87dd e707  .Zw5.M+..._.....
00000e0: a5b8 219d b1ae eaed 3743 4709 f1aa d83c  ..!.....7CG....<
00000f0: f1d5 3357 257d 6be7 1039 9186 63a3 214d  ..3W%}k..9..c.!M
0000100: 9257 f607 1251 a1e7 27                   .W...Q..'

The script uses the Perl 5.10 say feature, and so needs to be run with perl -M5.010. It takes a single command line argument consisting of the letters EPBTHFC and outputs the corresponding train car arrangement. For example, the input FEH produces the following output:

                             __                     
                 ======      \/                     
_______________  | [] |=========                    
\ | | | | | | /  |              )                   
===============--================--===============
 O-O       O-O    O-O-O   O-O-O \\  O-O       O-O   

The readable code at the beginning of the script simply decompressed the zlib-compressed string containing the body of the script and evals it. The decompressed code, in turn, looks like this:

@a=split$/,<<'';
            __    
======      \/    
| [] |=========   
|              )  
================--
 O-O-O   O-O-O \\ 


===============  
| [] [] [] [] |  
===============--
 O-O       O-O   


===============  
|-|-|  |  |-|-|  
===============--
 O-O       O-O   


 _____---_____   
(             )  
===============--
 O-O       O-O   


_______________  
\ | | | | | | /  
===============--
 O-O       O-O   




===============--
 O-O       O-O   

    =====      
====|   |====  
| []     [] |  
=============--
 O-O     O-O   

$i=reverse pop=~y/EPBTHFC/0-6/r;
say$i=~s/./$a[6*$&+$_]/gr=~s/--$//r for 0..5

Note that all the train cars have their lines padded with spaces to a uniform length, and include the coupling (which is stripped from the rightmost car by the output loop). The DEFLATE compression used by zlib is very good at compressing such repetitive data, so there's no need to try and compress it by hand.

Note that this is a quick first attempt. I'm sure it would be possible to shave several bytes off the length by playing with variations such as reordering the train cars in the source.

share|improve this answer

Python, 464

from curses import*
E,P,B,T,H,F,C='eJyNkM0NgDAIhe9MwVEPpBN0AxMHsKaLdHgfpVr7E+NHUyCQR4C5EiP5jKXBUeLj5ORvkDes5DtEiHeBoWo+hI36NtN9XurrRaVMQTSTEBizPo3+SGBBICLZ0/K9y0whtlDA/Gruj8SwyaRJA9tSPz16qmdTxqO9VeAvC5VloQ=='.decode('base64').decode('zlib').split('L')
i=[s.split('\n')for s in map(eval,raw_input()[::-1])]
h=max(sum(map(bool,s))for s in i)
w=initscr()
x=0
for t in i:[w.addstr(y,x,t[y+6-h])for y in range(h)];x+=len(t[-2])
w.addstr(h-2,x-2,'  ')
w.getch()
endwin()

I went for an approach using curses. It can't really compete, but I had some fun with it (~630 bytes):

train

from curses import*
E,P,B,T,H,F,C='eJyFkMENwCAIRe9M8Y/tgTiBGzTpALVxEYcvSFqiNO2DCAb8BgCnVsodu5ZEDceJlm/kPrBSniDsLCY1i6VsNDeZ6uMt1GEKMJU3ARYD1DX7F5DRBGbukZbvKeL7OkJF/nZL/wJxhrlFE6vooYtuviwlrso1JF745GMr'.decode('base64').decode('zlib').split('L')
i=[s.split('\n')for s in map(eval,raw_input()[::-1])]
h=max(sum(map(bool,s))for s in i)
w=initscr()
m=w.getmaxyx()[1]
for o in range(-sum(2+len(t[-2])for t in i),m):
 x=o
 for t in i:
  if m>x>o:w.addnstr(h-2,max(x,0),'--'[max(0,-x):],m-x);x+=2
  [w.addnstr(y,max(x,0),t[y+6-h][max(0,-x):],m-x)for y in range(h)if x<m];x+=len(t[-2])
 w.move(h,0);w.refresh();w.clear();napms(90)
endwin()
share|improve this answer
8  
Wow, that animation is great! (+1) Animated GIFs work in posts, so you could edit the actual image in instead of a link, which would make your solution look fancier. ;) –  Doorknob Jul 19 at 23:38
    
@Doorknob Thanks. I'll put the image in - I just wasn't sure if an animated GIF would be too annoying. –  grc Jul 20 at 2:57
16  
@grc annoying? are you sure you didn't mean AWESOME? –  nderscore Jul 20 at 5:22
3  
There's nothing better than an ASCII art gif. +1! –  Chris Cirefice Jul 20 at 17:44
2  
Send it to Homebrew! sl 2.0 –  Kroltan Jul 20 at 21:05

Python (582 488 476 450 Chars)

import sys
A=sys.argv[1]
h=0
c='eJyVkrEKAzEIhnef4h97g9x+kOVKS7d2uK0peZE8fNXQS3NCpb+BREU/YnIhfKkUgJKpBfIsgYrnCzV9pIFBE6WDCHcWk1zbMy0PGovg/GMPw+6rujwaAY0CWtb/ESwG6NJTjNhChMxQxMy2g06/R+URtxBRRlGWC3SbY8Q1vkXgh4gz+Qb7v7Jy/US1P7TKP3NvbG3fy/V/Cw=='.decode('base64').decode('zlib').split(':')
C={}
for x in c:X=x.split('\n');C[X[0]]=X[1:-1]
for c in A:h=max(h,1+('F..CE'.find(c)+1or 3))
for y in range(6-h,6):print(' -'[y==4]*2).join(C[c][y]for c in A[::-1])

The ascii-salad is a base64 encoded zlib-compressed string containing the figures...

share|improve this answer
    
1. string.decode('base64') 2. j=lambda y:y==4and'--'or' ' 3. 1-space indents 4. for c in A[::-1]:i.append(C[c][y]) 5. f.append(j(y).join(i) –  Sieg Jul 19 at 10:45
    
Also, last 6 lines could be for l in((y==4and'--'or' ').join(C[c][y]for c in A[::-1])for y in range(6-h,6)):print l –  Sieg Jul 19 at 11:03
1  
I offered an edit with some improvements. –  Sieg Jul 19 at 11:13
    
@TheRare Thank you! :-) –  max.haredoom Jul 19 at 16:16
1  
Come to think of it, the last line could be for y in range(6-h,6):print(y==4and'--'or' ').join(C[c][y]for c in A[::-1]) –  Sieg Jul 19 at 16:22

Python, 402 369

import sys
for n in range(6):
 l= sys.argv[1][::-1]
 for x,y in zip("EPBTHFC",range(0,42,6)):
  l=l.replace(x,'eJytktsNgCAMRVfpp340TMAHEziAGBZhePvgLYmGeGosXqQXSAEqIfDbWUElb0SKcF4QbUaljr0srCA6OJCC5jV7cDAyUYY6eQPlic9/kleqoKNVL6QANkmj37zohglElMzK9naJy16hhxRPR6ph/jzXB2XBS76bZpQa3Hex7Qpm1hOtg+Yb0a6PSA=='.decode('base64').decode('zlib').split('A')[y+n]).strip('-')
 print l

Thanks you for the improvements, ugoren!

share|improve this answer
    
Thank you for formatting my code! I'm kinda new to this and honestly I do not know what I'm doing. –  Elveone Jul 22 at 11:00
1  
Save some chars: range(6), for x,y in zip("EPBTHFC",range(0,42,6)): –  ugoren Jul 22 at 11:37

Java (583 characters)

With basic homemade compression - not sure it's so efficient though :-) The train string (e.g. EEHTBPFC) must be passed as parameter.

class C{public static void main(String[]a){String s="",y="thAthA",x=" *!*h*!* A",q="vjA",r=q+x+y;String[]m=("hP78A^\\#$8A% &' %j.,A%hh) Ajj.A *!*!*8*!*!* /A"+y+q+"% &' &' &' &' %A"+r+q+"%!%!%,%,%!%!%A"+r+" [9[ A(tP)A"+r+"ss+A# % % % % % % $A"+r+y+q+x+"tPADRDAF%8%FA% &'P&' %AvRA *!*P*!* ").split("A");for(int l,z,i,j=0;j<6;j++){for(i=a[0].length()-1;i>=0;i--){z=a[0].charAt(i);r=m["EPBTHFC".indexOf(z)*6+j];for(int c:r.toCharArray()){c-=32;for(l=0;l<=c/12;l++)s+=" -=\\/|[]()O_".charAt(c%12);}if(i>0)for(l=0;l<(z=='E'&&j!=4?1:2);l++)s+=j==4?"-":" ";}s+="\n";}System.out.println(s);}}

Unfolded:

class C{
    public static void main(String[]a){
        String s="",y="thAthA",x=" *!*h*!* A",q="vjA",r=q+x+y;
        String[]m=("hP78A^\\#$8A% &' %j.,A%hh) Ajj.A *!*!*8*!*!* /A"+y+q+"% &' &' &' &' %A"+r+q+"%!%!%,%,%!%!%A"+r+" [9[ A(tP)A"+r+"ss+A# % % % % % % $A"+r+y+q+x+"tPADRDAF%8%FA% &'P&' %AvRA *!*P*!* ").split("A");
        for(int l,z,i,j=0;j<6;j++){
            for(i=a[0].length()-1;i>=0;i--){
                z=a[0].charAt(i);
                r=m["EPBTHFC".indexOf(z)*6+j];
                for(int c:r.toCharArray()) {
                    c-=32;
                    for(l=0;l<=c/12;l++)
                        s+=" -=\\/|[]()O_".charAt(c%12);
                }
                if(i>0)for(l=0;l<(z=='E'&&j!=4?1:2);l++)s+=j==4?"-":" ";
            }
            s+="\n";
        }
        System.out.println(s);
    }
}
share|improve this answer

C#, 758 664 603 562bytes

Not a great score, 200 or so bytes in the poorly encoded string, and about 80 bytes devoted to decoding it. Frustrating amount of code spent sorting out the coupling on the engine! It now leaves white-space trailing at the front of the train, which is untidy but within the rules, and it also has the dimensions of the data-string hard coded, something I was reluctant to do initially.

using c=System.Console;class P{static void Main(){string d=c.ReadLine(),a="",z=@"99 1_5 4=78 5=5 \/1 3=|2 |3=14 29= 4_2-4_ 14_| [] |8= | []4 [] |14 | [] [] [] [] 1|-|-|1 |1 |-|-|(12 )\ | | | | | | /|13 )103= O-O4 O-O1 O-O6 O-O1 O-O6 O-O1 O-O6 O-O1 O-O6 O-O1 O-O6 O-O1 O-O-O2 O-O-O c";int j=0,e;foreach(var h in z)if(h>47&&h<58)j=j*10+h-48;else for(j++;j>0;j--)a+=h;int[]x={0,13,28,43,58,73,88,104};for(;j<6;j++){z="";foreach(var h in d)z=a.Substring(j*104+x[e="CFPBTHE".IndexOf(h)],x[e+1]-x[e])+(j==4?"--":"  ")+z;c.WriteLine(z.Replace("c ",@"\\").Trim('-'));}}}

Formatted a bit:

using c=System.Console;
class P{static void Main(){
    string d=c.ReadLine(),a="",z=@"99 1_5 4=78 5=5 \/1 3=|2 |3=14 29= 4_2-4_ 14_| [] |8= | []4 [] |14 | [] [] [] [] 1|-|-|1 |1 |-|-|(12 )\ | | | | | | /|13 )103= O-O4 O-O1 O-O6 O-O1 O-O6 O-O1 O-O6 O-O1 O-O6 O-O1 O-O6 O-O1 O-O-O2 O-O-O c";

    int j=0,e;

    foreach(var h in z)
        if(h>47&&h<58)
            j=j*10+h-48;
        else
            for(j++;j>0;j--)
                a+=h;

    int[]x={0,13,28,43,58,73,88,104};

    for(;j<6;j++)
    {
        z="";
        foreach(var h in d)
            z=a.Substring(j*104+x[e="CFPBTHE".IndexOf(h)],x[e+1]-x[e])+(j==4?"--":"  ")+z;
        c.WriteLine(z.Replace("c ",@"\\").Trim('-'));
    }
}}

The string is compressed very simply by replacing repeated character with a string representation of the number of characters followed by the character (minus 1), or just the character if there is only one of them (I wanted to stick with ASCII and avoid doing anything at the sub-char level). Encoder (not included in score):

string compress(string str)
{
    str += (char)0; // too lazy to write a proper loop
    string res = "";

    char prev = str[0];
    int count = 1;

    for (int i = 1; i < str.Length; i++)
    {
        char cur = str[i];
        if (cur != prev)
        {
            if (count != 1)
                res += (count - 1).ToString();
            res += prev;

            prev = cur;
            count = 1;
        }
        else
        {
            count++;
        }
    }

    return res;
}
share|improve this answer

Here is my solution in PHP (v5.4 compatible), 512bytes. Could be shorter, but just made a quick build to try this out.

<?php $m=array_combine(str_split('EPBTHFC'),explode('$',gzinflate(base64_decode('jZDBDYAwCEXvfwoOHvRAnKAzOICYLtLhhVYlrY320RQI5BMgcmJEyJRUViTaD0rhRvOKBaEBtLGa1ooXmdA2FdXnJfQ0rgkW9RRYjcieRQMKupzCzNlj/t6jIxBrIDrdbR1QwH+PRaVkn107+cWM971cxPwJ'))));$t=['','','','','',''];$i=str_split(strrev(strtoupper($argv[1])));foreach($i as $w=>$n){$c=$m[$n];$c=explode("\n",$c);foreach($t as $j=>&$p){$p.=str_pad($c[$j],$n=='E'?18:($n=='C'?15:17),$j==4?'-':' ');if($w==count($i)-1)$p=rtrim($p,' -');}}echo implode("\n",$t)."\n";

This is a spread-out version for easy reading:

<?php
$m=array_combine(
    str_split('EPBTHFC'),
    explode('$',
        gzinflate(
            base64_decode(
                'jZDBDYAwCEXvfwoOHvRAnKAzOICYLtLhhVYlrY320RQI5BMgcmJEyJRUViTaD0rhRvOKBaEBtLGa1ooXmdA2FdXnJfQ0rgkW9RRYjcieRQMKupzCzNlj/t6jIxBrIDrdbR1QwH+PRaVkn107+cWM971cxPwJ'
            )
        )
    )
);
$t=['','','','','',''];
$i=str_split(strrev(strtoupper($argv[1])));
foreach($i as $w=>$n)
{
    $c=$m[$n];
    $c=explode("\n",$c);
    foreach($t as $j=>&$p)
    {
        $p.=str_pad($c[$j],$n=='E'?18:($n=='C'?15:17),$j==4?'-':' ');
        if($w==count($i)-1)$p=rtrim($p,' -');
    }
}
echo implode("\n",$t)."\n";
share|improve this answer

Javascript, >471 bytes

Well crap, already over the best score, and I still haven't gotten to having it print everything in sequence. But I spent an afternoon on this and still wanted to show it.

function c(i){
    var i=i.replace(/f/,"=15r h 7h").match(/(\D)(\d+)?/g),
    s={
        's':'\\',
        'w':' []',
        'b':' |',
        'h':'O-O',
        't':'-|',
        'r':'\n'
    }
    ,
    a=[];
    for(j in i){
        x=/(\D)(\d+)?/g.exec(i[j]),
        a[j]=x[1],
        n=x[2]/1,
        o="";
        while(x[2]&&0<n--)o+=a[j];
        a[j]=o||a[j];
    }
    r=a.join('');
    for(j in s)r=r.replace(RegExp(j,"g"),s[j]);
    return r;
}
E=" 12_2r=6 6s/r|wb=9r| 14)r=16r h-O 3h-O ss",
P="r2=15r|w4brf",
B="r2=15r|t2 b bt2rf",
T="r2 _5-3_5r( 13)rf",
H="r2_15rsb6 /rf",
F="r4f",
C="r 4=5r=4| 3|=4r|w 4wbr=13r h 5h";
console.log(c(C));

Just console.log(c(L)); // L=train car letter and it will print a single car in the console. I know there's a lot of trimming I could do to even just this, but I give up. :P

share|improve this answer
2  
I had to do it: jsfiddle.net/34w2z –  William Barbosa Jul 23 at 17:47
1  
@WilliamBarbosa haha, I'm retarded. I was like, "What magic is this? My code is moving." and searching all over for what you changed in the script to make it scroll... then moved my eyes up to the HTML. Ahh, <marquee> you fiendish devil. Why did they ever deprecate you? –  philtune Jul 23 at 19:12
    
@WilliamBarbosa I believe you have located the one and only legitimate use for this tag. –  Mike Clark 15 hours ago

Python, 491 bytes

import zlib as z,sys,base64 as d
y=eval(z.decompress(d.b64decode('eNqlksEOwiAMhl/lv1WTkd1NdtFovLmDt7HwIOK729LJmJDY6F8SyA/0g6YPOtNhIhQKAaCOhiS1fJ+siGlGHN5Sa6N9vriKLdwcB+/r7D3NHY2fYCRI7dT50kPyiM0zUCKUCiEe/yA6DkCGrKzEu5XIVWc559Iszu5bYdvEq5UYtmLH8/fW6K3Ei/mPP1W+QTxVxCVXbtklk3RnLHtG1OqYkqOU5wsfZZmx')))
w=sys.argv[1][::-1]
x=[""]*6
v=range
u=len(w)
for j in v(6):
 for i in v(u):
  if j==5 and w[i]=='E':k="\\ "
  elif j==4 and i!=u-1:k="--"
  else:k="  "
  x[j]+=y[w[i]][j]+k
for q in x:print q

I like how it came out, even though it won't be a winner.

share|improve this answer
    
You could change if j==5...x[j]+=y[w[i]][j]+k to x[j]+=y[w[i]][j]+('\\ 'if j==5 and w[i]=='E'else'--'if j==4 and i!=u-1 else' ') to save a bit. (Also you can put a tab instead of two spaces in front of x[j]....) –  Calvin's Hobbies Jul 22 at 0:49

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.