66
\$\begingroup\$

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 its 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 in bytes 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.
\$\endgroup\$
10

13 Answers 13

65
\$\begingroup\$

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()
\$\endgroup\$
7
  • 11
    \$\begingroup\$ 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. ;) \$\endgroup\$
    – Doorknob
    Jul 19, 2014 at 23:38
  • 2
    \$\begingroup\$ @Doorknob Thanks. I'll put the image in - I just wasn't sure if an animated GIF would be too annoying. \$\endgroup\$
    – grc
    Jul 20, 2014 at 2:57
  • 26
    \$\begingroup\$ @grc annoying? are you sure you didn't mean AWESOME? \$\endgroup\$
    – nderscore
    Jul 20, 2014 at 5:22
  • 5
    \$\begingroup\$ There's nothing better than an ASCII art gif. +1! \$\endgroup\$ Jul 20, 2014 at 17:44
  • 5
    \$\begingroup\$ Send it to Homebrew! sl 2.0 \$\endgroup\$
    – Kroltan
    Jul 20, 2014 at 21:05
23
\$\begingroup\$

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.

\$\endgroup\$
8
\$\begingroup\$

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

\$\endgroup\$
9
  • \$\begingroup\$ 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) \$\endgroup\$
    – seequ
    Jul 19, 2014 at 10:45
  • \$\begingroup\$ 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 \$\endgroup\$
    – seequ
    Jul 19, 2014 at 11:03
  • 1
    \$\begingroup\$ I offered an edit with some improvements. \$\endgroup\$
    – seequ
    Jul 19, 2014 at 11:13
  • 1
    \$\begingroup\$ 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]) \$\endgroup\$
    – seequ
    Jul 19, 2014 at 16:22
  • \$\begingroup\$ @TheRare Incorporated your second(!) improvement! Thy! \$\endgroup\$ Jul 19, 2014 at 16:38
7
\$\begingroup\$

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!

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

Java 10, 637 617 600 595 593 592 chars

interface T{static void main(String[]u){String g=" ",n=g+g,m=n+g,s=m+m,h=s+s,q=h+m,o=" O-O",w=o+s+o+n,y="=",d=y+y+y,p="_____",b=d+d,e=b+b,f=n+n,t=e+d,c="|",l=g+c,z=l+l+l,v="|-|-|",k=" []",x=k+k,r=k+l,a[]={h+"__"+n,b+s+"\\/"+n,c+r+b+d+g,c+h+n+")",t+y,o+"-O"+n+o+"-O \\\\",q,q,t,c+x+x+l,t,w,q,q,t,v+g+l+n+v,t,w,q,q,g+p+"---"+p+g,"("+h+" )",t,w,q,q,p+p+p,"\\"+z+z+" /",t,w,q,q,q,q,t,w,h+g,f+d+y+y+f,d+y+c+m+c+d+y,c+k+f+r,e+y,o+f+o+n,n,n,n,n,"--",g};var O=System.out;for(int i=-1,j;i++<5;O.println())for(j=u[1].length();j-->0;O.print(a["EPBTHFC".indexOf(u[1].charAt(j))*6+i]+(j>0?a[42+i]:"")));}}

Try it online!

Readable:

interface T{
    static void main(String[]u){
        // constants - carriages' parts, a[] - array of carriages
        String g=" ",n=g+g,m=n+g,s=m+m,h=s+s,q=h+m,o=" O-O",w=o+s+o+n,y="=",d=
                y+y+y,p="_____",b=d+d,e=b+b,f=n+n,t=e+d,c="|",l=g+c,z=l+l+l,v=
                "|-|-|",k=" []",x=k+k,r=k+l,a[]={h+"__"+n,b+s+"\\/"+n,c+r+b+d+
                g,c+h+n+")",t+y,o+"-O"+n+o+"-O \\\\",q,q,t,c+x+x+l,t,w,q,q,t,v
                +g+l+n+v,t,w,q,q,g+p+"---"+p+g,"("+h+" )",t,w,q,q,p+p+p,"\\"+z
                +z+" /",t,w,q,q,q,q,t,w,h+g,f+d+y+y+f,d+y+c+m+c+d+y,c+k+f+r,e+
                y,o+f+o+n,n,n,n,n,"--",g};
        // output ASCII train
        var O=System.out;
        for(int i=-1,j;i++<5;O.println())
            for(j=u[1].length();j-->0;O.print(
                    a["EPBTHFC".indexOf(u[1].charAt(j))*6+i]+(j>0?a[42+i]:"")));
    }
}

Train carriages. The lower line of each carriage is one character longer because of engine but the lower line of couplings is one character shorter. Double backslashes are escaped characters, they are interpreted as a single backslash:

String a[] = {
        // 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  ",
        // Car coupling
        "  ",
        "  ",
        "  ",
        "  ",
        "--",
        " "};

Train EPBTHFC:

                                                                                                                __  
    =====                                                                                           ======      \/  
