title: Draw the Olympic Games logo

text:
# Question
Title: Draw the Olympic Games logo
# Challenge

Draw the Olympic Games logo...

...as character (e.g. ASCII) art!

# Sample Output

```
      * * *               * * *               * * *
  *           *       *           *       *           *
*               *   *               *   *               *
*               * * *               * * *               *
*           *   *   *   *       *   *   *   *           *
  *       *   *       *   *   *   *       *   *       *
      * * *               * * *               * * *
          *               *   *               *
            *           *       *           *
                * * *               * * *

```

Your art doesn't have to look exactly like mine, but it has to represent the Olympic rings well enough that it's recognizable.

# Rules

* The program must write the art to the console.
* Shortest code (in bytes, any language) wins.
* **A solution that prints rings in their respective colors (or a close representation) will be awarded a minus-twenty-point bonus.**

The winner will be chosen on February 23rd at the end of the 2014 Winter Olympics.

---

# Winners

# Answer
## APL (82) (-20 = 62)

Edit: for a change, this program is simple enough that TryAPL will touch it, so you can run it there (just paste the line in).

Not sure if I can claim the 'color' bit, I'm representing them all differently though.

```
2/' ▓█░▓▒'[1+(13↑⍉n)⌈¯13↑⍉32↑¯26↑⌈1.1×11↓n←⍉c,0,2×c,0,2×c←(⍳2/10)∊⌈5+5×1 2∘○¨⍳1e4]

```

The APL console doesn't support color, so I used shaded block characters (assigning any kind of other ASCII art would be as simple as replacing the characters at the beginning of the string.)

They should look like unbroken circles (depending on your font.)

```
      2/' ▓█░▓▒'[1+(13↑⍉n)⌈¯13↑⍉32↑¯26↑⌈1.1×11↓n←⍉c,0,2×c,0,2×c←(⍳2/10)∊⌈5+5×1 2∘○¨⍳1e4]
    ▓▓▓▓▓▓▓▓▓▓▓▓          ████████████          ▓▓▓▓▓▓▓▓▓▓▓▓
  ▓▓            ▓▓      ██            ██      ▓▓            ▓▓
▓▓                ▓▓  ██                ██  ▓▓                ▓▓
▓▓            ░░░░░░░░░░░░          ▒▒▒▒▒▒▒▒▒▒▒▒              ▓▓
▓▓          ░░    ▓▓  ██  ░░      ▒▒    ██  ▓▓  ▒▒            ▓▓
▓▓        ░░      ▓▓  ██    ░░  ▒▒      ██  ▓▓    ▒▒          ▓▓
▓▓        ░░      ▓▓  ██    ░░  ▒▒      ██  ▓▓    ▒▒          ▓▓
▓▓        ░░      ▓▓  ██    ░░  ▒▒      ██  ▓▓    ▒▒          ▓▓
  ▓▓      ░░    ▓▓      ██  ░░  ▒▒    ██      ▓▓  ▒▒        ▓▓
    ▓▓▓▓▓▓░░▓▓▓▓          ██░░██▒▒████          ▓▓▒▒▓▓▓▓▓▓▓▓
          ░░                ░░  ▒▒                ▒▒
            ░░            ░░      ▒▒            ▒▒
              ░░░░░░░░░░░░          ▒▒▒▒▒▒▒▒▒▒▒▒

```

Or:

```
      2/' bByRg'[1+(13↑⍉n)⌈¯13↑⍉32↑¯26↑⌈1.1×11↓n←⍉c,0,2×c,0,2×c←(⍳2/10)∊⌈5+5×1 2∘○¨⍳1e4]
    bbbbbbbbbbbb          BBBBBBBBBBBB          RRRRRRRRRRRR
  bb            bb      BB            BB      RR            RR
bb                bb  BB                BB  RR                RR
bb            yyyyyyyyyyyy          gggggggggggg              RR
bb          yy    bb  BB  yy      gg    BB  RR  gg            RR
bb        yy      bb  BB    yy  gg      BB  RR    gg          RR
bb        yy      bb  BB    yy  gg      BB  RR    gg          RR
bb        yy      bb  BB    yy  gg      BB  RR    gg          RR
  bb      yy    bb      BB  yy  gg    BB      RR  gg        RR
    bbbbbbyybbbb          BByyBBggBBBB          RRggRRRRRRRR
          yy                yy  gg                gg
            yy            yy      gg            gg
              yyyyyyyyyyyy          gggggggggggg

```
> 22 votes

# Answer
## Commodore 64 BASIC

Writing directly in the screen and color memory.

**Output:**

---

Here's how you do this with sprites.
> 164 votes

# Answer
## HTML Fiddle \- 48, 35, 33 characters (Thanks @Dom and @cnst!)

```
OOO<p style="margin:-15px 6px">OO

```

Output:
> 86 votes

# Answer
## BASH in color - 271 - 20 = 251 – With entangled rings ;P

```
o='_4mGA  _0mGA  _1mG\n _4m/A \A _0m/A \\_1mA /A \\\n_4mD_3m---_0mD_2m---_1mD\n _4m\A_3m/_4m/A_0m\\_3m\\A_2m/_0m/A_1m\\_2m\A _1m/\n_4mG_3mD_0m---_2mD_1m---\n_3m   A\A /A _2m\A /_1m\n _3mA G  A_2mG\n';o=${o//D/|A   |};o=${o//A/    };o=${o//G/   ---};printf "${o//_/\\e[3}"

```

Result:

---

### And the *for fun* of it one: 61 - 20 = 41.

```
x='_4mO_3m^_0m0_2m^_1mO\n_3m V _2mV\n';printf "${x//_/\\e[3}"

```

---

LZ77 version:

```
echo H4sIALOY5VIAA12QwRXAIAhD767ghQV8CnYbXYENOnw1YqX1xk8wQGz1UiJKKRFebLX8ARsIs7g0g/djN7CdRAYC7Pf6h+5RVR3foMdTMcqHWlS3jKr5RKO/g25doJdXZ+ii75CseU2zNkGzH6HYCPKhPGmA2Wh3+7mEDHMgb/2cUPYJH2gPhtZxAQAA|base64 -d|zcat

```
> 76 votes

# Answer
# Sinclair BASIC on the ZX Spectrum 48K (261 bytes)

BASIC listing:

Final result:

Program running and code measuring:

BASIC listing in text format:

```
5 INK VAL "7": CLS
10 LET a=VAL "42": LET b=VAL "131": LET c=VAL "40": CIRCLE INK SGN PI;a,b,c: CIRCLE INK PI-PI;a+a+a,b,c: CIRCLE INK VAL "2";VAL "210",b,c
20 LET a=VAL "84": LET b=VAL "87": CIRCLE INK VAL "6";a,b,c: CIRCLE INK VAL "4";a+a,b,c
30 FOR l=PI-PI TO VAL "21": FOR c=PI-PI TO VAL "31": IF ATTR (l,c)<>VAL "63" THEN PRINT INK VAL "8";AT l,c;"*"
40 NEXT c: NEXT l

```

TAP file with the program, suitable for emulators or real machine using DivIDE or DivMMC: http://www.zxprojects.com/images/stories/draw\_the\_olympics\_flag.tap
> 76 votes

# Answer
So I didn't actually read properly, it's ASCII-art, so I guess this is invalid. Oops!

---

## HTML 121 (141 - 20)

```
<pre style=line-height:3px;letter-spacing:-3px><font color=#06f>O <font color=#000>O <font color=red>O
 <font color=#fa0>O <font color=#193>O

```

In Chrome:

## PHP 103 (123 - 20)

```
<pre style=line-height:3px;letter-spacing:-3px><?=($f='<font color=')."#06f>O ${f}#000>O ${f}red>O
 ${f}#fa0>O ${f}#193>O";

```
> 44 votes

# Answer
# Ruby: 198 characters - 20 = 178

```
a=[*0..9].map{[' ']*35}
d=->c,x,y=0{11.times{|i|7.times{|j|a[y+j][x+i]="^[[3#{c}m#^[[0m"if[248,774,1025,1025,1025,774,248][j]&1<<i!=0}}}
d[4,0]
d[0,12]
d[1,24]
d[3,6,3]
d[2,18,3]
$><<a.map{|r|r*''}*$/

```

(Note that `^[` are single characters.)

Sample run:
> 38 votes

# Answer
# Mathematica - 185

```
c[x_, y_] :=
 Table[Boole[Abs[(i - x)^2 + (j - y)^2 - 16] < 4], {i, 0, 15}, {j, 0,
   30}]
MatrixForm@
 Replace[Blue c[5, 4] + Black c[5, 14] + Red c[5, 24] +
   Yellow c[9, 9] + Green c[9, 19], {0 -> "",
   c_ + _ | c_ :> Style["*", c]}, {2}]

```

Here is the ouput

Another version, based on rasterization of vector graphics

```
MatrixForm@
 Replace[ImageData@
   Rasterize[
    Graphics[{Blue, Circle[{4, 9}, 4], Black, Circle[{14, 9}, 4], Red,
       Circle[{24, 9}, 4], Yellow, Circle[{9, 4}, 4], Green,
      Circle[{19, 4}, 4]}], ImageSize -> {30, 15}], {c_ :>
    Style["*", RGBColor@c]}, {2}]

```
> 37 votes

# Answer
PostScript, 203 (-20 = 183)

```
%!
/Courier findfont 12 scalefont setfont
/l { setrgbcolor translate 20 { 0 30 moveto (*) show 18 rotate } repeat } def
140 200 0 0 1 l 45 -30 1 1 0 l 45 30 0 0 0 l 45 -30 0 1 0 l 45 30 1 0 0 l
showpage

```

I maintain that this counts as "ASCII art", though it doesn't write to the console. Output:

This could be golfed a little more.
> 34 votes

# Answer
## Windows Command Script - 112 percent bytes

```
%1%0 @echo. set
%2.= oooo
%2,=o    o
%1%.%%.%%.%&%1%,%%,%%,%&%1o  %.%%.%  o&%1%.%%.%%.%&%1   %,%%,%&%1   %.%%.%

```

**And of course, the obligatory cheat'ish version - 4 bytes**

```
%~n0

```

saved as:

```
@echo. oooo  oooo  oooo&echo.o    oo    oo    o&echo.o   oooo  oooo   o&echo. oooo  oooo  oooo&echo.   o    oo    o&echo.    oooo  oooo.cmd

```
> 25 votes

# Answer
# Another attempt in Perl, ~~130~~ 120

Thanks to manatwork for helping with this

```
for(qw(15005 40410 802a0 80a28 41414 15005 808 2a0)){$s=sprintf"%20b",hex;$s=~y/01/ #/;print$s.substr(reverse($s),1).$/}

```

Output:

```
   # # #         # # #         # # #
 #       #     #       #     #       #
#         # # #         # # #         #
#       # #   # #     # #   # #       #
 #     # #     # #   # #     # #     #
   # # #         # # #         # # #
        #       #     #       #
          # # #         # # #

```
> 21 votes

# Answer
# Python: ~~157~~ ~~140~~ ~~138~~ ~~133~~ ~~122~~ 107 characters

## 107

(thanks to manatwork)

```
for o in"jzd360 1zlpwci 3ydgr29 20pzv5u jzd360 149ytc b8n40".split():print bin(int(o,36))[2:].rjust(34,'0')

```

sample output:

```
0001001000000001001000000001001000
0100000010000100000010000100000010
1000000001001000000001001000000001
0100000110000110000110000110000010
0001001000000001001000000001001000
0000000100000010000100000010000000
0000000001001000000001001000000000

```

## 157

```
print'\n'.join(['{0:b}'.format(o).rjust(39,'0') for o in [45099909288,137984246274,275230249985,276241138945,137984246274,45099909288,1078001920,352343040]])

```

## 122

(just started this one, I will try to improve it)

```
h=lambda x:bin(int("15bb511iun9aqulod22j8d4 ho8skh  "[x::8],36))[2:].rjust(20)
for x in range(8):print h(x)+h(x)[::-1][1:]

```

---

### with better output: 120 characters

```
for o in"jzd360 1zlpwci 3ydgr29 20pzv5u jzd360 149ytc b8n40".split():print bin(int(o,36))[2:].replace('0',' ').rjust(34)

```

sample output:

```
   1  1        1  1        1  1
 1      1    1      1    1      1
1        1  1        1  1        1
 1     11    11    11    11     1
   1  1        1  1        1  1
       1      1    1      1
         1  1        1  1

```
> 20 votes

# Answer
# Perl, ~~177~~ 163

An improved version thanks to Dom Hastings:

```
$s=$"x3;print"  .-~-. "x3 .$/." /$s  \\"x3 .$/."|$s$s "x4 ."
 \\$s ./~\\.$s./~\\.$s /
  '-./'$s'\\-/'$s'\\.-'
"."$s |$s"x3 ."
$s "." \\$s  /"x2 ."
$s"."$s'-.-'"x2;

```

Output:

```
  .-~-.   .-~-.   .-~-.
 /     \ /     \ /     \
|       |       |       |
 \    ./~\.   ./~\.    /
  '-./'   '\-/'   '\.-'
    |       |       |
     \     / \     /
      '-.-'   '-.-'

```
> 17 votes

# Answer
# C, 257 bytes

```
#include <stdio.h>
d(i,j){int r=35;float x=r,y=0;while(--r>0){char s[8]={29,(((int)y+j)/32)+32,(((int)y+j)%32)+96,(((int)x+i)/32)+32,(((int)x+i)%32)+64,31,'.',0};puts(s);x-=0.2*y;y+=0.2*x;}}main(){d(140,200);d(185,170);d(230,200);d(275,170);d(320,200);}

```

This could have been golfed a bit more.

This has to be run on a Tektronix 4010 (or an emulator such as xterm -t). Output:

This is indeed ASCII art, since those are all '.' characters. And it does output to the console, as requested. Some Tektronix emulators support colour. Mine didn't, so I couldn't do that.
> 15 votes

# Answer
# Haskell, 200

```
main=mapM(putStrLn.map(\b->if b then '#' else ' '))$(map.map)(\(x,y)->or$map(\(n,m)->(<2).abs.(18-)$sqrt$(n-x)^2+(m-y*2)^2)$[(20,20),(60,20),(100,20),(40,40),(80,40)])$map(zip[0..120].repeat)[0..30]

```

Output:

```
            #################                       #################                       #################
         ########### ###########                 ########### ###########                 ########### ###########
      #######               #######           #######               #######           #######               #######
     #####                     #####         #####                     #####         #####                     #####
   #####                         #####     #####                         #####     #####                         #####
  #####                           #####   #####                           #####   #####                           #####
 #####                             ##### #####                             ##### #####                             #####
 ####                               #### ####                               #### ####                               ####
 ####                               #### ####                               #### ####                               ####
 ###                                 ### ###                                 ### ###                                 ###
 ####                           #################                       #################                           ####
 ####                        ########### ###########                 ########### ###########                        ####
 #####                    #######  ##### #####  #######           #######  ##### #####  #######                    #####
  #####                  #####    #####   #####    #####         #####    #####   #####    #####                  #####
   #####               #####     #####     #####     #####     #####     #####     #####     #####               #####
     #####            #####    #####         #####    #####   #####    #####         #####    #####            #####
      #######        #####  #######           #######  ##### #####  #######           #######  #####        #######
         ########### ###########                 ########### ###########                 ########### ###########
            #################                       #################                       #################
                     ###                                 ### ###                                 ###
                     ####                               #### ####                               ####
                     ####                               #### ####                               ####
                     #####                             ##### #####                             #####
                      #####                           #####   #####                           #####
                       #####                         #####     #####                         #####
                         #####                     #####         #####                     #####
                          #######               #######           #######               #######
                             ########### ###########                 ########### ###########
                                #################                       #################

```

golfed out of:

```
{-# LANGUAGE NoMonomorphismRestriction #-}

olympMids = [(1,1),(3,1),(5,1),(2,2),(4,2)]
circleRadius = 0.9
circleBorder = 0.1
scaleFactor = 20
verticalScale = 0.5

distance :: Floating a => (a,a) -> (a,a) -> a
distance (x,y) (x2,y2) = sqrt $ (x2-x)^2 + (y2-y)^2

match :: (Floating a, Ord a) => (a,a) -> (a,a) -> Bool
match v v2 = (<circleBorder) . abs . (circleRadius-) $ distance v v2

matchOlymp :: (Floating a, Ord a) => (a,a) -> Bool
matchOlymp v = or $ map (match $ scale v) $ olympMids
  where
    scale (x,y) = (x / scaleFactor, y / scaleFactor / verticalScale)

board :: (Enum a, Num a) => a -> a -> [[(a, a)]]
board lx ly = map (zip [0..lx] . repeat) [0..ly]

printOlymp = mapM (putStrLn . map to) $ (map.map) matchOlymp $ board 120 30

main = printOlymp

to :: Bool -> Char
to True = '#'
to False = ' '

```
> 12 votes

# Answer
# Java, ~~181~~ ~~179~~ ~~161~~ 156 bytes

```
enum M{M;{System.out.print(new java.math.BigInteger("2b13bp4vx9rreb1742o0tvtpxntx0mgsfw48c4cf",36).toString(2).replaceAll(".{29}","$0\n"));System.exit(1);}}

```

(Won't compile on jdk 1.7, requires 1.6 or lower)

The output:

```
11100011111110001111111000111
10111110111011111011101111101
01111111000111111100011111110
10111100111001110011100111101
11100011111110001111111000111
11111101111101110111110111111
11111111000111111100011111111

```

Definitely not a winner, but come on, it's *java*.
> 12 votes

# Answer
## Ruby, 9

```
p"\044"*5

```

**#satire**

The rules allow for art that does not look exactly like the example, but it must *"represent the Olympic rings well enough that it's recognizable"*.

You may recognize this representation of the Olympic Games logo.
> 11 votes

# Answer
# Javascript - 170 ~~185~~ ~~189~~ Chars

```
'jzd36071zlpwci73ydgr29720pzv5u7jzd3607149ytc7b8n40'.split(7).map(function(x){a=parseInt(x,36).toString(2);console.log((Array(35-a.length).join(0)+a).replace(/0/g,' '))})

```

**Output:**

```
   1  1        1  1        1  1
 1      1    1      1    1      1
1        1  1        1  1        1
 1     11    11    11    11     1
   1  1        1  1        1  1
       1      1    1      1
         1  1        1  1

```

# 2nd Javascript - 25 Chars

```
console.log('O O O\n O O')

```

**Output:**

```
O O O
 O O

```

The second is lazy
> 11 votes

# Answer
**Binary! (265 CHARS)**

```
0001111100000000111110000000011111000
0100000001000010000000100001000000010
1000000001111100000000011111000000001
0100000011000011000001100001100000010
0001111100000000111110000000011111000
0000000010000001000001000000100000000
0000000001111100000000011111000000000

```

It is too large to win, but at least it looks cool!
> 11 votes

# Answer
# PHP - 99 (-20?)

```
 bbbb  ####  rrrr
b    b#    #r    r
b   ybyy  g#gg   r
 bbyb  ##g#  rrrr
   y    yg    g
    yyyy  gggg

```

That is definitely recognizable. I say that my "colors" count; it's a close representation.

If you don't like that, then here is

# GolfScript - 101 (-20?)

```
' bbbb  ####  rrrr
b    b#    #r    r
b   ybyy  g#gg   r
 bbyb  ##g#  rrrr
   y    yg    g
    yyyy  gggg'

```
> 10 votes

# Answer
# Bash + ImageMagick: 163 characters

```
e=ellipse
c=,10,5,0,360
convert -size 70x20 xc:black +antialias -stroke white -fill none -draw "$e 10,5$c$e 34,5$c$e 58,5$c$e 22,10$c$e 46,10$c" xpm:-|tr -dc ' .
'

```

Sample output:

```
.

     ...........             ...........             ...........
   ....       ....         ....       ....         ....       ....
 ...             ...     ...             ...     ...             ...
..                 ..   ..                 ..   ..                 ..
..                 ..   ..                 ..   ..                 ..
.                ...........             ...........                .
..             ......   ......         ......   ......             ..
..           ...   ..   ..   ...     ...   ..   ..   ...           ..
 ...        ..   ...     ...   ..   ..   ...     ...   ..        ...
   ....     ......         ......   ......         ......     ....
     ...........             ...........             ...........
            ..                 ..   ..                 ..
            ..                 ..   ..                 ..
             ...             ...     ...             ...
               ....       ....         ....       ....
                 ...........             ...........

```
> 10 votes

# Answer
## Perl 6: ~~112~~ ~~77~~ 56 characters, 75 bytes

```
say flip .ord.base(2).trans("01"=>" @")for"䔐㣠".comb

```
* Unicde strings! (above string is "\x1C71C\x228A2\x438E1\x26DB2\x1C71C\x4510\x38E0")
* `.comb` gives a List of the separate characters in a String (without argument anyway)
* `.ord` gives character code number from character
* `.base(2)` returns a string with base-2 encoding of that Int
* `.trans` replaces the digits with space and @ for better visibility
* `flip` reverses the characters of a string so that missing leading 0's don't mess up the drawing.

```
  @@@   @@@   @@@
 @   @ @   @ @   @
@    @@@   @@@    @
 @  @@ @@ @@ @@  @
  @@@   @@@   @@@
    @   @ @   @
     @@@   @@@

```

---

edit2: newer solution using qwote words and base-36 encoded

```
say flip :36($_).base(2).trans("01"=>" @")for<2HWC 315U 5XI9 3ESY 2HWC DN4 B8G>

```
* `<ABC DEF GHI>` is a quote-words syntax in perl6, so you get a list of Strings
* `:36($_)` creates an Int from a base-36 encoded string in `$_` (`for` loop default variable)

---

edit: old solution has nicer (copied) drawing but is longer:

```
  say flip :36($_).base(2).trans("01"=>" o")for<KPVBKQ0 1RE099TU 3IFSZG1T 3IWIUAYP 1SDK5282 KPVBKQ0 HTTBLS 5TRXMO>

```

```
   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     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
```
> 10 votes

# Answer
# Mathematica ~~185~~ 175

10 bytes saved by mathe.

The rings below are ASCII 'O's.

The letter "O", slightly translucent, in Century Gothic, printed 5 times at font size=145 printer points.

This is not terminal art. However it fully satisfies Wikipedia's definition of Ascii art: http://en.wikipedia.org/wiki/ASCII\_art.

```
Graphics[{Opacity@.8,Style["O",#]~Text~#2&@@@{{Blue,{-1.5,1}},{Black,{0,1}},{Red,{1.5,1}},{Orange,{-.8,.4}},{Darker@Green,{.8,.4}}}},BaseStyle->{145,FontFamily->"Century Gothic"}]

```
> 10 votes

# Answer
**JavaScript: 153 chars**

I wanted to see if I could do it any faster using algebra to actually graph the circles:

```
s="";c=[3,7,11,7,19,7,7,4,15,4];for(y=10;y>0;y--){s+="\n";for(x=0;x<23;x+=.5){t=1;for(i=0;i<9;i+=2){a=x-c[i];b=y-c[i+1];d=a*a+b*b-9;t&=(d<0?-d:d)>3}s+=t}}

```

(`c` is an array of five (x,y) pairs, the centers of the circles, flattened to save ten characters.)

output:

```
1110000000111111111000000011111111100000001111
1000111110001111100011111000111110001111100011
0011111111100111001111111110011100111111111001
0011111111100000001111111110000000111111111001
0011111110000111000011111000011100001111111001
1000111100001111100001110000111110000111100011
1110000000111111111000000011111111100000001111
1111111100111111111001110011111111100111111111
1111111110001111100011111000111110001111111111
1111111111100000001111111110000000111111111111

```

**159 chars** is a little more readable:

```
s="";c=[3,7,11,7,19,7,7,4,15,4];for(y=10;y>0;y--){s+="\n";for(x=0;x<23;x+=.5){t=1;for(i=0;i<9;i+=2){a=x-c[i];b=y-c[i+1];d=a*a+b*b-9;t&=(d<0?-d:d)>3}s+=t?" ":t}}

```

output:

```
   0000000         0000000         0000000
 000     000     000     000     000     000
00         00   00         00   00         00
00         0000000         0000000         00
00       0000   0000     0000   0000       00
 000    0000     0000   0000     0000    000
   0000000         0000000         0000000
        00         00   00         00
         000     000     000     000
           0000000         0000000

```

In **167 chars** we have "colors":

```
s="";c=[3,7,11,7,19,7,7,4,15,4];for(y=10;y>0;y--){s+="\n";for(x=0;x<23;x+=.5){t=1;for(i=0;i<9;i+=2){a=x-c[i];b=y-c[i+1];d=a*a+b*b-9;t&=(d<0?-d:d)>3;h=t?i:h}s+=t?" ":h}}

```

output:

```
   8888888         0000000         2222222
 888     888     000     000     222     222
88         88   00         00   22         22
88         8844400         0066622         22
88       4444   0044     6600   2266       22
 888    4444     0004   6000     2226    222
   8888888         0000000         2222222
        44         44   66         66
         444     444     666     666
           4444444         6666666

```

And with **189 chars**, I can make the radius `r` adjustable as well:

```
r=5;s="";c=[r,0,2*r+1,r,3*r+2,0,4*r+3,r,5*r+4,0];for(y=-r;y<3*r;y++){s+="\n";for(x=0;x<9*r;x+=.5){t=1;for(i=0;i<9;i+=2){a=x-c[i];b=y-c[i+1];d=a*a+b*b-r*r;t&=(d<0?-d:d)>r;h=t?i:h}s+=t?" ":h}}

```

http://jsfiddle.net/mblase75/5Q6BX/
> 8 votes

# Answer
# APL, 8 chars/bytes\*

Here's an answer pushing for lowest char count (this is code golf after all)

```
2 5⍴'○ '

```

Output:

```
○ ○ ○
 ○ ○

```

The symbol is ○, APL circle operator. You can put an 'O' instead, in case you want strictly ASCII output. I just thought it fit to use an APL symbol.

---

Just for kicks, here's a color version (37 chars - 20 = 17 score)

```
2 20⍴'m',⍨¯2↓3↓∈(⊂'m○ ^[[3'),⍪'40132 '
                      ‾‾ ← single Esc character, type Ctrl+V Esc on the terminal

```

Output: ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯
\*: APL can be written in its own (legacy) single-byte charset that maps APL symbols to the upper 128 byte values. Therefore, for the purpose of scoring, a program of N chars *that only uses ASCII characters and APL symbols* can be considered to be N bytes long.
> 7 votes

# Answer
# CSS, ~~1176~~ ~~922~~ ~~855~~ 771 bytes, -20 colour bonus = 751

```
html,head,title,body{display:block; color:transparent; font:bold 1em/1 monospace; height:0}
link,meta,style{display:none}
:before,:after{float:left; color:#000; white-space:pre;
content:'   @@@@@@@\A  @@@     @@@\A@@         @@ \A            @@\A@@         @@\A@@         @@\A  @@@     @@@\A    @@@@  @'}
html:before{color:blue}
title:before,title:after{color:blue; position:absolute; left:0; top:3em; content:'@@'}
title:after{color:red; top:7em; content:'                                   @@'}
head:after{color:red}
body:before{clear:left; content:'     '}
body:after,html:after{position:relative; top:-5em; color:#EC0;
content:'    @  @@@@\A   @@@     @@@\A  @@         @@\A  @@         @@\A  @@\A  @@         @@\A   @@@     @@@\A     @@@@@@@'}
html:after{color:#090}

```

CSS only, no markup needed. See markupless fiddle here: http://jsfiddle.net/XcBMV/12/

In colour, and with the correct overlap.
> 7 votes

# Answer
**Perl - 12 characters**

```
say"OOO\nOO"

```

OK, so it's not an especially artistic rendering. ;-)

Slightly cuter:

```
perl -MTerm::ANSIColor=:constants -E'say ON_BRIGHT_WHITE,BLUE,O,BLACK,O,RED,O,$/,YELLOW,O,GREEN,O,RESET'

```
> 6 votes

# Answer
# GAS Assembly 16-bit BIOS OL loader – 617 - 20 = 597

Going crazy on length here, so mere for the fun of it.

---

It does not load much, but it loads The Olympic Games logo as ASCII with colors ;)