====|   |====                   _______________   _____---_____   ===============  ===============  | [] |========= 
| []     [] |                   \ | | | | | | /  (             )  |-|-|  |  |-|-|  | [] [] [] [] |  |              )
=============--===============--===============--===============--===============--===============--================
 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 \\
\$\endgroup\$
0
3
\$\begingroup\$

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;
}
\$\endgroup\$
3
\$\begingroup\$

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";
\$\endgroup\$
3
\$\begingroup\$

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);
    }
}
\$\endgroup\$
1
2
\$\begingroup\$

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.

\$\endgroup\$
1
  • \$\begingroup\$ 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]....) \$\endgroup\$ Jul 22, 2014 at 0:49
2
\$\begingroup\$

GNU sed, 491 bytes

s/./& #/g
s:E:0S__s%1esss\\/s%2|bpef %3|Ss)%4E=@5 o-Os o-O \\\\:g
s/P/zE%3|bbbbp%4E@5ut/g
s/B/zE%3|-|-|s|s|-|-|%4E@5ut/g
s/T/z l---l %3(S )%4E@5ut/g
s:H:zlll%3\\pppppp /%4E@5ut:g
s/F/zSs %3Ss %4E@5ut/g
s/C/0S %1ssf==ss%2f=|spf=%3|bssbp%4ee=@5 ts t/g
s/z/0Ss %1Ss %2/g
s/%/s%/g
s/@/--%/g
s/u/ tss /g
s/t/os/g
s/S/ssssss/g
s/s/  /g
s/E/eef/g
s/e/ff/g
s/f/===/g
s/b/ []/g
s/p/ |/g
s/o/O-O/g
s/l/_____/g
s/^/0123456;/
:
s/([0-6])(.*;)\1([^%#]+)[%#](.*)/\1\3!\2\4/
t
s/(--!)?[1-6]/\n/g
s/[0!;]//g

Try it online!

Explanation

This is basically a super naïve custom compression scheme. The first line appends to each letter in the input a space and #, to mark the end of each part:

s/./& #/g

The next 7 lines replace each letter with a compressed representation of the corresponding ASCII image:

s:E:0S__s%1esss\\/s%2|bpef %3|Ss)%4E=@5 o-Os o-O \\\\:g
s/P/zE%3|bbbbp%4E@5ut/g
s/B/zE%3|-|-|s|s|-|-|%4E@5ut/g
s/T/z l---l %3(S )%4E@5ut/g
s:H:zlll%3\\pppppp /%4E@5ut:g
s/F/zSs %3Ss %4E@5ut/g
s/C/0S %1ssf==ss%2f=|spf=%3|bssbp%4ee=@5 ts t/g

The next 14 lines do the "decompression". For example, an S decompresses to six ses, and an s decompresses to two spaces, so S becomes 12 spaces.

s/z/0Ss %1Ss %2/g
s/%/s%/g
s/@/--%/g
s/u/ tss /g
s/t/os/g
s/S/ssssss/g
s/s/  /g
s/E/eef/g
s/e/ff/g
s/f/===/g
s/b/ []/g
s/p/ |/g
s/o/O-O/g
s/l/_____/g

Decompressed, the lines of each car are preceded by a line number, and each car is terminated by #. The rest of the code prepends 0123456; (the line numbers and delimiter) to the pattern space and then, in a loop, replaces each digit with the corresponding line of each car.

s/^/0123456;/
:
  s/([0-6])(.*;)\1([^%#]+)[%#](.*)/\1\3!\2\4/
  t

Finally, it cuts the pattern space into lines by splitting on digits and cleans up extraneous characters:

s/(--!)?[1-6]/\n/g
s/[0!;]//g

There's a lot of room for improvement here. I wasn't rigorous at all about finding an optimal set of compressions, and using a lookup table instead of 14 separate s///gs would be an easy win. I may or may not noodle with this some more.

\$\endgroup\$
2
\$\begingroup\$

C (gcc), 501 499 490 489 484 483 481 bytes

-2 -9 -1 -5 -1 -2 bytes thanks to ceilingcat.

#define A": O-Og O-O:o=:"
char*p,*q,s[80];i=6,k,n;main(j,a)char**a;{for(;i--;puts(q))for(k=strlen(a[1]);k--;*q=0,printf("%-*s%s",j?j^6?15:13:16,s,k?i^1?!j*!i+"  ":"--":q)){j=index(p="EPBTHFC",a[1][k])-p;for(n=j*6+i,p=" O-O-Oc O-O-O \\\\:p=:|n ):| [] |i=:f=f \\/:l __"A"| [] [] [] [] |:o=::"A"|-|-|  |  |-|-|:o=::"A"(m ): e_c-e_::"A"\\ | | | | | | /:o_::"A":::: O-Oe O-O:m=:| []e [] |:d=|c |d=:d e=::";n--;)for(;*p++-58;);for(q=s;*p^58;q+=n)memset(q,*p++,n=islower(*p)?*p++-96:1);}}

Try it online!

\$\endgroup\$
0
1
\$\begingroup\$

Python 3, 529 bytes

a=['']*6
T,R="EPBTHFC",{'S':' '*3,'E':'='*3,'W':'[] ','U':'_'*5,'P':'| ','H':'O-O'}
A=('SSSS__  ',)+('S'*5,)*5+('SSSS ',),('EESS\/  ',)+('S'*5,)*5+('S E==S ',),('PW|EEE ','E'*5,'E'*5,' U---U ','U'*3,'S'*5,'E=|S|E='),('P SSSS)','PWWWW|','|-|-P P |-|-|','(SSSS )','\ PPPPPP/','S'*5,'PWS W|'),('E'*5+'=--',)+('E'*5+'--',)*5+('EEEE=--',),(' H-OSH-O \\\\ ',)+(' HSS HS',)*5+(' HS  HS',)
for C in input():
 for I in range(6):
  a[I]=A[I][T.index(C)]+'  '*(I<4)+a[I]
  for k in R:a[I]=a[I].replace(k,R[k])
a[4]=a[4][:-2]
[*map(print,a)]

Try it online!

Figured I would post it because it does not use any compression, unlike most of the other answers here.

\$\endgroup\$
1
\$\begingroup\$

Javascript (Node.js), 1216 bytes

var c={E:['            __  ','======      \\/  ','| [] |========= ','|              )','================',' O-O-O   O-O-O \\',],P:['               ','               ','===============','| [] [] [] [] |','===============',' O-O       O-O'],B:['               ','               ','===============','|-|-|  |  |-|-|','===============',' O-O       O-O'],T:['               ','               ',' _____---_____ ','(             )','===============',' O-O       O-O '],H:['               ','               ','_______________','\\ | | | | | | /','===============',' O-O       O-O '],F:['               ','               ','               ','               ','===============',' O-O       O-O '],C:['             ','    =====    ','====|   |====','| []     [] |','=============',' O-O     O-O ']};var o=[];for(var w=0;w<process.argv[2].length;w++){o.push(process.argv[2].charAt(w));}var arg=o.reverse().join('');var s=['  ','  ','  ','  ','--','  '];for(var x=0;x<6;x++){var k=[];for(var y=0;y<arg.length;y++){if(!['B','C','E','F','H','P','T'].includes(arg.charAt(y))){y++;}k.push(c[arg.charAt(y)][x]);}var v='';for(var q in k){v+=k[q]; if(arg.charAt(q)=='E'&&x== 5){v+='\\ ';}else if(q<k.length-1){v+=s[x];}}console.log(v);}

Uncompressed

var c = { // define cars
    E: [
        '            __  ',
        '======      \\/  ',
        '| [] |========= ',
        '|              )',
        '================',
        ' O-O-O   O-O-O \\',
    ],
    P: [
        '               ',
        '               ',
        '===============',
        '| [] [] [] [] |',
        '===============',
        ' O-O       O-O'
    ],
    B: [
        '               ',
        '               ',
        '===============',
        '|-|-|  |  |-|-|',
        '===============',
        ' O-O       O-O'
    ],
    T: [
        '               ',
        '               ',
        ' _____---_____ ',
        '(             )',
        '===============',
        ' O-O       O-O '
    ],
    H: [
        '               ',
        '               ',
        '_______________',
        '\\ | | | | | | /',
        '===============',
        ' O-O       O-O '
    ],
    F: [
        '               ',
        '               ',
        '               ',
        '               ',
        '===============',
        ' O-O       O-O '
    ],
    C: [
        '             ',
        '    =====    ',
        '====|   |====',
        '| []     [] |',
        '=============',
        ' O-O     O-O '
    ]
};
//reverse string - why is there no builtin for this?
var o = [];
for(var w = 0; w < process.argv[2].length; w++){
    o.push(process.argv[2].charAt(w));
}
var arg = o.reverse().join('');
//train car seperators
var s = ['  ','  ','  ','  ','--','  '];
// for each row
for(var x = 0; x < 6; x++){ 
    var k = []; //empty array for each car string
    for(var y = 0; y < arg.length; y++){
        //ignore non-included characters
        if(!['B','C','E','F','H','P','T'].includes(arg.charAt(y))){
            y++;
        }
        // add car
        k.push(c[arg.charAt(y)][x]);
    }
    var v = '';
    for(var q in k){
        v += k[q]; // append car
        if(arg.charAt(q) == 'E' && x == 5){ // to deal with annoying engine thing, see below
            v += '\\ ';
        } else if(q < k.length - 1){ // if not last car
            v += s[x]; // append separator
        }
    }
    console.log(v); //output
}

The annoying thing about this challenge is the coupling near the engine. All the other cars are just one solid block, but the \ on the front takes up the same vertical space as the coupling. See here:

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

Note: Enter via the CLI e.g. node asciitrain.js EBCEFH. This was badly golfed.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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