Code:

```
.code16;S:jmp o;nop;o:mov $1984,%ax;mov %ax,%ds;mov %ax,%es;movw $t,%si;r:lodsb;or %al,%al;jz q;cmp $33,%al;jg k;movb $0,c;call X;inc %dh;mov $0,%dl;call G;jmp r;k:sub $48,%al;mov %al,%cl;add %al,c;lodsb;cmp $32,%al;je v;mov %al,%bl;and $15,%bl;mov $35,%al;v:mov $9,%ah;mov $0,%bh;mov $0,%ch;int $16;call X;mov c,%dl;call G;jmp r;q:ret;G:mov $2,%ah;int $16;X:mov $3,%ah;mov $0,%bh;int $16;ret;c:.byte 0;t:.asciz "3 5A9 5H9 5D!1 1A7 1A5 1H7 1H5 1D7 1D!1A9 1A4N9 1H4B9 1D!1A7 1N1 1A3 1H1 1N5 1B1 1H3 1D1 1B7 1D!1 1A5 1N1 1A5 1H1 1N3 1B1 1H5 1D1 1B5 1D!3 4A1N9 4H1B9 5D!8 1N7 1N5 1B7 1B!9 1 5N9 5B!";.=S+510;.word 0xaa55

```

### (Linux) Build and extract MBR image

```
as -o olymp.o olymp.S
objcopy -O binary olymp.o olymp.img

```

### Running in emulator

*(Have not tested it on my home computer yet ...)*

```
qemu-system-i386 olymp.img

```

### Result
> 6 votes

# Answer
# TI-Basic (16 bytes)

Note: TI-Basic is tokenized. If I remember correctly, `ClrHome` and `Disp` are one-byte tokens.

```
ClrHome
Disp "O O O"," O O

```
> 5 votes

# Answer
## Python (318-20)

```
def f(s,i,j,c):
    for (k,l) in zip([i,i,i+1,i+1,i+2,i+2,i+3,i+3,i+4,i+4,i+5,i+5],[j+2,i+3,j+1,j+4,j,j+5,j,j+5,j+1,j+4,j+2,j+3]):s[k][l]=c+'+'+'\033[0m'
a=[];
for i in range(9):a+=[14*[' ']]
for i in [0,4,8]:f(a,0,i,'\033[9%im'%((4*i+4)%5))
for i in [2,6]:f(a,3,i, '\033[9%im'%((i+1)%5))
for l in a:print''.join(l)

```

`a` is a matrix of strings, the function `f` modifies it by drawing a circle at location `i,j` with color `c` using ansi color codes. Finally `a` is printed.
> 4 votes

# Answer
```
#include<iostream.h>
#include<conio.h>
#define tc textcolor

void circle(int x,int y,int k)
{
  tc(k);
  int n;
  for(n=0;n<=6;n++)
  {

    if(n==0||n==6)
    {
      gotoxy(x+3,y+n);
      cprintf("* * *");
    }
    else if(n==1||n==5)
    {
      gotoxy(x+1,y+n);
      cprintf("*");
      gotoxy(x+9,y+n);
      cprintf("*");
    }
    else if(n>1&&n<5)
    {
      gotoxy(x,y+n);
      cprintf("*");
      gotoxy(x+10,y+n);
      cprintf("*");
    }
  }
}

void main()
{
  clrscr();
  circle(1,1,BLUE);
  circle(14,1,WHITE);
  circle(27,1,RED);
  circle(8,4,YELLOW);
  circle(21,4,GREEN);
  _setcursortype(0);
  getch();
}

```
> 4 votes

# Answer
# Python - 163 characters (thanks to manatwork!)

```
print("""  000     000     000
 0   0   0   0   0   0
0     000     000     0
 0   0   0   0   0   0
  000     000     000
     0   0   0   0
      000     000""")

```

### Output:

```
  000     000     000
 0   0   0   0   0   0
0     000     000     0
 0   0   0   0   0   0
  000     000     000
     0   0   0   0
      000     000

```

Very simple...
> 4 votes

# Answer
# Coffeescript 123

Input:

```
for t in[y=124830,137313,146673,y,17160,15600]
 n=t.toString 2;k=31-n.length;n=0+n while k--;console.log n.replace /0/g,' '

```

Output:

```
   1111  1111  1111
  1    11    11    1
  1   1111  1111   1
   1111  1111  1111
     1    11    1
      1111  1111

```

Screenshot:

### Javascript 136

Input:

```
r=[y=124830,137313,146673,y,17160,15600]
for(i in r){
n=r[i].toString(2)
k=31-n.length
while(k--)n=0+n
console.log(n.replace(/0/g,' '))}

```
> 4 votes

# Answer
**R - 70**

Using CRAN-R statistics. Unfortunately the output goes to X and not to the console. I resubmitted this answer to the Olympic Games Logo - Free Style Edition

Anyhow, here is the code:

```
l=c(1,9);plot(3:7,c(6,4,6,4,6),col=c(4,7,1,3,2),cex=10,ylim=l,xlim=l)

```
> 3 votes

# Answer
# C - 230 bytes

Not a winner, but draws in a non-intuitive way:

```
#include <stdio.h>
#include <math.h>
#define D(p,q) ((int)hypot(x-(p),y-(q))==8)
int main(){int y,x;for(y=0;y<29;y++){for(x=0;x<61;x++)putchar((D(10,10)||D(30,10)||D(50,10)||D(20,18)||D(40,18))?'*':' ');putchar('\n');}return 0;}

```

To compile, `gcc -o ologo ologo.c -lm`.

Output:

```
    *********           *********           *********
   **       **         **       **         **       **
  *           *       *           *       *           *
 *             *     *             *     *             *
**             **   **             **   **             **
*               *   *               *   *               *
*               *   *               *   *               *
*               *   *               *   *               *
*             *********           *********             *
*            ** *   * **         ** *   * **            *
*           *   *   *   *       *   *   *   *           *
*          *    *   *    *     *    *   *    *          *
**        **   **   **   **   **   **   **   **        **
 *        *    *     *    *   *    *     *    *        *
  *       *   *       *   *   *   *       *   *       *
   **     * **         ** *   * **         ** *     **
    *********           *********           *********
          *               *   *               *
          *               *   *               *
          *               *   *               *
          **             **   **             **
           *             *     *             *
            *           *       *           *
             **       **         **       **
              *********           *********

```
> 3 votes

# Answer
**using PASCAL / DELPHI**

```
program Project_olympic_rings;
{$APPTYPE CONSOLE}
{$R *.res}
uses
  System.SysUtils;
begin
    writeln(' O O O ' + #10 + '  O O ');
    readln;
end.

```
> 2 votes

# Answer
# PowerShell, 555 bytes

Certainly not the shortest, but it's PowerShell with real circle functions and some color!

```
cls
c 8 8 1
c 16 8 2
c 24 8 3
c 12 15 4
c 20 15 5
w 30 30 . 6
function global:c ([int]$x,[int]$y,[int]$n) {
foreach ($i in 1..360)
{
$t = [math]::pi * ($i / 180)
w ($x + 5 * [math]::cos($t)) ($y + 5 * [math]::sin($t)) * $n
}
}
function global:w ([int]$x,[int]$y,[string]$c,[int]$n) {
$p=$host.ui.rawui.cursorposition
$p.x=$x
$p.y=$y
$host.ui.rawui.cursorposition=$p
$h="green"
switch ($n){ 1 {$h = "blue" } 2 {$h = "black" } 3 {$h = "red" } 4 {$h = "yellow" } 5 {$h = "green" }}
write-host $c -f $h -nonewline
}

```
> 2 votes

# Answer
LAZARUS / FREE PASCAL (with color support , unit CRT)

```
program P;
uses crt;
procedure R(c : Byte);
begin
  TextColor(c);
  write('O ');
end;
begin
  R(blue);
  R(white);
  R(red);
  writeln;
  write(' ');
  r(yellow);
  r(green);
end.

```
> 2 votes

# Answer
# HTML+CSS (222 ch)

First go at code golf so it's not golfed nearly enough but I hadn't spotted anyone using HTML+CSS yet so meh..

```
<style>a{margin:-8px;font-size:4em}a:first-child{color:blue}a:nth-child(3){color:red}a:nth-child(4){color:#ff0}a:last-child{color:#060}a:nth-child(n+4){position:relative;top:-.8em;left:.2em}</style><a>O<a>O<a>O<br><a>O<a>O

```

Someone can probably golf it more. (size for example was just to make it look better!)

fiddle: http://jsfiddle.net/mikecmpbll/LtYCh/1/
> 2 votes

# Answer
## Jquery 503 chars

good challenge!

since I'm a web developer, I used the tools that I use each day... html/jquery/js

check out my answer at jsfiddle.net

http://jsfiddle.net/rYcVV/5/

screenshot of rings attached...

code minified `

var color=["#06f","#000","red","#fa0","#193"],lefty=[150,300,450,225,380],toppy=[50,50,50,100,100];for(var j=0;j<color.length;j++){for(var i=0;i<36;i++){$("#rings").append('*')}}for(var m=0;m<color.length;m++){for(var k=0;k<36;k++){$($("span.x"+m)[k]).css("transform","rotate("+(10*k)+"deg)")}};`
> 2 votes

# Answer
# PHP, 90 bytes

This matches the sample output exactly.

The code is displayed in a screenshot as it contains control characters that I can't post on Stack Exchange. Here is a longer, equivalent version using character codes that I can post here:

```
<?echo gzinflate("SP\0\1-0D\58Åx¹\x14P\$´Ðhœb¼\\˜æ)(\x10%†M+‘NFÕª…†q‰Aµb*\"d\x08\\#Yáª€%Üð\4Š‚\2v-8‚_X§\0");

```

That is 109 bytes but the version in the screenshot using control characters is 90 bytes.
> 1 votes

# Answer
## *Mathematica*, 132

Further golfing of swish's fine method:

```
x_~f~y_:=Boole[E<Norm@{#-x,#2-y}<4.3]&~Array~{13,30}

Grid@Replace[Hue/@{E,{0,0,0},0,π,.3}.f@@@{5|5,5|15,5|25,9|10,9|20},0->"",c_+_.:>Style["*",c]},{2}]

```
> 1 votes

# Answer
# Bash / base64 / zcat, 125

```
$ base64 -d<<<H4sIAKc54FIAA1NQUFDQAkMEwMrnUoCLEaS5UHUrKODlcxG0G4dqLahZWjj4Ckiuxq0KxgKpJT4sUH2M3V+oclhpJDW47AIAX9PRBqIBAAA=|zcat
    * * *           * * *           * * *
  *       *       *       *       *       *
*           *   *           *   *           *
*           * * *           * * *           *
*         * *   * *       * *   * *         *
  *     * *       * *   * *       * *     *
    * * *           * * *           * * *
        *           *   *           *
          *       *       *       *
            * * *           * * *
$

```
> 1 votes

# Answer
# TeX, 169

```
\color{blue}\put(0,2){\circle{5}}\color{black}\put(6,2){\circle{5}}\color{red}\put(12,2){\circle{5}}\color{yellow}\put(2,0){\circle{5}}\color{green}\put(9,0){\circle{5}}

```

Converting the resulting image to ASCII characters:

# Java

```
public class Converter {
    public static String convertImage(BufferedImage img)  {
        BufferedImage image = img;

        char[] tones = new char[]{'*', '*', '*', '*', '*',  ' '};
        int tone = 0;

        StringBuilder stringBuilder = new StringBuilder();

        Color color;

        for (double y = 0; y < image.getHeight(); y++) {
            for (double x = 0; x < image.getWidth(); x++) {
                color = new Color(image.getRGB((int) x, (int) y));

                tone = (color.getRed() + color.getGreen() + color.getBlue()) / 3;
                tone = tone / (256 / tones.length - 1);

                while (tone > tones.length - 1) tone--;

                stringBuilder.append(tones[tone] + " ");
            }
            stringBuilder.append("\n");
        }
        return stringBuilder.toString();
    }

    public static void main(String args[ ]) {
        BufferedImage image = null;
        Writer writer;
        try {
            image = ImageIO.read(new File("C:\\OlympicRings.gif"));

            writer = new BufferedWriter(new FileWriter(new File("C:\\ascii-conversion.txt")));
            writer.append((convertImage(image)));
            writer.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

```

it gives -

```
          * * * * * *                             * * * * * *                             * * * * * *
      * *             * *                     * *             * *                     * *             * *
    *                     *                 *                     *                 *                     *
  *                         *             *                         *             *                         *
  *                         *             *                         *             *                         *
*                             *         *                             *         *                             *
*                             *         *                             *         *                             *
*                             * * * * * * *                           * * * * * * *                           *
*                           * *         *   * *                     * *         *   * *                       *
*                         *   *         *       *                 *   *         *       *                     *
*                       *     *         *         *             *     *         *         *                   *
  *                     *   *             *       *             *   *             *       *                 *
  *                   *     *             *         *         *     *             *         *               *
    *                 *   *                 *       *         *   *                 *       *             *
      * *             * *                     * *   *         * *                     * *   *         * *
          * * * * * * *                           * * * * * * *                           * * * * * *
                      *                             *         *                             *
                      *                             *         *                             *
                        *                         *             *                         *
                        *                         *             *                         *
                          *                     *                 *                     *
                            * *             * *                     * *             * *
                                * * * * * *                             * * * * * *

```
> 1 votes

# Answer
# Math

```
|f(x)|=sqrt(1-x^2)
f(x+2)
f(x-2)
f(x+1)-1
f(x-1)-1

```

For the output to be able to be graphed with a computer I had to add:

```
g(x)=-f(x)
g(x+2)
g(x-2)
g(x+1)-1
g(x-1)-1

```

And remove the |'s from the first line.

But they don't *really* have to be there.
> 1 votes

# Answer
# C# \[202\]

Basic foreach loop in C#

```
class P{static void Main(){foreach(var i in new[]{0x3c7f1fc7,0x37ddf77d,0x2fe3f8fe,0x379ce73d,0x3c7f1fc7,0x3fbeefbf,0x3fe3f8ff})System.Console.WriteLine(System.Convert.ToString(i,2).Replace('1',' '));}}

```

Result Below

```
    000       000       000
  0     0   0     0   0     0
 0       000       000       0
  0    00   00   00   00    0
    000       000       000
       0     0   0     0
         000       000

```

Linq Version 215 Characters

```
namespace System.Linq{class P{static void Main(){new[]{0x3c7f1fc7,0x37ddf77d,0x2fe3f8fe,0x379ce73d,0x3c7f1fc7,0x3fbeefbf,0x3fe3f8ff}.ToList().ForEach(i=>Console.WriteLine(Convert.ToString(i,2).Replace('1',' ')));}}}

```
> 1 votes

# Answer
**PROCESSING** B/W (78 characters)

No output to the console but still fun to participate. Colours add a lot to the code so it is not worth the 20 points in this case.

> float i,s=9,k=1;for(i=1;i\<6;i++){k=i;if(i\>3){s=13;k=i\*1-2.5;}text("O",k\*8,s);}

Colour (150-20=130 characters)

> float r=0,g=0,b=255,i,s=9,k=1;for(i=1;i\<6;i++){k=i;if(i\>3){s=12;k=k-2.5;g=255;r=(5-i)\*255;}if(i==3){r=255;}if(i==2){b=0;}fill(r,g,b);text("O",k\*9,s);}
> 1 votes

# Answer
# gnuplot 42 characters

```
se te du
uns bor
uns tic
p '-' w ell not
1 4
2 3
3 4
4 3
5 4
e

```

Output:

```
             **                       **                      **
       ******  ******           ******  ******          ******  ******
    ***              ***     ***              ***    ***              ***
  ***                  *** ***                  ******                  ***
  *                      * *                      **                      *
  *                      ***                      **                      **
  *                **************           **************                **
  *             ***      * *     ***     ***      **      ***             *
  ***         ***      *** ***     *** ***      ******      ***         ***
    ***       *      ***     ***     * *      ***    ***      *       ***
       **************           **************          **************
             **                      ***                      **
              *                      * *                      *
              ***                  *** ***                  ***
                ***              ***     ***              ***
                   **************           **************

```

# Shorter version (with axes) 27 characters

```
se te du
p '-' w ell
1 4
2 3
3 4
4 3
5 4
e

```

Output:

```
  5.5 ++----------+----------+-----------+----------+-----------+---------++
      +           +          +           +          +           '-' ****** +
    5 ++                                                                  ++
      |     ************           ************           ************     |
      |  ***            ***     ***            ***     ***            ***  |
  4.5 +**                  ** **                  ** **                  **+
      **                    ***                    ***                    **
    4 *+                     *                      *                     +*
      *                ************           ************                 *
  3.5 **            ***     ***    ***     ***     ***    ***             **
      |**         **       ** **      ** **       ** **      **          **|
      |  ***     **     ***     ***    ***     ***     ***    **      ***  |
    3 ++    ************           ************           ************    ++
      |          *                      *                      *           |
  2.5 ++         **                    ***                    **          ++
      |           **                  ** **                  **            |
      |             ***            ***     ***            ***              |
    2 ++               ************           ************                ++
      +           +          +           +          +           +          +
  1.5 ++----------+----------+-----------+----------+-----------+---------++
      0           1          2           3          4           5          6

```
> 1 votes

# Answer
# HTML + CSS ( 209 characters )

This isn't really much better than the other HTML / CSS attempt, but I wanted to try this for myself! removing font size will again shrink down a teeny bit.

```
<style>e:after{content:'o';font-size:2em}e{position:absolute;color:#00f}e>e{left:9px;color:#000}e e e{color:red}e e e e{left:-4px;top:9px;color:#0F0}e e e e e{left:-9px;top:0;color:#ff0}</style><e><e><e><e><e>

```

fiddle: http://jsfiddle.net/rV4eQ/

it's not really kosher code, but the e seemed fun to use.
> 0 votes

# Answer
# PERL, 15 characters

```
say"O O O
 O O"

```

To be invoked with `-E`.

```
O O O
 O O

```
> 0 votes

# Answer
# TI-Basic (15 bytes)

This really ought to be a comment on @bb94 's answer, but I don't have the reputation for that yet.

```
ClrHome
Disp "O O O
" O O

```

I saved a byte by omitting a closing quote and using the fact that programs print the final line without being explicitly told to. This also avoids the "Done" that would be printed otherwise.
> 0 votes

---
Tags: code-golf, ascii-art
---


# Question
Title: Build railroad tracks and cheat the government
You are a railroad entrepreneur in the 19th-century United States when trains become popular because they are the most efficient means of transporting large volumes of materials by land. There is a national need for railroad tracks from the east coast through some recently colonized lands in the west.

To accommodate this need, the U.S. government is going to levy a tax to subsidize railroads. They have promised to pay money to your railroad company for each mile of track laid. Since laying tracks in hilly and mountainous regions is more expensive than laying tracks in flat land, they adjust the amount they give accordingly. That is, the government will pay

* $5,000 per mile of track laid in flat land
* $12,500 per mile of track laid in hilly land
* $20,000 per mile of track laid in mountains.

Of course, this plan does not accurately reflect how much it actually costs to lay tracks.

You have hired some cartographers to draw relief maps of the regions where you will be laying track to analyze the elevation. Here is one such map:

```
S12321
121234
348E96

```

Each digit represents one square mile of land. `S` is the starting point, `E` is the ending point. Each number represents the intensity of the elevation changes in that region.

* Land numbered 1-3 constitutes flat land.
* Land numbered 4-6 constitutes hilly land.
* Land numbered 7-9 constitutes a mountain range.

You have, through years of experience building railroad tracks, assessed that the cost of track building (in dollars) satisfies this formula:

```
Cost_Per_Mile = 5000 + (1500 * (Elevation_Rating - 1))

```

That means building on certain elevation gradients will cost you more money than the government gives, sometimes it will be profitable, and sometimes you will just break even.

For example, a mile of track on an elevation gradient of 3 costs $8,000 to build, but you only get paid $5,000 for it, so you lose $3000. In contrast, building a mile of track on an elevation gradient of 7 costs $14,000, but you get paid $20,000 for it: a $6,000 profit!

Here is an example map, as well as two different possible paths.

```
S29    S#9    S##
134    1#4    1##
28E    2#E    2#E

```

The first track costs $30,000 dollars to construct, but the government pays you $30,000 for it. You make no profit from this track.

On the other hand, the second costs $56,500 to build, but you get paid $62,500 for it. You profit $6,000 from this track.

**Your goal:** given a relief map, find the most profitable (or perhaps merely the least expensive) path from the start to the end. If multiple paths tie, any one of them is an acceptable solution.

# Program Details

You are given text input separated with a rectangular map of numbers and one start and end point. Each number will be an integer inclusively between 1 and 9. Other than that, the input may be provided however you like, within reason.

The output should be in the same format as the input, with the numbers where track has been built replaced by a hash (`#`). Because of arbitrary regulations imposed by some capricious politicians, tracks can only go in horizontal or vertical paths. In other words, you can't backtrack or go diagonally.

The program should be able to solve in a reasonable amount of time (i.e. \<10 minutes) for maps up to 6 rows and 6 columns.

This is a **code golf** challenge, so the shortest program wins.

I have an example (non-golfed) implementation.

# Sample I/O

```
S12321
121234
348E96

S12321
######
3##E##

S73891
121234
348453
231654
97856E

S#3###
1###3#
3#####
######
#####E

```

# Answer
## Python, 307 chars

```
import os
I=os.read(0,99)
n=I.find('\n')+1
I='\0'*n+I+'\0'*n
def P(p):
 S=[]
 for d in(-n,-1,1,n):
  y=p[-1]+d
  if'E'==I[y]:S+=[(sum((int(I[v])-1)/3*75-15*int(I[v])+15for v in p[1:]),p)]
  if'0'<I[y]<':'and y not in p:S+=P(p+[y])
 return S
for i in max(P([I.find('S')]))[1][1:]:I=I[:i]+'#'+I[i+1:]
print I,

```

`P` takes a partial path `p` and returns all ways of extending it to reach `E`. Each returned path is paired with its score so `max` can find the best one.

Takes about 80 seconds on a 6x6 map.
> 5 votes

# Answer
## Python: 529 482 460 bytes

My solution will not win any prizes. However, since there are only two solutions posted and I found the problem interesting, I decided to post my answer anyway.

**Edit:** Thanks to Howard for his recommendations. I've managed to shave a lot of my score!

```
import sys
N=len
def S(m,c,p=0):
 if m[c]=='E':return m,p
 if m[c]<'S':
    b=list(m);b[c]='#';m=''.join(b)
 b=[],-float('inf')
 for z in(1,-1,w,-w):
    n=c+z
    if 0<=n<N(m)and m[n]not in('S','#')and(-2<z<2)^(n/w!=c/w):
     r=S(m,n,p+(0if m[n]=='E'else(int(m[n])-1)/3*5-int(m[n])+1))
     if b[1]<r[1]:b=r
 return b
m=''
while 1:
 l=sys.stdin.readline().strip()
 if l=='':break
 w=N(l);m+=l
b,_=S(m,m.index('S'))
for i in range(0,N(b),w):print b[i:i+w]

```
> 4 votes

# Answer
### Ruby, 233 characters

```
R=->s{o=s=~/S/m
s=~/E/m?(q=[-1,1,-N,N].map{|t|s[f=o+t]>'0'?(n=s*1
n[o]='#'
n[f]='S'
a=R[n]
a&&[a[0]-(e=s[f].to_i-1)/3*5+e,a[1]]):nil}-[nil]
q.sort!&&q[0]):[0,(n=s*1;n[o]='E'
n[$_=~/S/m]='S'
n)]}
N=1+(gets(nil)=~/$/)
$><<R[$_+$/*N][1]

```

A Ruby brute-force approach which runs well inside the time constraints on a 6x6 board. The input must be given on STDIN.

*Examples:*

```
S12321
121234
348E96

S#2321
1#####
3##E##
--
S73891
121234
348453
231654
97856E

S#####
1212##
#####3
#3####
#####E

```
> 3 votes

---
Tags: code-golf, path-finding
---


title: Name the poker hand - 7 cards edition

text:
# Question
Title: Name the poker hand - 7 cards edition
### The Challenge:

In this question: Name the poker hand you had to take a five card poker hand and identify it. This question is similar, with two twists:

First, the output will be in all lower case. This allows for more golfing, as you don't have to worry about the capitalization of `flush` and `straight`

```
high card
one pair
two pair
three of a kind
straight
flush
full house
four of a kind
straight flush
royal flush

```

Secondly, with the popularity of Texas Hold'em and 7 card stud, we here at code golf should be able to score a **seven card** poker hand am I right? When scoring a seven card hand, use the five best cards for your hand and ignore the two you don't need.

### Reference:

List of poker hands: http://en.wikipedia.org/wiki/List\_of\_poker\_hands

## Input (lifted directly from the previous thread)

7 *cards* from either stdin or commandline arguments. A card is a two letter string on the form `RS`, where R is rank and S is suit. The **ranks** are `2` \- `9` (number cards), `T` (ten), `J` (Jack), `Q` (Queen), `K` (King), `A` (Ace). The **suits** are `S`, `D`, `H`, `C` for spades, diamonds, hearts and clubs respectively.

### Example of cards

```
5H - five of hearts
TS - ten of spades
AD - ace of diamonds

```

### Example of input =\> desired output

```
3H 5D JS 3C 7C AH QS => one pair
JH 4C 2C 9S 4H JD 2H => two pair
7H 3S 7S 7D AC QH 7C => four of a kind
8C 3H 8S 8H 3S 2C 5D => full house
AS KC KD KH QH TS JC => straight

```

Notice in the second example there are actually three pairs, but you can only use five cards, so it's `two pair`. In the fifth example, there are both a `three of a kind` and a `straight` possible, but a `straight` is better, so output `straight`.

### Scoring

This is , so shortest code wins!

### Errata

1. You may not use external resources.
2. Ace is both high and low for straights.

# Answer
> 4 votes
# Ruby 353

This was based off of Chron's answer from the original question.

This takes input as command line arguments. Basically we just iterate over all combinations of size 5 to get what type of hand it is. Each hand type was modified so that is starts with a number. ("royal flush" -\> "0royal 4flush", "high card" -\> "9high card"). This allows us to sort strings that were returned. The first string after sorting is the best possible hand. So we print that after removing all numbers from the string.

```
o,p=%w(4flush 1straight)
f=/1{5}|1{4}0+1$/
puts $*.combination(5).map{|z|s=[0]*13;Hash[*z.map{|c|s['23456789TJQKA'.index c[0]]+=1;c[1]}.uniq[1]?[f,'5'+p,?4,'2four'+a=' of a kind',/3.*2|2.*3/,'3full house',?3,'6three'+a,/2.*2/,'7two pair',?2,'8one pair',0,'9high card']:[/1{5}$/,'0royal '+o,f,p+' '+o,0,o]].find{|r,y|s.join[r]}[1]}.sort[0].gsub(/\d/,'')

```

# Answer
> 5 votes
# Haskell ~~618 603 598 525 512 504 480~~ 464

Cards taken as a line of input. I think I've golfed this to death, but will easily be beaten by ruby etc using the same trick: if you generate all permutations, you get the forward sorts you want to look for straights, plus the reverse sorts you want for testing N of a kind.

```
import Data.List
m=map
z=take 5
q=m(\x->head[n|(f,n)<-zip"A23456789TJQK"[1..],f==x!!0])
l=m length
v=" of a kind"
w="flush"
y="straight"
c f s p r|f&&r="9royal "++w|f&&s='8':y++" "++w|f='5':w|s||r='4':y|True=case p of 4:_->"7four"++v;3:2:_->"6full house";3:_->"3three"++v;2:2:_->"2two pair";2:_->"1one pair";_->"0high card"
d x=c([5]==l(group$m(!!1)x))(q x==z[head(q x)..])(l$group$q x)$q x==1:[10..13]
k h=tail$maximum$m(d.z)$permutations$words h
main=interact k

```

Edited to inline "pair" and use number prefixes after seeing @FDinoff's entry, also composed map functions to shave one more char.

# Answer
> 2 votes
# C++, ~~622~~ 553 chars

four unnecessary newlines added below for clarity.

```
#include"stdafx.h"
#include"string"
std::string c=" flush",d=" of a kind",e="straight",z[10]={"high card","one pair","two pair","three"+d,e,c,"full house","four"+d,e+c,"royal"+c},
x="CDHSA23456789TJQK";char h[99];int main(){__int64 f,p,t,g,u,v,w,l=1,a=78517370881,b=a+19173960,i,j,q=0;gets_s(h,99);for(i=28;i-->7;){f=p=0;
for(j=7;j--;)if(j!=i%7&j!=(i+i/7)%7){f+=l<<x.find(h[j*3+1])*6;p+=l<<x.find(h[j*3])*3-12;}
v=p&b*2;u=v&v-1;w=p&p/2;g=p*64&p*8&p&p/8&p/64;f&=f*4;t=f&&p==a?9:f&&g?8:p&b*4?7:u&&w?6:f?5:g||p==a?4:w?3:u?2:v?1:0;
q=t>q?t:q;}puts(z[q].c_str());}

```

**Things changed in the golfed version:**

Rev 1: Changed all numeric variables to `__int64` for single declaration.

Rev 1: Golfed increment and condition of `for` loops

Rev 0: Changed octal constants to decimal.

Rev 0: Changed `if` statements to assignments with conditional operator. Rev 1: Rearranged further into a single expression for `t`. This required new variable `v` for one of the intermediate values

Rev 0: Deleted verbose output. Only outputs the best overall hand.

~~Rev 0: Gave up on compressing the output text (difficult in C because you can't concatenate strings using the + operator.) Writing "flush" only once saved me 12 characters but cost me 15, making me 3 chars worse off overall. So I just wrote it 3 times instead.~~  Rev 1: used `std::string` instead of `char[]` as suggested by FDinoff, making it possible to concatenate with `+`.

**Ungolfed version, 714 noncomment nonwhitespace characters.**

Loops through all 21 possible hands that can be made from 7 cards and rejects 2 cards each time. The suit and rank of the five chosen cards are totalised in variables f and p with a different octal digit for each suit/rank. Various bit operations are performed to determine the hand type, which is then stored in t (all 21 possibilities are output in the ungolfed version.) Finally the best possible hand is output.

```
#include "stdafx.h"
#include "string.h"

char x[] = "CDHSA23456789TJQK", h[99], z[10][99] =
{ "high card", "one pair", "two pair","three of a kind", "straight","flush","full house","four of a kind","straight","royal" };

int main(void)
{
        int i,j,q=0;                  //i,j:loop counters. q:best possible hand of 7 card
        scanf_s("%s/n", &h, 99); getchar();
        for (i = 7; i < 28; i++){

          //f,p: count number of cards of each suit (2 octal digits) and rank (1 octal digit.)
          //t: best hand for current 5 cards. g:straight flag. u,w: flags for pairs and 3's.
          //l: constant 1 (64bit leftshift doesn't work on a literal.)
          //octal bitmasks: a=ace high straight, b=general purpose

            __int64 f=0,p=0,t=0,g,u,w,l=1,a=01111000000001,b=a+0111111110;

           for (j = 0; j < 7; j++){
               if (j != i %7 & j != (i+i/7) %7){

                   f += l << (strchr(x,h[j*3+1])-x)*6;
                   p += l << (strchr(x,h[j*3])-x-4)*3;

                   printf_s("%c%c ",h[j*3], h[j*3+1]);
               }
           }

           w=p&b*2;                          //if 2nd bit set we have a pair
           if (w) t=1;
           u= w & w-1;                       //if there is only one pair w&w-1 evaluates to 0; +ve for 2 pair.
           if (u) t=2;
           w = p & p/2;                      // if 2nd and 1st bit set we have 3 of kind.
           if (w) t=3;
           g = p*64 & p*8 & p & p/8 & p/64;  // detects all straights except ace high. pattern for ace high in a.
           if (g||p==a) t=4;
           f&=f*4;                           //for a flush we want 5 cards of the same suit, binary 101
           if (f) t=5;
           if (u&&w) t=6;                    //full house meets conditions of 2 pair and 3 of kind
           if (p & b*4) t=7;                 //four of a kind
           if (f && g) t=8;                  //straight flush
           if (f && p==a) t=9;               //royal flush
           printf_s("%s %s \n",z[t],t>7?z[5]:"");
           q=t>q?t:q;
        }
        printf_s("%s %s",z[q],q>7?z[5]:"");
        getchar();
}

```

**Ungolfed output**

# Answer
> 2 votes
## perl (\>=5.14), ~~411~~ ~~403~~ ~~400~~ ~~397~~ 400

**Edit**: inlined a sub that was only called once, saving 8 chars.
**Edit 2**: removed a `.""` that was left over from an early attempt
**Edit 3**: instead of a temp variable that preserves the original `$_`, use one to make it unnecessary. Net gain 3 chars.
**Edit 4**: fixed failure to detect over-full full house (2x 3-of-a-kind). cost 3 chars.

Not quite a winner, but the straight detector is an interesting concept, I think.

```
sub
j{join"",sort@_}sub
o{j(map{{A=>10}->{$_},11+index(j(2..9).TJQKA,$_)}$h=~/(.(?=@_))/g)=~/.*(..)(??{j
map$1+$_.'.*',1..4})/?$1:()}$h=$_=<>;if(j(/(\S)\b/g)=~/(.)\1{4}/){$w=$_==19?royal:straight
for
o$f=$1}$_=j(/\b(\S)/g)=~s/(.)\1*/length$&/rge;$k=" of a kind";print$w?"$w flush":/4/?four.$k:/3.*2|[23].*3/?"full house":$f?flush:(o".")?straight:/3/?three.$k:/2.*2/?"two pair":/2/?"one pair":"high card"

```

Expanded version:

```
# We'll be doing a lot of sorting and joining
sub j {
  return join "", sort @_;
}

# r() expects $_ to contain a rank, and converts it to a numeric code. The
# code starts at 10 so the numbers will sort correctly as strings, and a list
# of 2 values is returned because A is both 10 and 23. All other ranks have
# undef as the first value and their proper 11..22 value as the second value.
sub r {
  return ({A=>10}->{$_}, 11+index(j(2..9).TJQKA,$_));
}

# Sequence-detector. Factored into a sub because it's run twice; once over
# the ranks in the flush suit to find a straight flush and once over all the
# ranks to find a straight. On successful match, returns the lowest rank of
# the straight (in the 10..23 representation).
# Required parameter: the suit to search, or "." for all suits.
sub o {
  j(map r,$h=~/(.(?=@_))/g)          # The list of ranks, in increasing order,
                                     # with ace included at both ends...
    =~                               # ...is matched against...
  /.*(..)(??{j map$1+$_.'.*',1..4})/ # ...a pattern requiring 5 consecutive
                                     # numbers.
  ?$1:()
  # A note about this regexp. The string we're matching is a bunch of numbers
  # in the range 10..23 crammed together like "121314151619" so you might
  # worry about a misaligned match starting on the second digit of one of the
  # original numbers. But since that would make every pair of digits in the
  # match end with a 1 or a 2, there's no way 5 of them will be consecutive.
  # There are no false matches.
  # Another note: if we have a royal flush and also have a 9 in the same
  # suit, we need to return the T rank, not the 9, which is why the regexp
  # starts with a .*
}

# Read a line into $_ for immediate matching with /.../ and also save it into
# $h because $_ will be clobbered later and we'll need the original string
# afterwards.
$h = $_ = <>;

if(j(/(\S)\b/g) =~ /(.)\1{4}/) { # flush detector: sorted list of all suits
                                 # contains 5 consecutive identical chars
  # $f=$1 comes first, so $f will be true later if there's a flush.
  # Then o() is called with the flush suit as arg to detect straight flush.
  # If there's no straight flush, o() returns the empty list and for loop
  # runs 0 times, so $w is not set. If there is a straight flush, the return
  # value of o() is compared to 19 to detect royal flush.
  $w = ($_==19 ? "royal" : "straight")
    for o($f=$1);
}

$_ =
  j(/\b(\S)/g)                 # Get the sorted+joined list of ranks...
    =~ s/(.)\1*/length $&/rge; # ... and turn it into a list of sizes of
                               # groups of the same rank. The /r flag
                               # requires perl 5.14 or newer.

print
  $w             ? "$w flush" :
  /4/            ? "four of a kind" :
  /3.*2|[23].*3/ ? "full house" :
  $f             ? "flush" :
  (o".")         ? "straight" :
  /3/            ? "three of a kind" :
  /2.*2/         ? "two pair" :
  /2/            ? "one pair" :
                   "high card"

```

# Answer
> 1 votes
## JavaScript 600

usage with nodeJS: `node code.js "7H 3S 7S 7D AC QH 7C"`

```
function a(o){s="";for(k in o)s+=o[k];return s}
b=process.argv[2]
c={S:0,H:0,D:0,C:0}
v={A:0,K:0,Q:0,J:0,T:0,"9":0,"8":0,"7":0,"6":0,"5":0,"4":0,"3":0,"2":0}
d=b.split(" ")
for(i=d.length;i--;){e=d[i];c[e[1]]++;v[e[0]]++}
c=a(c);v=a(v)
f=g=h=j=k=l=m=false
if((st=c.indexOf(5))!=-1)g=!g
if(v.match(/[1-9]{5}/))h=!h
if(st==0)f=!f
if(v.indexOf(4)!=-1)j=!j
if(v.indexOf(3)!=-1)k=!k
if(n=v.match(/2/g))if(n)if(n.length>=2)m=!m;else l=!l
p=" of a kind"
q="Flush"
r="Straight"
console.log(f&&g?"Royal "+q:h&&g?r+" "+q:j?"Four"+p:k&&(l||m)?"Full House":g?q:h?r:k?"Three"+p:m?"Two pairs":l?"Pair":"High card")

```

---
Tags: code-golf, game
---


title: Arranging pins on a microchip

text:
# Question
Title: Arranging pins on a microchip
Since no one has posted a "good quality question" recently, i feel it is my duty to...

**Task:**

> You work at an electronics company in the design department. The designers that work with you have asked you to make a program that will calculate the optimum configuration of pins on a microchip they are designing. With your ninja golfing skills, you are confident you can handle it.

Your company also has these requirements for each chip:

* The chips your company makes are known as TQFP, they have pins on each edge, but none in the middle.
* Each chip must be square, and have the same number of pins on each side.
* If the chip doesn't have enough pins to be square, pins will be added.
    + Extra pins are either a ground or voltage supply pin.
    + Half are ground, half are voltage supply.
    + If there is an odd number of extra pins, the odd one out is ground

Your program will take input as a single integer, which is the minimum number of pins the manufacturing needs. You will then output 4 integers:

* The number of pins (total)
* The number of pins per side
* The number of ground pins added
* The number of voltage supply pins added

**Rules:**

* You can use any language
* This is , to the shortest answer in bytes wins
* Bonus: -50 for printing an ASCII chip:

Something like this:

```
 +++++
 +   +
 +   +
 +   +
 +++++

```

(For example with an input of 20)

# Answer
> 5 votes
# APL, 54 chars/bytes\* – 50 = score 4

*“Take this, Golfscript!” special edition*

```
{t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]}

```

Takes a number as input and returns the required output. Dialect is Dyalog with `⎕IO⎕ML←1 3`

**Explanation**

```
{                        s←⌈⍵÷4 }  divide the # of pins by 4, take the ceiling and call it s
            ∘.{       }⍨⍳s         for each couple of naturals up to s compute a table with:
               ∨/⍺⍵∊1s             1 if either one of the two numbers is 1 or s, 0 otherwise
    ⊂' +'[1+                   ]   convert the 0 and 1s to space and + and enclose the table
                                   then...
                  t←4×s            multiply the pins per side by 4 and call it t (for total)
          h←2÷⍨⍵-⍨t                subtract the # of pins from it and divide by 2, call it h
 t s(⌈h)(⌊h            )           make a vector with t, s, the ceiling of h, and its floor,
                        ,——        and prepend it to the previously enclosed table of chars.

```

**Examples**

```
    {t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 0
0 0 0 0
    {t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 1
4 1 2 1  +
    {t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 2
4 1 1 1  +
    {t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 3
4 1 1 0  +
    {t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 4
4 1 0 0  +
    {t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 5
8 2 2 1  ++
         ++
    {t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 6
8 2 1 1  ++
         ++
    {t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 7
8 2 1 0  ++
         ++
    {t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 8
8 2 0 0  ++
         ++
    {t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 9
12 3 2 1  +++
          + +
          +++
    {t s(⌈h)(⌊h←2÷⍨⍵-⍨t←4×s),⊂' +'[1+∘.{∨/⍺⍵∊1s}⍨⍳s←⌈⍵÷4]} 13
16 4 2 1  ++++
          +  +
          +  +
          ++++

```

\*: Dyalog supports its own (legacy) single byte charset, where the APL symbols are mapped to the upper 128 byte values. Therefore the entire code can be stored in 54 bytes if needed.

# Answer
> 5 votes
# Python: 64 53 46 bytes

```
x=input()
m=x+3&~3
t=m-x
print m,m/4,t-t/2,t/2

```

Second Third attempt seems pretty minimal. Thanks for the help.

First attempt seems sort of long, we'll see what an hour or two of mulling it over will shave off of the byte count. Could also probably make it shorter if a function is allowed instead of program.

```
> python chip.py
9
(12, 3, 2, 1)

```

Also made a version that prints chips, seems like the `-50` isn't worth it in python. Total score of `102-50=52`.

```
x=input()
m=x+3&~3
n=m/4
t=m-x
s=['+'*-~n]
print'\n'.join(s+['+'+' '*~-n+'+']*~-n+s+[`m,n,t-t/2,t/2`])

```

Example:

```
> python chip.py
9
++++
+  +
+  +
++++
(12, 3, 2, 1)

```

# Answer
> 3 votes
## Julia, 62 61 56 bytes

```
m(x)=(s=iceil(x/4);p=4s-x;(4s,s,iceil(p/2),ifloor(p/2)))

```

Very straightforward. And now down to 56 thanks to gggg's sharp eyes.

Outputs:

```
In [14]:
    m(9),m(6),m(71),m(1),m(3)
Out[14]:
    ((12,3,2,1),(8,2,1,1),(72,18,1,0),(4,1,2,1),(4,1,1,0))

```

The ASCII chip bonus isn't worth the bytes it costs, but since I made it, here's all 190 bytes of it. **Edit:** I made the chip drawing before OP posted an example chip , so I'm sticking with my method. I think it looks better than plus signs, anyway.

```
m(x)=begin s=iceil(x/4)
p=4s-x
g=iceil(p/2)
v=ifloor(p/2)
b={x in[1,s]||y in[1,s+1]?"o":"."for x=1:s,y=1:s+1}
if g>0 b[1,1:g]="G" end
if v>0 b[s,s+2-v:s+1]="V" end
print(b,'\n')
return 4s,s,g,v end

m(29)

G G 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 V

Out[7]:
(32,8,2,1)

```

This version of the chip gets it down to 115, which is still too long for the bonus to be worthwhile. And it requires the "corners have two pins even though one is shown" assumption of OP's example. I prefer my corrected version above which shows the exact number of each type of pin.

```
m(x)=((s=iceil(x/4);p=4s-x);b={x in[1,s]||y in[1,s]?"o":"."for x=1:s,y=1:s};print(b);(4s,s,iceil(p/2),ifloor(p/2)))

```

Question posters of the future, take note: bonuses often serve only to increase the advantage of terse languages.

# Answer
> 2 votes
# Perl, 72 bytes

The input number is expected in STDIN, the result is written to STDOUT.

```
$_=<>;$==$_/4+!!($_%4);$a=4*$=-$_;@a=(4*$=,$=,$a-($-=$a/2),$-);print"@a"

```

**Test:**

```
echo 4 | perl a.pl
4 1 0 0

echo 5 | perl a.pl
8 2 2 1

echo 6 | perl a.pl
8 2 1 1

echo 7 | perl a.pl
8 2 1 0

```

**Ungolfed:**

```
$_=<>; # read input number from STDIN
$= = $_ / 4 + !!($_ % 4); # tricky way for ceil($_ % 4)
$a = 4 * $= - $_;         # extra pins in $a
@a = (4 * $=,             # total
      $=,                 # each side
      $a - ($- = $a / 2), # ground, tricky way for $a - floor($a/2)
      $-                  # voltage
);
print "@a"                # print result, separated by spaces

```

# Answer
> 2 votes
# J - 71 66 char -50 = 16 pts

Saves a bunch of bytes with the 50 bonus, so let's do that.

```
(((>.,<.)@-:@-@],~-,[:#2:1!:2~' +'{~1,~1,1,.~1,.0$~2#2-~-%4:)_4&|)

```

Some key bits:

* `_4&|` \- Take the input modulo -4: it's just like taking it mod 4, but you go into the range (-4,0\].
* `(>.,<.)@-:@-@]` \- Negate the residue mod -4 from before, halve it (`-:`), and take the ceiling (`>.`) and the floor (`<.`).
* `1,~1,1,.~1,.0$~2#` \- We make a square array of zeroes, and then pin ones all around it: in front (`,.`), behind (`,.~`), on top (`,`) and below (`,~`).
* `[:#2:1!:2~' +'{~` \- After constructing the square array the way we like it, we use its values to select (`{`) out of the characters `' '` and `'+'`, and then we print the matrix with `2:1!:2~`. Finally, we get the original number back (the number of pins per side) with the length.

Usage:

```
   (((>.,<.)@-:@-@],~-,[:#2:1!:2~' +'{~1,~1,1,.~1,.0$~2#2-~-%4:)_4&|) 20
+++++
+   +
+   +
+   +
+++++
20 5 0 0
   (((>.,<.)@-:@-@],~-,[:#2:1!:2~' +'{~1,~1,1,.~1,.0$~2#2-~-%4:)_4&|) 9
+++
+ +
+++
12 3 2 1

```

The version without the ASCII-drawing portion is 30 characters:

```
   (((>.,<.)@-:@-@],~-,-%4:)_4&|) 86
88 22 1 1

```

# Answer
> 2 votes
### GolfScript, score 5 (55 characters - 50 bonus)

```
~:^3+3~&.4/:&1$^-.)2/\2/]p&)'+'*n+'+'&(' '*'+'++n+&(*1$

```

The input is given on STDIN. The first part (until `]p`) does the calculation while the rest is for the bonus.

*Examples (run online):*

```
> 20
[20 5 0 0]
++++++
+    +
+    +
+    +
+    +
++++++

> 9
[12 3 2 1]
++++
+  +
+  +
++++

```

# Answer
> 1 votes
# Python (103):

```
from math import*
a=int(raw_input());c=ceil(a**.5);b=c**2;z=(b-a)/2;d=ceil(z);e=floor(z);print (b,c,d,e)

```

Not the shortest, but it does what it's supposed to.

# Answer
> 0 votes
# K - 68 char -50 = 18 pts

This solution mimics the J methods somewhat, but has an APL-like way of shaving off characters.

```
{`0:(" +"1,|1,)'+r#,1 0,|~!r:-2+q:_(x-:m:x!-4)%4;x,q,-1 1*_.5 -.5*m}

```

Explained:

* `x-:m:x!-4` \- Take `x` mod -4, putting it into the range (-4,0\]. Now, assign this to `m` (for modulus), and reassign `x` to `x` subtract `m`.
* `r:-2+q:_(x)%4` \- Divide `x` by 4 and floor it, converting it from unnecessary float to integer. Assign this to `q`, and assign two less than this to `r`.
* `1 0,|~!r` \- Take the integers less than `r`, starting from 0. Logical negate every integer, leaving a 1 in the 0 place and 0 everywhere else. Reverse the list, and then prepend `1 0`. Now, the list will be `r+2` = `q` items long, and the first and last are a 1.
* `+r#,` \- Make `r` copies of this list, and transpose the resulting matrix, which is now `r` wide and `q` high.
* ``0:(" +"1,|1,)'` \- Append 1 to the front and back of each row, and then use the placement of the 0s and 1s to select characters out of `" +"`. This creates an ASCII chip, which we print out to console with ``0:`.
* `_.5 -.5*m` \- Take `m` from before, halve it, and then floor it and its negation. K doesn't have a ceiling function, so you have to emulate ceiling by flooring the negative, and negating that again.
* `x,q,-1 1*` \- Flip the sign on the negative number of the two, and then append `x` and `q` from before to the list. This then goes on to be the return value.

Usage:

```
  {`0:(" +"1,|1,)'+r#,1 0,|~!r:-2+q:_(x-:m:x!-4)%4;x,q,-1 1*_.5 -.5*m} 20
+++++
+   +
+   +
+   +
+++++
20 5 0 0
  {`0:(" +"1,|1,)'+r#,1 0,|~!r:-2+q:_(x-:m:x!-4)%4;x,q,-1 1*_.5 -.5*m} 9
+++
+ +
+++
12 3 2 1

```

The version with no ASCII drawing is 34 characters:

```
  {x,_%[x-:m;4],-1 1*_.5 -.5*m:x!-4} 86
88 22 1 1

```

---
Tags: code-golf, hardware
---


# Question
Title: compare string without conditional operator
Compare if three string variables with the same content, return `true` if they are or `false` if they are not without using conditional operators and bitwise operators.

e.g. in C# without `&& || ?:`

```
return  (string1==string2)==(string1==string3)==true;

```

PS: initial idea came from these question

# Answer
# GolfScript

```
1$=:a;=a+2="true""false"if

```

This program assumes three strings on the stack.

Test online

How it works:

1. `1$` copies the second element on the stack (the second string) to the top of the stack.
2. `=:a;` returns `1` if the two top elements (the second and the third string) are equal; otherwise, `0`. Then, it stores this result in the variable `a` and it pops it from the stack. Now only the first and the second string remain on the stack.
3. `=` checks whether the first and the second string are equal.
4. `a+` puts the value of `a` on the stack and calculates the sum of `a` and the result of the previous comparison.
5. `2="true""false"if` puts `"true"` on the stack if the sum of the comparison results is equal to `2`: in this case, both comparisons returned true. If the sum is `1` or `0` then it puts `"false"` on the stack. This value is now the only one on the stack, and at the and of a program, GolfScript always outputs the values on the stack.

\[Edit\]

Thanks to Peter Taylor for pointing out that variables are not necessary:

```
1$=@@=+2="true""false"if

```
> 2 votes

# Answer
# Perl

The function `CompareStrings` takes *any* number of strings and returns the strings `true` or `false`:

* `true` is returned if there are one or more strings and all strings are equal.
* `false` is returned if there is no string or at least two different strings.

```
sub CompareStrings (@) {
    my %hash = map { $_ => 1 } @_;
    return ('false', 'true')[not scalar(keys %hash) - 1];
}

```

The strings are put as keys in a hash. If there is at least one string and all strings are equal, then the hash has one key exactly. Otherwise there are zero or two or more keys. After 1 is subtracted the operator `not` maps the cases to the empty string and `1` that are used to select the result string (the empty string becomes 0).

```
sub CompareStrings (@) {
    my %hash = map { $_ => 1 } @_;
    return ('false', 'true')[not scalar(keys %hash) - 1];
}

```

**Complete script with test cases:**

```
#!/usr/bin/env perl
use strict;
$^W=1;

sub CompareStrings (@) {
    # several variants to initialize the hash, whose keys are the strings:
    # my %hash; @hash{@_} = (1) x @_;
    # my %hash; $hash{$_} = 1 for @_;
    my %hash = map { $_ => 1 } @_;
    return ('false', 'true')[not scalar(keys %hash) - 1];
}

# Testing

$\ = "\n";
print CompareStrings qw[];                  # false
print CompareStrings qw[foobar];            # true
print CompareStrings qw[hello hello];       # true
print CompareStrings qw[Hello World];       # false
print CompareStrings qw[abc abc abc];       # true
print CompareStrings qw[abc abc def];       # false
print CompareStrings qw[abc def ghi];       # false
print CompareStrings qw[a a a a a a a a];   # true
print CompareStrings qw]a a a a oops a a];  # false

__END__

```
> 1 votes

---
Tags: popularity-contest
---


title: Tips for golfing in Delphi

text:
# Question
Title: Tips for golfing in Delphi
Code-golfing is incredibly fun to do, trying to solve the given problem is one thing but the real challenge is getting your code as short as possible.

Some languages are perfect for golfing because of their short commands, sadly Delphi isn't one of them.

I'm looking for tips that are useful for golfing in Delphi.
Tips like "Use 1 letter variables" don't really count in my opinion since that is pretty obvious.

Tips I learned working with Delphi or found in other peoples answers so far are:

* Semicolon isn't always required (Example 1)
* Use `int8` or `int16` as datatype rather than integer (saves 3 or 2 characters)
* Combine string manipulations(Example 2)

### Example 1:

```
Procedure Example1(i:int16);
var x:int16;
begin
  for x:=0to 99do
    if i=1then
      inc(i)//Semicolon not allowed because of "else"
    else
     i:=i+3//No semicolon required
end;//Semicolon required

```

### Example 2

```
function WrongExample2(myString:string):string;
const
  f:string='The result of your manipulation is: %s';
begin
  myString:= StringReplace(s,'x', '_', [RfReplaceAll]);
  Result := Format(f,[myString])
end;

function CorrectExample2(myString:string):string;
const
  f:string='The result of your manipulation is: %s';
begin
  Result := Format(f,[StringReplace(s,'x', '_', [RfReplaceAll])])
end;

```

# Answer
### Group definitions by keyword

This will save you from having to retype the keyword.

```
type WD=(Su,M,Tu,W,Th,F,Sa);M=(Ja,F,Mr,Ap,My,Jn,Jl,Ag,S,O,N,D);
const A=1;B=2;
var X,Y,Z:string;

```

### Use function name instead of `Result` for holding function return value

Functions' return value can be referenced by the function name. Unless the function is required to be a particular name it will usually be shorter than `Result`.

```
function F:Int8;
begin
  F:=1
end;

```

Using the `Exit` short hand (Delphi 2009 or newer) is shorter than assigning to `Result` also:

```
function F:Int8;
begin
  Exit(1)
end;

```

### Use comma-separated variable declarations

```
procedure Z(A,B,C: string);
var A,B,C:string;

```

### Constants usually require fewer characters than variable declarations

With the exception of the above mentioned comma separated variable declarations constant declarations use fewer characters than variable declarations when initialization is taken into consideration.

```
const A=1; // True constant = 10 chars
const A:Int8=1; // Typed constant = 15 chars
var A:Int8; // Variable = 11 chars
begin
  A:=1; // + 5 chars for initialization = 16 chars

```

### Use `set` data types and their operators

If ordering isn't important, then use sets instead of arrays or lists for more concise statements. Unfortunately you are limited to a maximum of 256 elements in a set

```
+  The union of two sets
*  The intersection of two sets
-  The difference of two sets
=  Tests for identical sets
<> Tests for non-identical sets
>= Is one set a subset of another
<= Is one set a superset of another
in Test for set membership of a single element

```

The `in` operator is particularly useful when testing if a variable equals any one of possible values. Silly example using `in` and `..` (the range operator):

```
// expensive:
if ( A = 1 ) or ( A = 2 ) or ( A = 3 ) or ( A = 6 ) then ...;
if ( A > 0 ) and ( A < 4 ) or ( A = 6 ) then ...;

// better:
if A in [ 1 .. 3, 6 ] then ...;

```
> 3 votes

---
Tags: code-golf, tips
---


title: St. Patrick's Day Challenge!

text:
# Question
Title: St. Patrick's Day Challenge!
Seeing as its St. Patrick's day, I thought I would have a little challenge

Your task is to write a program draws a clover in any way possible. Each leaf has to be symmetrical, and the user has to input the number of leaves that they want on the clover. It then must be drawn. This has to be generated. You cannot just load an image or have ASCII art saved as a variable. However using modules like `turtle` to generate (and draw is included under generate) are fine.

You can use any language. This is a code-golf so the shortest answer wins.

Begin! Happy St Patrick's Day!

Just for reference, here is an example of a 3 leaf clover

Just for DavidCarraher

# Answer
## Mathematica - 106 bytes

```
c=RegionPlot[x^2+y^2<Abs@Sin[#x~ArcTan~y/2]||x>0&&y^2<.001,{x,-1,1},{y,-1,1},Frame->0>1,PlotStyle->Green]&

```

Ungolfed version:

```
c[leaves_] := (
    angle = ArcTan[x,y];
    RegionPlot[
        x^2 + y^2 < Abs[Sin[leaves*angle/2]]
        || x > 0 && y^2 < .001
      , {x,-1,1}
      , {y,-1,1}
      , Frame -> False, PlotStyle -> Green
    ]);

```

Here are the outputs for `c[3]` through `c[6]`.

At the cost of another **7 bytes** you can improve the colour (using `PlotStyle->Darker@Green` or `PlotStyle->Hue[.3,1,.7]` instead), and for another **15 bytes** you can remove some of the sampling artifacts (using an additional option `,PlotPoints->90`), giving a total of **128 bytes** for these beauties:

The braces and commes in those pictures are not produced by `c`, but just by how I output them to fit them all in one row.

Lastly, here is an attempt at somewhat neater shading. I didn't even bother golfing this down further, the option names are just too long. I'm not even sure I'm too pleased with the result, but I thought I'd post it anyway. This is **188 bytes** as it stands:

```
c=RegionPlot[x^2+y^2<Abs@Sin[(l=#)x~(a=ArcTan)~y/2]||x>0&&y^2<.001,{x,-1,1},{y,-1,1},Frame->0>1,PlotPoints->90,ColorFunction->(Hue[.3,1,.5+.2Sin[.5l#~a~#2]^8]&),ColorFunctionScaling->0>1]&

```
> 12 votes

# Answer
# C (145 126)

```
float d=2/--r,x,y=-1;for(;y<=1;y+=d,puts(""))for(x=-1;x<=1;x+=d)putchar(x*x+y*y<fabs(sin(l*atan2(x,y)))||fabs(x)<d&y>0?35:32);

```

Draws a clove in ASCII art; the function is passed the number of desired leaves and the resolution in characters. See example here: http://ideone.com/YDGN4H

Note that the result is much nicer when the horizontal resolution is doubled, at the cost of a slightly more verbose code (see http://ideone.com/RYaLz4).

**Full version:**

```
#include <math.h>
#include <stdio.h>

void clover(float l, float r)
{
    float d = 2.f / --r;
    float x, y=-1.f;
    for (; y<=1.f; y+=d){
        for (x=-1.f; x<=1.; x+=d){
            printf((x*x + y*y < fabs(sin(l * atan2(x,y))) | (fabs(x) < d & y > 0)) ? "#" : " ");
        }
        printf("\n");
    }
}

int main(int argc, char* argv[])
{
    clove(4.f, 48.f);
    return 0;
}

```
> 4 votes

---
Tags: code-golf
---


title: Cropping an image succintly

text:
# Question
Title: Cropping an image succintly
I am constantly frustrated by how complicated it is to write graphical programs that would have been only a few lines of code 20+ years ago. Since the invention of the mouse this has become even worse it seems. I was hoping someone could put me out of my misery and show the shortest code to do the following really basic "modern" operations.

The code will read in an image in any sensible format of your choosing (png, jpg, etc.), display it on the screen, allow you to choose a rectangular region *with your mouse* and then just save the selected region as an image file.

You are free to use any programming language and any library which hasn't been written especially for this competition. Both should be freely (in both senses) online. The code should be runnable in linux.

To start things off.... here is a very lightly golfed solution in **python** modified from code to Andrew Cox from https://stackoverflow.com/questions/601874/digital-image-cropping-in-python which takes **1294** **1101** characters.

```
import pygame, sys
from PIL import Image
pygame.init()

def displayImage( s, px, t):
    s.blit(px, px.get_rect())
    if t:
        pygame.draw.rect( s, (128,128,128), pygame.Rect(t[0], t[1], pygame.mouse.get_pos()[0] - t[0], pygame.mouse.get_pos()[1] - t[1]))
    pygame.display.flip()

def setup(path):
    px = pygame.image.load(path)
    s = pygame.display.set_mode( px.get_rect()[2:] )
    s.blit(px, px.get_rect())
    pygame.display.flip()
    return s, px

def mainLoop(s, px):
    t = None
    b = None
    runProgram = True
    while runProgram:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                runProgram = False
            elif event.type == pygame.MOUSEBUTTONUP:
                if not t:
                    t = event.pos
                else:
                    b = event.pos
                    runProgram = False
        displayImage(s, px, t)
    return ( t + b )

s, px = setup(sys.argv[1])
left, upper, right, lower = mainLoop(s, px)
im = Image.open(sys.argv[1])
im = im.crop(( left, upper, right, lower))
im.save(sys.argv[2])

```

I believe it is traditional to give a time limit, so I will accept the best answer in exactly one week's time.

**Current count**

* **Octave - 44 + 15 = 59** characters
* **R - 305** characters
* **Python - 343** characters
* **Java - 560** characters

# Answer
# Octave - 59 chars

```
pkg load image;imwrite(imcrop(imread(input(''))),input(''))

```

# MATLAB - 44 chars (not free, out of the contest)

```
imwrite(imcrop(imread(input(''))),input(''))

```

MATLAB seemed spot-on for this. Requires the Image Processing Toolbox (or package `image 2.0.0` from Octave Forge). Usage:

1. Write at prompt 'input-filename' (single quotes included)
2. **MATLAB:** Drag from top-left to bottom-right corner and double click the rectangle. **Octave:** Click top-left and bottom-right corner
3. Write 'output-filename' (between single quotes too)
> 2 votes

# Answer
## Java (580 560 559)

```
import java.awt.*;import javax.imageio.*;public class R extends
Frame{static java.awt.image.BufferedImage i;int
x,y,w,h;{setSize(i.getWidth(),i.getHeight());setUndecorated(0<1);show();}public static void
main(String[]a)throws Exception{i=ImageIO.read(System.in);new R();}public boolean handleEvent(Event
e){if(e.id==501){x=e.x;y=e.y;}if(e.id==502){w=e.x-x;if(w<0)x-=w=-w;h=e.y-y;if(h<0)y-=h=-h;try{ImageIO.write(i.getSubimage(x,y,w,h),"png",System.out);System.exit(0);}catch(Exception
E){}}return 0<1;}
public void paint(Graphics g){g.drawImage(i,0,0,this);}}

```

Takes input image from stdin and writes cropped image to stdout. You can drag in whichever direction you choose and it will automatically flip the coordinates as required. Input in GIF, PNG, JPEG, TIFF, probably one or two others; output in PNG.

With whitespace and a couple of comments:

```
import java.awt.*;
import javax.imageio.*;

// Extending Frame is the simplest and ugliest way of showing a GUI.
public class R extends Frame {

    // static so that we can read it in main() and save a try/catch block
    static java.awt.image.BufferedImage i;
    int x,y,w,h;

    // Instance initialiser ~= constructor without the signature
    {
        setSize(i.getWidth(),i.getHeight());
        // Don't show frames. This saves handling inset dimensions everywhere
        setUndecorated(0<1);
        show();
    }

    public static void main(String[]a) throws Exception
    {
        i=ImageIO.read(System.in);
        new R();
    }

    // This is deprecated, but it's the shortest way of handling events.
    // I learnt this trick from the Java4k Game Competition
    public boolean handleEvent(Event e) {
        if (e.id == 501) { // MOUSE_DOWN
            x=e.x;
            y=e.y;
        }
        if (e.id == 502) { // MOUSE_UP
            w = e.x - x;
            // If the second click was to the left of the first one, flip them.
            if (w < 0) x -= w = -w;
            h = e.y - y;
            // Similarly.
            if (h < 0) y -= h = -h;

            try {
                ImageIO.write(i.getSubimage(x,y,w,h), "png", System.out);
                System.exit(0);
            } catch(Exception E){
            }
        }
        return 0<1;
    }

    public void paint(Graphics g) {
        g.drawImage(i,0,0,this);
    }
}

```
> 2 votes

# Answer
**R - ~~325~~ 305 characters**

```
f=scan(,"");l=locator;r=round;i=as.raster(png::readPNG(f));n=nrow(i);m=ncol(i);x11(h=7,w=7*m/n);p=function(X){par(mar=rep(0,4));m=ncol(X);n=nrow(X);plot(c(1,m),c(1,n),xaxs="i",yaxs="i");rasterImage(X,1,1,m,n)};p(i);a=l(1);b=l(1);j=i[r(n-a$y):r(n-b$y),r(a$x):r(b$x)];png(w=ncol(j),h=nrow(j));p(j);dev.off()

```

Or fully developed:

```
f=scan(,"")
l=locator
r=round
i=as.raster(png::readPNG(f))
n=nrow(i)
m=ncol(i)
x11(h=7,w=7*m/n)
p=function(X){
par(mar=rep(0,4))
m=ncol(X)
n=nrow(X)
plot(c(1,m),c(1,n),xaxs="i",yaxs="i")
rasterImage(X,1,1,m,n)
}
p(i)
a=l(1)
b=l(1)
j=i[r(n-a$y):r(n-b$y),r(a$x):r(b$x)]
png(w=ncol(j),h=nrow(j))
p(j)
dev.off()

```

Tested on a Mac, untested on Linux but should work.
Package png needs to be installed.
At prompt, should be provided with path to png file to crop. Then when the picture appears, click twice: once for the left upper corner of selection rectangle and a second time for the right lower corner.
Create a cropped png file in working directory with default name ("Rplot001.png").
> 1 votes

# Answer
# Java (Applet), 706 698 590

By no means is Java ever considered terse, and it certainly doesn't have the most elegant handling of image display or mouse interaction, but this really isn't that bad. I'm wondering if a solution using Swing or some other library might be shorter.

```
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.imageio.*;

public class R extends java.applet.Applet{
    Scanner s=new java.util.Scanner(System.in);
    java.awt.image.BufferedImage i;
    int x,y;
    {
        try{
            i=ImageIO.read(new File(s.nextLine()));
        }catch(Exception e){}
        addMouseListener(new MouseAdapter(){
            public void mousePressed(MouseEvent e){
                x=e.getX();y=e.getY();
            }
            public void mouseReleased(MouseEvent e){
                try{
                    ImageIO.write(i.getSubimage(x,y,e.getX()-x,e.getY()-y),"png",new File(s.nextLine()));
                }catch(Exception z){}
            }
        });
    }
    public void paint(java.awt.Graphics g){
        g.drawImage(i,0,0,this);
    }
}

```
> 1 votes

# Answer
# Python/PyGame (343C)

Usage:

```
python this.py image.png result.png

```

which read from `image.png` and write to `result.png`.

```
import pygame as P
import sys
D=P.display
I=P.image
D.init()
f,g=sys.argv[1:3]
m=I.load(f)
s=D.set_mode(m.get_size())
r=k=0
c=1
while c:
 for e in P.event.get():
  t=e.type
  if t==5:x,y=e.pos;k=1
  if t==4 and k:i,j=e.pos;r=(x,y,i-x,j-y)
  if t==6:c=0
 s.blit(m,(0,0))
 if r and c:P.draw.rect(s,0,r,1)
 D.flip()
q=s.subsurface(r)
I.save(q,g)

```
> 1 votes

# Answer
I know the time limit is up, but here's how to do it in 34 characters using Bash:

```
display $1&K=$!;import $2;kill $K

```

Call it like this: 'script.sh input.png output.png'.

This uses the ImageMagick tools/library to first display the image. Then it lets you select an area to take a screenshot of using the mouse. This screenshot is effectively a crop of the image. Finally, the display is closed.
> 1 votes

---
Tags: code-golf, graphical-output
---