# Question
Title: Make a regex that matches certain binary numbers
Your task is to create a regular expression that matches *most* binary numbers with an even number of `0`s and an odd number of `1`s (e.g. `"101100011"`).

The full criteria for the regex are:

* matches 90% or more of all binary numbers between `0` and `11111111` with even number of `0`s *and* an odd number of `1`s,
* doesn't match 90% or more of all binary numbers between `0` and `11111111` with odd number of `0`s *or* an even number of `1`s,
* works in most common programming languages.

Ideally, it should be short and creative.

The input string always has a length that is greater than 1, less than infinity, and only contains `1`s and `0`s.

I will upvote any answer that seriously attempts to match the above criteria. Once the activity around this question dies down, I'll accept the highest-voted answer that is at least only 1.333... times the length of the shortest answer.

# Answer
> 6 votes
The following regex

```
(?=^1*(01*0)*1*$)^.(..)*$

```

works in many languages. It performs a perfect match for any binary of arbitrary length.

Basically, it consists of two parts which are joined via *and* by using a lookahead pattern:

* `^1*(01*0)*1*$` matches if an even number of zeros is provided.
* `^.(..)*$` tests for an odd number of digits in total.

The test run can be seen here.

# Answer
> 0 votes
### 80 characters long

```
^(?:(?(1)|(1))|0101|1010|(?:1{2})+|(?:0{2})+|0(?:1{2})+0|1(?:0{2})+1|)+(?(1)|a)$

```

Doesn't match some numbers that have an odd number over four `1`s in a row, e.g 01111101

---
Tags: binary, regular-expression
---


title: Dungeon Construction Set

text:
# Question
Title: Dungeon Construction Set
When I was a kid, I played the Intellivision game Advanced Dungeons and Dragons: Treasure of Tarmin. The 3-D graphics put you in a first-person-perspective point of view with shocking realism:

But then I got a C-64. And I was able to draw on the 40x25 character grid by cursoring around the screen, setting the color with the Ctrl key and a digit, and putting symbols anywhere I wanted *(why doesn't `bash` let me do that?)*. The character set had triangular components and solid block components. So I was able to reason through how one might generate a rendering of one's perspective in a grid through that medium.

I found the nearly-three-decades-old spec, in spiral-bound notebook paper, about "Dungeon Construction Set" this week:

*(**UPDATE**: Careful readers will notice that this doesn't quite hold together on the slanted parts. Corrected numbers are provided below.)*

Though Treasure of Tarmin was played on a grid, the walls existed only on the *edges* of grid squares. Having learned what bytes were, I realized that if I made the map out of bytes...then each square on the map could have four possible states for each of its edges:

1. Unobstructed
2. Wall
3. Door
4. Something Else?

I never did get around to writing it (until last night). I thought it might be fun for others to try.

So your task is to implement a character-mode-based maze renderer that implements my *(corrected!!)* spec...but using the technologies of 2013.

## Input

Because the spec doesn't define rendering for doors, we'll just assume the only options are wall-and-not-wall. For simplicity, your input is a map composed of lines of strings that look like this:

```
WN.. .N.. .N.. .N.. .N.E
W... .... .... ..S. ...E
W... .N.E W... .N.. ...E
W... .... .... .... ...E
W.S. ..S. ..S. ..S. ..SE

```

That would be a 5x5 map. The upper left corner (1,1) has its `W`est and `N`orth wall set. The lower right corner (5,5) has its `S`outh and `E`ast wall set.

This is considerably less fun with no map navigation. So at minimum, put your player at (1,1) facing north and offer them:

```
[F]orward, [B]ackward, turn [L]eft, turn [R]ight or [Q]uit?

```

At each step, output a 16x15 display of the first-person perspective, as defined by the notebook paper spec. To keep you from having to count, the size of flat walls at the three distances are:

```
14x13  (directly in front of you; e.g. wall is in same cell)
8x7    (one step away)
6x5    (two steps away)

```

The bounding sizes of the slanted walls are:

```
1x15   (your direct left or right; e.g. wall is in same cell)
3x13   (one step away)
1x7    (two steps away)

```

## Clarifications

* Adjacent cells may disagree about shared walls. So the south edge on a square might be a wall, while the north edge on the square to the south of it would be unobstructed. In the original design I considered this a feature: it permits interesting ideas like one-way doors...or invisible walls that only appear after you passed through them. For this simplification, follow the same rule: for navigation and rendering, pay attention only to the edge status on the cell *closest to you in the direction you are facing*.
* The view is a lot better with "shading". So for your full blocks, alternate either Unicode 2593 ▓ and 2591 ░, or use `X` and `+` if your implementation is ASCII.
* Unicode triangle characters (25E2 ◢, 25E3 ◣, 25E4 ◤, 25E5 ◥) are a bit lame for drawing this. Besides not having any shaded variants, they often stretch only the width of the character and not the full height...even in fixed width fonts. You can draw full blocks or slash characters or something of your choosing in the places I wanted diagonals. Interesting creative solutions that incorporate color and use these characters instead of shading appreciated.
* You may assume the outermost walls are set to bound the playing area, so you don't have to worry about rendering anything outside of the maze. Any walls farther away from you than the spec are ignored and just leave empty space.
* The shading of the wall you see directly in front of you if facing North at (1,1) should be DARK. Alternate shading on adjacent walls in the map, such that if all walls were present then a light wall would never abut a dark wall.
* A C-64 implementation that actually does what I originally intended...with the diagonal characters and all...will trump any other entry criterion. :-)

## Examples

For the sample map given above...

At (1,3) facing south:

```
               /
              /+
             /X+
            /XX+
           /XXX+
+++++XXXXXX+XXX+
+++++XXXXXX+XXX+
+++++XXXXXX+XXX+
+++++XXXXXX+XXX+
+++++XXXXXX+XXX+
           \XXX+
            \XX+
             \X+
              \+
               \

```

At (3,2) facing south:

```
                      /* blank line */
X             /
X            /+
X           /++
X           +++
X           +++
X           +++
X           +++
X           +++
X           +++
X           +++
X           \++
X            \+
X             \
                      /* blank line */

```

At (3,2) facing east:

```
                      /* blank line */
              /
             /X
            /XX
            XXX
+++++XXXXXX+XXX+
+++++XXXXXX+XXX+
+++++XXXXXX+XXX+
+++++XXXXXX+XXX+
+++++XXXXXX+XXX+
            XXX
            \XX
             \X
              \
                      /* blank line */

```

At (2,3) facing north:

```
               /
 ++++++++++++++X
 ++++++++++++++X
 ++++++++++++++X
 ++++++++++++++X
X++++++++++++++X
X++++++++++++++X
X++++++++++++++X
X++++++++++++++X
X++++++++++++++X
 ++++++++++++++X
 ++++++++++++++X
 ++++++++++++++X
 ++++++++++++++X
               \

```

# Answer
> 11 votes
## Commodore 64 Basic

Man, that was fun. And hard. C64 Basic is almost undebuggable, you can't even use `print` debugging because the screen is already taken for rendering the dungeon. You know you're having fun when you're writing code like `55250 goto 55110`. Dijkstra will kill me.

The program uses two colors, and diagonal characters.

Needless to say I didn't golf it. It says *code challenge* now, after all. It's **7183** bytes if you're interested.

It's slow - at default speed it takes several seconds for it to render the scene. The maximum map size is 10 by 10 but it can be changed by editing line 120.

I have developed and tested this using the **VICE** emulator. The code below is displayed in ASCII, so that means *shifted* PETSCII. *However, when inputting the map, you should use **unshifted** PETSCII*.

Screenshot:

Code:

```
10 rem c64 dungeon construction set.
20 rem enter using lowercase mode
99 rem DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
100 rem initialisation
110 poke 53272,21
115 poke 53280,0
120 dim m%(10,10)
121 dim di$(3),wa$(1),ma%(2,2)
122 di$(0)="north"
123 di$(1)="east "
124 di$(2)="south"
125 di$(3)="west "
126 wa$(1)="-wall"
127 wa$(0)="     "

130 x=0:y=0:di=0:xs=0:ys=0:wa=0
134 rem read map
135 print "input map"
140 l$="":input l$
150 if len(l$)=0 goto 250
160 cz=0
170 for i=1 to len(l$)
180   c$=mid$(l$,i,1)
190   if c$="n" then cz=cz or 8
200   if c$="e" then cz=cz or 4
205   if c$="s" then cz=cz or 2
210   if c$="w" then cz=cz or 1
215   if c$=" " then m%(x,y)=cz:cz=0:x=x+1
220   if x>=xs then xs=x
225 next
230 m%(x,y)=cz:x=0:y=y+1
240 goto 140
250 rem come from 150
260 print chr$(147)
265 ys=y:xs=xs+1
270 x=0:y=0

500 rem loop
510 gosub 1000: rem status
515 gosub 2000: rem render
520 gosub 55000: rem input
530 goto 500

1000 rem display current (x,y) value
1010 sx=5
1020 sy=17
1030 sl$="    "
1035 sw=14
1040 gosub 63900
1050 cz=m%(x,y)
1060 sx=5:sl$=".":if cz and 8 then sl$="n"
1065 gosub 63900
1070 sx=6:sl$=".":if cz and 4 then sl$="e"
1075 gosub 63900
1080 sx=7:sl$=".":if cz and 2 then sl$="s"
1085 gosub 63900
1090 sx=8:sl$=".":if cz and 1 then sl$="w"
1095 gosub 63900
1100 return

2000 rem render dungeon
2010 rem DDDDDDDDDDDDDD
2020 rem clear area
2030 sw=14:sz=32
2040 for sy=0 to 15
2050   for sx=0 to 16
2060      gosub 63950
2070   next
2080 next
2090 rem find cells / reorient sw
2100 rem store in ma% - we're at (0,1)
2110 sx=x:sy=y
2113 co=di+x+y and 1
2115 for ty=0 to 2
2120    gosub 59800:rem left/right sx/sy
2125    ma%(1,ty)=0
2126    if sx>=0 and sy>=0 and sx<xs and sy<ys then ma%(1,ty)=m%(sx,sy)
2130    ma%(0,ty)=rl
2140    ma%(2,ty)=rr
2150    gosub 59900:rem advance
2160 next
2170 rem draw back walls
2180 sa=ma%(1,2):gosub 59700
2190 if rf=0 goto 2245
2195 sw=14-11*co:sz=160
2200 for sy=5 to 9
2210    for sx=5 to 10
2220       gosub 63950
2230    next
2240 next
2245 sw=3:if co=1 then sw=14
2250 for de=0 to 2 step 2
2260    sa=ma%(de,2):gosub 59700
2270    if rf=0 goto 2350
2280    for sx=de*5.5 to 4+de*5.5
2290       for sy=5 to 9
2300          gosub 63950
2310       next
2340    next
2350 next
2360 rem 1,2 left wall
2370 sa=ma%(1,2):gosub 59700
2380 if rl=0 goto 2430
2390 sx=4:sz=160
2400 for sy=5 to 9:gosub 63950:next
2410 sy=4:sz=223:gosub 63950
2420 sy=10:sz=105:gosub 63950
2430 rem 1,2 right wall
2440 if rr=0 goto 2490
2450 sx=11:sz=160
2460 for sy=5 to 9:gosub 63950:next
2470 sy=4:sz=233:gosub 63950
2480 sy=10:sz=95:gosub 63950
2490 rem 1,1 back wall
2500 sa=ma%(1,1):gosub 59700
2510 sz=160
2520 sw=14:if co=1 then sw=3
2520 if rf=0 goto 2580
2530 for sy=4 to 10
2540    for sx=4 to 11
2550       gosub 63950
2560    next
2570 next
2580 rem (0-2),1 back walls
2590 sw=14:if co=1 then sw=3
2600 for de=0 to 2 step 2
2610    sa=ma%(de,1):gosub 59700
2620    if rf=0 goto 2680
2630    for sx=de*6 to 3+de*6
2640       for sy=4 to 10
2650          gosub 63950
2660       next
2670    next
2680 next
2690 rem 1,1 left side wall
2700 sw=14:if co=1 then sw=3
2710 sa=ma%(1,1):gosub 59700
2720 if rl=0 goto 2760
2730 for sx=1 to 3
2735   sy=sx:sz=223:gosub 63950
2736   sy=14-sx:sz=105:gosub 63950
2737   sz=160
2740   for sy=1+sx to 13-sx:gosub 63950:next
2750 next
2760 rem 1,1 right side wall
2770 if rr=0 goto 2850
2780 for qx=1 to 3
2790   sx=15-qx
2800   sy=qx:sz=233:gosub 63950
2810   sy=14-qx:sz=95:gosub 63950
2820   sz=160
2830   for sy=1+qx to 13-qx:gosub 63950:next
2840 next
2850 rem 0,1 back wall
2860 sa=ma%(1,0):gosub 59700
2870 if rf=0 goto 2930
2880 for sy=1 to 13
2890   for sx=1 to 14
2900     gosub 63950
2910   next
2920 next
2930 rem (0,2)-0 back walls
2940 sw=3:if co=1 then sw=14
2950 for de=0 to 2 step 2
2960   sa=ma%(de,0):gosub 59700
2970   if rf=0 goto 3000
2980   sx=de*7.5
2990   for sy=1 to 13:gosub 63950:next
3000 next
3010 rem (1,0) left side wall
3020 sa=ma%(1,0):gosub 59700
3030 if rl=0 goto 3080
3040 sx=0:sy=0:sz=223:gosub 63950
3050 sy=14:sz=105:gosub 63950
3060 sz=160
3070 for sy=1 to 13:gosub 63950:next
3080 rem (1,0) right side wall
3085 if rr=0 goto 3130
3090 sx=15:sy=0:sz=233:gosub 63950
3100 sy=14:sz=95:gosub 63950
3110 sz=160
3120 for sy=1 to 13:gosub 63950:next
3130 rem done
3140 return

55000 rem ask for prompt & handle input
55010 sx=0:sy=20:gosub 63850
55013 print "at";x+1;y+1;"going ";di$(di);" size";xs;ys;wa$(wa)
55020 print "{f}rwd {b}kwd {l}eft {r}ight {q}uit"
55030 input c$
55040 if c$="q" goto 63999
55050 if c$="f" then dm=1:goto 55100
55060 if c$="b" then dm=-1:goto 55100
55070 if c$="l" then di=(di-1)and 3
55080 if c$="r" then di=(di+1)and 3
55090 return
55100 goto 55200:rem check walls
55110 if di=0 then y=y-dm
55120 if di=1 then x=x+dm
55130 if di=2 then y=y+dm
55140 if di=3 then x=x-dm
55145 wa=0
55146 if y>=ys then y=0
55147 if y<0   then y=ys-1
55148 if x>=xs then x=0
55149 if x<0   then x=xs-1
55150 return
55200 rem check walls
55205 cz=m%(x,y)
55207 if dm=-1 goto 55280
55210 if (di=0) and (cz and 8) goto 55260
55220 if (di=1) and (cz and 4) goto 55260
55230 if (di=2) and (cz and 2) goto 55260
55240 if (di=3) and (cz and 1) goto 55260
55250 goto 55110
55260 wa=1
55270 return : rem wall in the way
55280 rem backward
55290 if (di=2) and (cz and 8) goto 55260
55300 if (di=3) and (cz and 4) goto 55260
55310 if (di=0) and (cz and 2) goto 55260
55320 if (di=1) and (cz and 1) goto 55260
55330 goto 55110

59700 rem return front/back/left/right
59710 rem given sa and d
59720 sn=0:if sa and 8 then sn=1
59725 se=0:if sa and 4 then se=1
59730 ss=0:if sa and 2 then ss=1
59735 zw=0:if sa and 1 then zw=1
59740 if di=0 then rf=sn:rr=se:rb=ss:rl=zw
59745 if di=1 then rf=se:rr=ss:rb=zw:rl=sn
59750 if di=2 then rf=ss:rr=zw:rb=sn:rl=se
59755 if di=3 then rf=zw:rr=sn:rb=se:rl=ss
59760 return

59800 rem return left/right from sx/sy/d
59810 if di=0 then ly=sy:ry=sy:lx=sx-1:rx=sx+1
59820 if di=1 then lx=sx:rx=sx:ly=sy-1:ry=sy+1
59830 if di=2 then ly=sy:ry=sy:lx=sx+1:rx=sx-1
59840 if di=3 then lx=sx:rx=sx:ly=sy+1:ry=sy-1
59850 rl=0:rr=0
59860 if lx<0 or lx>=xs or ly<0 or ly>=ys goto 59880
59870 rl=m%(lx,ly)
59880 if rx<0 or rx>=xs or ry<0 or ry>=ys goto 59895
59890 rr=m%(rx,ry)
59895 return

59900 rem step forward
59910 if di=0 then sy=sy-1:rem N
59920 if di=1 then sx=sx+1:rem E
59930 if di=2 then sy=sy+1:rem S
59940 if di=3 then sx=sx-1:rem W
59950 return

63850 rem set cursor position
63851 rem sx=x sy=y
63860 poke 781,sy
63870 poke 782,sx
63880 poke 783,0
63890 sys 65520
63895 return

63900 rem write str to screen
63901 rem sl$ = string
63910 gosub 63850
63920 print sl$;
63930 return

63950 rem write chr to screen
63951 rem sx = x coordinate
63952 rem sy = y coordinate
63953 rem sz = character code
63954 rem sw = color
63950 sv=sx+sy*40
63960 poke 1024+sv,sz
63970 poke 55296+sv,sw
63980 return

63998 rem quit program
63999 print chr$(147):end

```

Tape image: download here.

The examples:

# Answer
> 10 votes
> *(why doesn't `bash` let me do that?)*

I just had to now.

## Bash, 12743 chars

```
#!/bin/bash
IFS=
declare -a term
typeset -i term[0] term[1]
IFS=' ' read -a term <<< `stty size`
front[0]='\e[2;2H██████████████
\e[3;2H██████████████
\e[4;2H██████████████
\e[5;2H██████████████
\e[6;2H██████████████
\e[7;2H██████████████
\e[8;2H██████████████
\e[9;2H██████████████
\e[10;2H██████████████
\e[11;2H██████████████
\e[12;2H██████████████
\e[13;2H██████████████
\e[14;2H██████████████'
front[1]='\e[5;5H████████
\e[6;5H████████
\e[7;5H████████
\e[8;5H████████
\e[9;5H████████
\e[10;5H████████
\e[11;5H████████'
front[2]='\e[6;6H██████
\e[7;6H██████
\e[8;6H██████
\e[9;6H██████
\e[10;6H██████'
lfront[0]='\e[2;1H█
\e[3;1H█
\e[4;1H█
\e[5;1H█
\e[6;1H█
\e[7;1H█
\e[8;1H█
\e[9;1H█
\e[10;1H█
\e[11;1H█
\e[12;1H█
\e[13;1H█
\e[14;1H█'
lfront[1]='\e[5;1H████
\e[6;1H████
\e[7;1H████
\e[8;1H████
\e[9;1H████
\e[10;1H████
\e[11;1H████'
lfront[2]='\e[6;1H█████
\e[7;1H█████
\e[8;1H█████
\e[9;1H█████
\e[10;1H█████'
rfront[0]='\e[2;16H█
\e[3;16H█
\e[4;16H█
\e[5;16H█
\e[6;16H█
\e[7;16H█
\e[8;16H█
\e[9;16H█
\e[10;16H█
\e[11;16H█
\e[12;16H█
\e[13;16H█
\e[14;16H█'
rfront[1]='\e[5;13H████
\e[6;13H████
\e[7;13H████
\e[8;13H████
\e[9;13H████
\e[10;13H████
\e[11;13H████'
rfront[2]='\e[6;12H█████
\e[7;12H█████
\e[8;12H█████
\e[9;12H█████
\e[10;12H█████'
left[0]='\e[1;1H▙
\e[2;1H█
\e[3;1H█
\e[4;1H█
\e[5;1H█
\e[6;1H█
\e[7;1H█
\e[8;1H█
\e[9;1H█
\e[10;1H█
\e[11;1H█
\e[12;1H█
\e[13;1H█
\e[14;1H█
\e[15;1H▛'
left[1]='\e[2;2H▙
\e[3;2H█▙
\e[4;2H██▙
\e[5;2H███
\e[6;2H███
\e[7;2H███
\e[8;2H███
\e[9;2H███
\e[10;2H███
\e[11;2H███
\e[12;2H██▛
\e[13;2H█▛
\e[14;2H▛'
left[2]='\e[5;5H▙
\e[6;5H█
\e[7;5H█
\e[8;5H█
\e[9;5H█
\e[10;5H█
\e[11;5H▛'
right[0]='\e[1;16H▟
\e[2;16H█
\e[3;16H█
\e[4;16H█
\e[5;16H█
\e[6;16H█
\e[7;16H█
\e[8;16H█
\e[9;16H█
\e[10;16H█
\e[11;16H█
\e[12;16H█
\e[13;16H█
\e[14;16H█
\e[15;16H▜'
right[1]='\e[2;13H  ▟
\e[3;13H ▟█
\e[4;13H▟██
\e[5;13H███
\e[6;13H███
\e[7;13H███
\e[8;13H███
\e[9;13H███
\e[10;13H███
\e[11;13H███
\e[12;13H▜██
\e[13;13H ▜█
\e[14;13H  ▜'
right[2]='\e[5;12H▟
\e[6;12H█
\e[7;12H█
\e[8;12H█
\e[9;12H█
\e[10;12H█
\e[11;12H▜'

echo -e "\e[2J"

# Read map
typeset -i cout
cout=0
echo "Please input your map!"
echo "Please input the next row (or leave it blank if you're finished!)"
read input

declare -A map

typeset -i xlen ylen
ylen=0

until [ -z $input ]
do
    IFS=' ' read -a inputmap <<< "$input"
    xlen=${#inputmap[*]}
    let ylen++
    for index in "${!inputmap[@]}"
    do
        typeset -i map[$index,$cout]
        map[$index,$cout]=0
        el=${inputmap[index]}
        if [[ $el == W??? ]]
        then
            let "map[$index,$cout]|=1"
        fi
        if [[ $el == ?N?? ]]
        then
            let "map[$index,$cout]|=2"
        fi
        if [[ $el == ??S? ]]
        then
            let "map[$index,$cout]|=4"
        fi
        if [[ $el == ???E ]]
        then
            let "map[$index,$cout]|=8"
        fi
    done
    echo "Please input the next row (or leave it blank if you're finished!)"
    read input
    cout+=1
done

echo -ne "\e[2J"

typeset -i dir x y
dir=0
x=0
y=0

move() {
    if ((dir == 0)) && ( ((${map[$x,$y]} & 2)) || ((y == 0)) )
    then
        return 1
    elif ((dir == 1)) && ( ((${map[$x,$y]} & 8)) || (($x == $xlen)) )
    then
        return 1
    elif ((dir == 2)) && ( ((${map[$x,$y]} & 4)) || ((y == $ylen)) )
    then
        return 1
    elif ((dir == 3)) && ( ((${map[$x,$y]} & 1)) || ((x == 0)) )
    then
        return 1
    fi
    x=$1
    y=$2
}

input=

until [[ $input == [qQ] ]]
do
    if [[ $input == [DlL] ]]
    then
        let dir-=1
        if (( dir == -1 ))
        then
            dir=3
        fi
    elif [[ $input == [CrR] ]]
    then
        let dir+=1
        if (( dir == 4 ))
        then
            dir=0
        fi
    elif [[ $input == [AfF] ]]
    then
        if (( dir == 0 ))
        then
            move $x $(( y-1 ))
        elif (( dir == 1 ))
        then
            move $(( x+1 )) $y
        elif (( dir == 2 ))
        then
            move $x $(( y+1 ))
        elif (( dir == 3 ))
        then
            move $(( x-1 )) $y
        fi
    elif [[ $input == [bB] ]]
    then
        if (( dir == 0 ))
        then
            dir=2
            move $x $(( y+1 ))
            dir=0
        elif (( dir == 1 ))
        then
            dir=3
            move $(( x-1 )) $y
            dir=1
        elif (( dir == 2 ))
        then
            dir=0
            move $x $(( y-1 ))
            dir=2
        elif (( dir == 3 ))
        then
            dir=1
            move $(( x+1 )) $y
            dir=3
        fi
    fi
    echo -ne "\e[2J"
    echo -ne "\e[16;1Hd=$dir; x=$x; y=$y\e[48;5;29m"
    for (( y2=1; y2 <= 15; y2++ ))
    do
        echo -ne "\e[$y2;16H\e[1K"
    done
    if (( dir == 0 ))
    then
        for (( y2=(y-2); y2 <= y; y2++ ))
        do
            if (( y2 < 0 )); then continue; fi
            let i=y-y2
            if (( x > 0 )) && (( ${map[$((x-1)),$y2]} & 2 ))
            then
                if (( ((x-1) + y2) & 1 ))
                then
                    echo -ne "\e[38;5;40m"
                else
                    echo -ne "\e[38;5;28m"
                fi
                echo -ne ${lfront[$i]}
            fi
            if (( (x+1) < xlen )) && (( ${map[$((x+1)),$y2]} & 2 ))
            then
                if (( ((x-1) + y2) & 1 ))
                then
                    echo -ne "\e[38;5;40m"
                else
                    echo -ne "\e[38;5;28m"
                fi
                echo -ne ${rfront[$i]}
            fi
            if (( ${map[$x,$y2]} & 1 ))
            then
                if (( (x + y2) & 1 ))
                then
                    echo -ne "\e[38;5;28m"
                else
                    echo -ne "\e[38;5;40m"
                fi
                echo -ne ${left[$i]}
            fi
            if (( ${map[$x,$y2]} & 8 ))
            then
                if (( (x + y2) & 1 ))
                then
                    echo -ne "\e[38;5;28m"
                else
                    echo -ne "\e[38;5;40m"
                fi
                echo -ne ${right[$i]}
            fi
            if (( ${map[$x,$y2]} & 2 ))
            then
                if (( (x + y2) & 1 ))
                then
                    echo -ne "\e[38;5;40m"
                else
                    echo -ne "\e[38;5;28m"
                fi
                echo -ne ${front[$i]}
            fi
        done
    elif (( dir == 1 ))
    then
        for (( x2=x+2; x2 >= x; x2-- ))
        do
            if (( x2 > 16 )) || (( x2 >= xlen )); then continue; fi
            let i=x2-x
            if (( y > 0 )) && (( ${map[$x2,$((y-1))]} & 8 ))
            then
                if (( (x2 + (y-1)) & 1 ))
                then
                    echo -ne "\e[38;5;28m"
                else
                    echo -ne "\e[38;5;40m"
                fi
                echo -ne ${lfront[$i]}
            fi
            if (( (y+1) < ylen )) && (( ${map[$x2,$((y+1))]} & 8 ))
            then
                if (( (x2 + (y-1)) & 1 ))
                then
                    echo -ne "\e[38;5;28m"
                else
                    echo -ne "\e[38;5;40m"
                fi
                echo -ne ${rfront[$i]}
            fi
            if (( ${map[$x2,$y]} & 2 ))
            then
                if (( (x2 + y) & 1 ))
                then
                    echo -ne "\e[38;5;40m"
                else
                    echo -ne "\e[38;5;28m"
                fi
                echo -ne ${left[$i]}
            fi
            if (( ${map[$x2,$y]} & 4 ))
            then
                if (( (x2 + y) & 1 ))
                then
                    echo -ne "\e[38;5;40m"
                else
                    echo -ne "\e[38;5;28m"
                fi
                echo -ne ${right[$i]}
            fi
            if (( ${map[$x2,$y]} & 8 ))
            then
                if (( (x2 + y) & 1 ))
                then
                    echo -ne "\e[38;5;28m"
                else
                    echo -ne "\e[38;5;40m"
                fi
                echo -ne ${front[$i]}
            fi
        done
    elif (( dir == 2 ))
    then
        for (( y2=(y+2); y2 >= y; y2-- ))
        do
            if (( y2 > 15 )) || (( y2 >= ylen )); then continue; fi
            let i=y2-y
            if (( x > 0 )) && (( ${map[$((x-1)),$y2]} & 4 ))
            then
                if (( ((x-1) + y2) & 1 ))
                then
                    echo -ne "\e[38;5;40m"
                else
                    echo -ne "\e[38;5;28m"
                fi
                echo -ne ${rfront[$i]}
            fi
            if (( (x+1) < xlen )) && (( ${map[$((x+1)),$y2]} & 4 ))
            then
                if (( ((x+1) + y2) & 1 ))
                then
                    echo -ne "\e[38;5;40m"
                else
                    echo -ne "\e[38;5;28m"
                fi
                echo -ne ${lfront[$i]}
            fi
            if (( ${map[$x,$y2]} & 8 ))
            then
                if (( (x + y2) & 1 ))
                then
                    echo -ne "\e[38;5;28m"
                else
                    echo -ne "\e[38;5;40m"
                fi
                echo -ne ${left[$i]}
            fi
            if (( ${map[$x,$y2]} & 1 ))
            then
                if (( (x + y2) & 1 ))
                then
                    echo -ne "\e[38;5;28m"
                else
                    echo -ne "\e[38;5;40m"
                fi
                echo -ne ${right[$i]}
            fi
            if (( ${map[$x,$y2]} & 4 ))
            then
                if (( (x + y2) & 1 ))
                then
                    echo -ne "\e[38;5;40m"
                else
                    echo -ne "\e[38;5;28m"
                fi
                echo -ne ${front[$i]}
            fi
        done
    elif (( dir == 3 ))
    then
        for (( x2=(x-2); x2 <= x; x2++ ))
        do
            if (( x2 < 0 )); then continue; fi
            let i=x-x2
            if (( y > 0 )) && (( ${map[$x2,$((y-1))]} & 1 ))
            then
                if (( (x2 + (y-1)) & 1 ))
                then
                    echo -ne "\e[38;5;28m"
                else
                    echo -ne "\e[38;5;40m"
                fi
                echo -ne ${rfront[$i]}
            fi
            if (( (y+1) < ylen )) && (( ${map[$x2,$((y+1))]} & 1 ))
            then
                if (( (x2 + (y+1)) & 1 ))
                then
                    echo -ne "\e[38;5;28m"
                else
                    echo -ne "\e[38;5;40m"
                fi
                echo -ne ${lfront[$i]}
            fi
            if (( ${map[$x2,$y]} & 4 ))
            then
                if (( (x2 + y) & 1 ))
                then
                    echo -ne "\e[38;5;40m"
                else
                    echo -ne "\e[38;5;28m"
                fi
                echo -ne ${left[$i]}
            fi
            if (( ${map[$x2,$y]} & 2 ))
            then
                if (( (x2 + y) & 1 ))
                then
                    echo -ne "\e[38;5;40m"
                else
                    echo -ne "\e[38;5;28m"
                fi
                echo -ne ${right[$i]}
            fi
            if (( ${map[$x2,$y]} & 1 ))
            then
                if (( (x2 + y) & 1 ))
                then
                    echo -ne "\e[38;5;28m"
                else
                    echo -ne "\e[38;5;40m"
                fi
                echo -ne ${front[$i]}
            fi
        done
    fi
    echo -ne "\e[0m"
    echo -ne "\e[${term[0]};0H[F]orward, [B]ackward, turn [L]eft, turn [R]ight or [Q]uit?"
    read -n 1 input
done

echo

```

Please keep in mind that this is pretty much the first thing I did with `bash` that was more than just piping a few commands together. It would probably be reducable by quite a lot if I didn't hardcode all the walls, but it seemed easier. It's got no consistency whatsoever. The byte format for each square is picked in a horrible way. But it works.

I even added support for movement through the arrow keys :)

These are some screenshots for the sample input ( Note that my map starts at (0|0) ):

Apart from the fourth one they all look like the sample ones as well (see my comment on the OP).

These screenshots were taken on urxvt v9.15 with 256 color support, it probably would look quite crap on a 88 color terminal, and terminals without unicode support don't work at all. The font I used was Source Code Pro by Adobe.

# Answer
> 3 votes
Here's my version, in Python 3. It's something like 3k characters and could get a bit smaller with a little effort (there's lots of white space that could be removed, to start with).

It currently uses `+X/\` as its drawing characters, but it is set up to draw with Unicode characters if you have a fixed width font that will render them properly. It supports using separate tiles for the angled parts of the differently collored walls, though I'm not using that feature. It also lets you provide ceiling, floor and "distant" tiles, and you can use different ones for when the player is facing east or west vs north or south. Alas this never looked very good, so probably all of these should be blank (or something solid, like ).

Alas, on my Windows 7 system I had a horrible time trying to find a monospaced font with the full set of block characters (e.g.  and ). Most of the ones I found could not be made available in the `cmd` console for some reason (perhaps because they're not perfectly monospaced?). If you think your console is more functional, try using the alternate character set that I've commented out near the top of the file, which doesn't look too bad even with just two colors. It has filled in ceilings and floors and mostly transparent walls.

The code:

```
from itertools import product as p
r=range
cs=r"+X//\\//\\      " #" ░▛▛▜▜▟▟▙▙██████"
shapes=[(1,[(x,y,0)for x,y in p(r(5),r(5,10))]),
        (0,[(x,y,0)for x,y in p(r(5,11),r(5,10))]),
        (1,[(x,y,0)for x,y in p(r(11,16),r(5,10))]),
        (1,[(4,4,4),(4,10,6)]+[(4,y,0)for y in r(5,10)]),
        (1,[(11,4,2),(11,10,8)]+[(11,y,0)for y in r(5,10)]),
        (0,[(x,y,0)for x,y in p(r(4),r(4,11))]),
        (1,[(x,y,0)for x,y in p(r(4,12),r(4,11))]),
        (0,[(x,y,0)for x,y in p(r(12,16),r(4,11))]),
        (0,[(1,1,4),(2,2,4),(3,3,4),(1,13,6),(2,12,6),(3,11,6)]+
           [(x,y,0)for x,y in p(r(1,4),r(2,14)) if x<y<14-x]),
        (0,[(14,1,2),(13,2,2),(12,3,2),(14,13,8),(13,12,8),(12,11,8)]+
           [(x,y,0)for x,y in p(r(12,15),r(2,14)) if 15-x<y<x-1]),
        (1,[(0,y,0) for y in r(1,14)]),
        (0,[(x,y,0) for x,y in p(r(1,15),r(1,14))]),
        (1,[(15,y,0) for y in r(1,14)]),
        (1,[(0,0,4),(0,14,6)]+[(0,y,0)for y in r(1,14)]),
        (1,[(15,0,2),(15,14,8)]+[(15,y,0) for y in r(1,14)])]
def rr(s):
    for r in s:print("".join(r))
def dw(s,a,p,d):
    for i,r in enumerate(s):r[:]=cs[10+i//5*2+d%2]*16
    for w,(pl,sh) in zip(a,shapes):
        if w:
            for x,y,c in sh:
                s[y][x]=cs[c+(p+d+pl)%2]
dx=[1,0,-1,0]
def ga(x,y,d,m):
    fx=dx[d];fy=lx=dx[d-1];ly=dx[d-2]
    return [m[y+2*fy+ly][x+2*fx+lx][d],m[y+2*fy][x+2*fx][d],
            m[y+2*fy-ly][x+2*fx-lx][d],m[y+2*fy][x+2*fx][d-1],
            m[y+2*fy][x+2*fx][d-3],m[y+fy+ly][x+fx+lx][d],
            m[y+fy][x+fx][d],m[y+fy-ly][x+fx-lx][d],
            m[y+fy][x+fx][d-1],m[y+fy][x+fx][d-3],
            m[y+ly][x+lx][d],m[y][x][d],
            m[y-ly][x-lx][d],m[y][x][d-1],m[y][x][d-3]]
def rd():
    l=input();
    while l!="":
        if "\n" in l:yield from l.split("\n")
        else:yield l
        l=input()
def rm():
    m=[[[d in s for d in"ESWN"]for s in r.strip().split()]+[[1]*4]*2
       for r in rd()]
    return m+[[[1]*4 for _ in m[0]]]*2
def cl():print("\n"*30)
def gl():
    print("Enter map, followed by a blank line.")
    x=y=0;d=3;m=rm();mv="";s=[[""]*16 for _ in r(15)]
    while True:
        cl();dw(s,ga(x,y,d,m),x+y,d);rr(s)
        print("X:",x+1,"Y:",y+1,"Facing:","ESWN"[d])
        if mv:print("Last move:",mv)
        mv=input("[FBLRQ]? ").upper()
        if mv=="F":
            if not m[y][x][d]:x+=dx[d];y+=dx[d-1]
            else:mv+=" (Blocked)"
        elif mv=="B":
            if not m[y][x][d-2]:x+=dx[d-2];y+=dx[d-3]
            else:mv+=" (Blocked)"
        elif mv=="L":d=(d-1)%4
        elif mv=="R":d=(d+1)%4
        elif mv=="Q":break
        else:mv="I didn't understand %r."%mv
gl()

```

The character set is specified near the top of the file. The order of the characters are:

1. even parity wall
2. odd parity wall
3. even parity top right wall angle (e.g. `/` with a wall below it)
4. odd parity top right wall angle
5. even parity top left wall angle
6. odd parity top left wall angle
7. even parity bottom right wall angle
8. odd parity bottom right wall angle
9. even parity bottom left wall angle
10. odd parity bottom left wall angle
11. ceiling facing E/W
12. ceiling facing N/S
13. horizon facing E/W (the middle of the screen if there are no walls)
14. horizon facing N/S
15. floor facing E/W
16. floor facing N/S

There are 15 walls that might need to be rendered by the game, in a pattern like this (with `V` indicating the player's position and arc of view):

```
_ _ _
_|_|_
_|_|_
 |V|

```

The tiles used by the 15 walls are defined in the `shapes` list. It's a list of 2-tuples. The first value of the tuple indicates the "parity" of the wall, with `0` indicating that it should be drawn with the same characters as a wall directly in front of the character and a `1` indicating that it should be the alternate pattern (e.g. `+` vs `X`). The second value is a list of `x,y,t` tuples indicating the screen coordinates and tile index of one pixel (walls being rendered with odd parity will have `1` added to each of these indexes). The shapes are ordered by distance, so the first three represent the perpendicular walls two tiles ahead of the character, followed by the two parallel walls two tiles ahead, and so on.

The functions are:

* `rr`: "render" the screen (by printing the tiles in the screen buffer).
* `dw`: "draw walls" to a provided screen buffer. This uses the painters algorithm, so the most distant walls are drawn first and may get covered up by closer ones.
* `ga`: "get area" returns a list of boolean values indicating which walls are opaque for a given map position and facing.
* `rd`: "read", a generator that reads the map, yielding the lines. This is only needed because IDLE's console does weird stuff when you paste multi-line inputs rather than entering one line at a time.
* `rm`: "read map", parses the map into a nested list of booleans, indexed by `m[y][x][d]` (with `d=0` being East and `d=1` being South). It also adds two rows and two columns of padding squares, to avoid index errors in the other code.
* `cl`: "clear" the output (by writing enough newlines to scroll the old view off the top of the most consoles).
* `gl`: "game loop", where the input is gathered and the above stuff gets called.

A few "screenshots":

The starting position:

```
\
+XXXXXXXXXXXXXX+
+XXXXXXXXXXXXXX+
+XXXXXXXXXXXXXX+
+XXXXXXXXXXXXXX+
+XXXXXXXXXXXXXX+
+XXXXXXXXXXXXXX+
+XXXXXXXXXXXXXX+
+XXXXXXXXXXXXXX+
+XXXXXXXXXXXXXX+
+XXXXXXXXXXXXXX+
+XXXXXXXXXXXXXX+
+XXXXXXXXXXXXXX+
+XXXXXXXXXXXXXX+
/
X: 1 Y: 1 Facing: N
[FBLRQ]?

```

Looking along the north wall:

```
\
X\
X+\
X++\
X+++\
X+++X
X+++X
X+++X
X+++X
X+++X
X+++/
X++/
X+/
X/
/
X: 1 Y: 1 Facing: E
Last move: R
[FBLRQ]?

```

A couple of shots matching your examples (note, the blank first lines are being chopped off by Stack Overflow, they're in the program output):

```
X             /
X            /+
X           /++
X           +++
X           +++
X           +++
X           +++
X           +++
X           +++
X           +++
X           \++
X            \+
X             \

X: 3 Y: 2 Facing: S
Last move: F
[FBLRQ]?

```

And:

```
              /
             /X
            /XX
            XXX
+++++XXXXXX+XXX+
+++++XXXXXX+XXX+
+++++XXXXXX+XXX+
+++++XXXXXX+XXX+
+++++XXXXXX+XXX+
            XXX
            \XX
             \X
              \

X: 3 Y: 2 Facing: E
Last move: L
[FBLRQ]?

```

Here's one of the stranger views in the supplied map, as the wall parallel to our view is the same color as the perpendicular wall sticking out behind it:

```
 \
 +\
 ++\
++++        ++++
++++        ++++
++++        ++++
++++        ++++
++++        ++++
++++        ++++
++++        ++++
 ++/
 +/
 /

X: 3 Y: 4 Facing: N
Last move: R
[FBLRQ]?

```

Here's what the area of last shot would look like from above:

```
_   _
 |
  V

```

---
Tags: code-challenge, maze
---


title: Make a Voronoi diagram (ASCII variant)

text:
# Question
Title: Make a Voronoi diagram (ASCII variant)
Suppose you're given some distinct uppercase letters scattered in a rectangular array of otherwise-blank cells. Each cell in the array *belongs* to the letter *nearest* to it, defined as the letter reachable in the smallest number of horizontal and/or vertical steps -- no diagonal steps. (If a cell is equidistant from two or more nearest letters, it belongs to whichever of those letters is first in alphabetical order. A cell with an uppercase letter in it belongs to that letter.) *Boundary*-cells are those that are horizontally or vertically adjacent to one or more cells that do not belong to the letter that they themselves belong to.

**Write a procedure subprogram** with the following behavior, producing a kind of Voronoi diagram ...

**Input**: Any ASCII string composed only of dots, uppercase letters, and newlines, such that when printed it displays a rectangular array of the kind described above, with dots acting as blanks.

**Output**: A printout of the input string with each blank boundary-cell replaced by the lowercase version of the letter it belongs to. (The subprogram does the printing.)

**Example 1**

Input:

```
......B..
.........
...A.....
.........
.......D.
.........
.C.......
.....E...
.........

```

Output:

```
...ab.B..
....ab.bb
...A.abdd
aa...ad..
cca.ad.D.
..caeed..
.C.ce.edd
..ce.E.ee
..ce.....

```

A sketch highlighting the boundaries:

**Example 2**

Input:

```
............................U...........
......T.................................
........................................
.....................G..................
..R.......S..........F.D.E............I.
.........................H..............
.....YW.Z...............................
......X.................................
........................................
........................................
......MN...........V....................
......PQ................................
........................................
.............L...............J..........
........................................
........................................
....C...........K.......................
........................................
..................................A.....
...........B............................

```

Output:

```
..rt.....ts...sg......gduu..U.....ui....
..rt..T..ts...sg......gddeu......ui.....
...rt...ts....sg......gddeeu....ui......
....rttts.....sggggggGgdde.euuuui.......
..R.rywss.S....sfffffFdDdEeeeeeei.....I.
...ryywwzs.....sf....fddhHhhhhhhhi......
..ryyYWwZzs..sssffff.fddh.......hi......
..rxxxXxzzs.sllvvvvvffddh....hhhhi......
rrrxxxxnzzssl.lv....vfddh...hjjjjii.....
mmmmmmmnnnnnl.lv.....vvdh..hj....jai....
mmmmmmMNnnnnl.lv...V...vvhhj.....jaai...
ppppppPQqqql...lv.......vhj......ja.ai..
ppppp.pq.ql....lkv.....vjj.......ja..aii
cccccppqql...L.lkkv...vj.....J...ja...aa
.....cpqqlll..lk..kvvvvj........ja......
......cccbbbllk....kkkkj.......ja.......
....C...cb..bk..K......kj.....ja........
.......cb....bk........kjjjjjja.........
......cb......bk.......kaaaaaa....A.....
.....cb....B...bk......ka...............

```

Color enhancement:

# Answer
> 5 votes
### GolfScript, 138 144 137 characters

```
:^n%,,{{^n/1$=2$>1<.'.'={;{@~@+@@+\{^3$?^<n/),\,@-abs@@-abs+99*+}++^'.
'-\$1<{32+}%}++[0..1.0..(.0]2/%..&,(\0='.'if}{@@;;}if}+^n?,%puts}/

```

Input is given to the subprogram as a single string on the stack. Unfortunately I had to use a `puts` because of the requirement that the routine has to print the result.

**Explanation of the code**

The outer block essentially loops over all position (x,y) according to the size of the input rectangles. Within the loop the coordinates x and y are left on the stack each time. After each line is complete the result is printed to console.

```
:^              # save input in variable ^
n%,,{{          # split along newlines, count rows, make list [0..rows-1]
    ???             # loop code, see below
}+^n?,%puts}/       # ^n?, count columns, make list [0..cols-1], loop and print

```

The code executed within the loop first takes the corresponding character of the input.

```
^n/                 # split input into lines
1$=                 # select the corresponding row
2$>1<               # select the corresponding col

```

Then basically we check, if we have a `.`, i.e. if we (possibly) have to replace the character.

```
.'.'={              # if the character is '.'
    ;               # throw away the '.'
    ???             # perform more code (see below)
}{                  # else
    @@;;            # remove coordinates, i.e. keep the current character
                    # (i.e. A, B, ... or \n)
}if                 # end if

```

Again, the inner code starts with a loop, now over all coordinates (x,y) (x,y+1) (x+1,y) (x,y-1) (x-1,y)

```
{
    @~@+@@+\        # build coordinates x+dx, y+dy
    ???             # loop code
}++                 # push coordinates before executing loop code
[0..1.0..(.0]2/%    # loop over the coordinates [0 0] [0 1] [1 0] [0 -1] [-1 0]

```

The recent inner code snippet simply returns the (lower case) letter of the nearest point, given the two coordinates.

```
{                   # loop
    ^3$?^<          # find the current letter (A, B, ...) in the input string,
                    # take anything before
    n/              # split at newlines
    ),              # from the last part take the length (i.e. column in which the letter is)
    \,              # count the number of lines remaining (i.e. row in which the letter is)
    @-abs@@-abs+    # calculate distance to the given coordinate x, y
    99*+            # multiply by 99 and add character value (used for sorting
                    # chars with equal distance)
}++                 # push the coordinates x, y
^'.
'-                  # remove '.' and newline
\$                  # now sort according to the code block above (i.e. by distance to letter)
1<{32+}%            # take the first one and make lowercase

```

So from the five nearest letters for the coordinates (x,y) (x,y+1) (x+1,y) (x,y-1) (x-1,y) take the first, if not all are equal, otherwise take a `.`.

```
.                   # copy five letter string
.&,(                # are there distinct letters?
\0=                 # first letter (i.e. nearest for coordinate x,y)
'.'                 # or dot
if                  # if command

```

# Answer
> 7 votes
# Python 3 - 424 422 417 332 295 characters:

```
def v(s):
 w=s.find("\n")+1;n=(-1,1,-w,w);r=range(len(s));x=str.replace;s=x(x(s,*".~"),*"\n~")+"~"*w;t=0
 while s!=t:t=s;s=[min(s[i+j]for j in n).lower()if"~"==s[i]and(i+1)%w else s[i]for i in r]+["~"]*w
 print(x("".join(s[i]if any(s[i]!=s[i+j].lower()!="~"for j in n)else"."for i in r),*"~\n"))

```

There are three parts, each of which needs to be on its own line due to Python's syntax:

1. The first line sets up the variables. `w` is the width of a row of the board (including the newline at the end, which will be recycled as a padding column). `r` is a `range` object that indexes all the characters in `s`. `n` is a tuple of index offsets to get at the neighbors of a character (so if you wanted to allow the letters to spread out diagonally, you'd just need to add `-w-1,-w+1,w-1,w+1` to the tuple). `x` is a short name for the `str.replace` method, which gets used several times in the later code (the calls will look odd though, since I use `x(s,*"xy")` to save characters, rather than the conventional `s.replace("x", "y")`). The `s` parameter string is modified slightly at this point as well, with its `.` characters and newlines being replaced by `~` characters (because they sort after all letters). A row's worth of padding `~` characters are also added to the end. `t` will later be used as a reference to the "old" version of `s`, but it needs to be initialized to something not equal to `s` at the start, and zero takes only one character (a more Pythonic value would be `None`, but that's three extra characters).
2. The second line has a loop that repeatedly updates `s` using a list comprehension. As the comprehension iterates over the indexes of `s`, `~` characters are replaced by the `min` of their neighbors. If a `~` character was completely surrounded by other `~`s, this will do nothing. If it was next to one or more letters, it will become the smallest of them (favoring `"a"` over `"b"`, etc.). The newlines that were turned to `~` characters are preserved by detecting their indexes with the modulus operator. The padding row at the end isn't updated in the list comprehension (because the range of indexes, `r`, was calculated before they were added to `s`). Instead, a fresh row of `~` characters is added after the comprehension is done. Note that `s` becomes a list of characters rather than a string after first pass of the loop (but because Python is flexible about types we can still index to get at the characters in the same way).
3. The last line hollows out the insides of the diagram and rebuilds the characters into a string to be printed. First, any letter that is surrounded only by other copies of itself (or `~` characters from the padding) gets replaced by `.`. Next, the characters are all concatenated together into a single string. Finally, the padding `~` characters are converted back to newlines and the string is printed.

# Answer
> 3 votes
## Python, 229 226 chars

```
def F(s):
 e,f,b='~.\n';N=s.index(b)+1;s=s.replace(f,e)
 for i in 2*N*e:s=''.join(min([x[0]]+[[y.lower()for y in x if y>b],all(y.lower()in f+b+x[0]for y in x)*[f]][x[0]!=e])for x in zip(s,s[1:]+b,s[N:]+b*N,b+s,b*N+s))
 print s

F("""......B..
.........
...A.....
.........
.......D.
.........
.C.......
.....E...
.........
""")

```

Does a flood fill to compute the result. The trailing `for`/`zip` combo generates an array `x` for each cell containing the value in that cell and its four neighbors. Then we use Blckknght's trick and `min` a bunch of possibilities for each cell. Those are the original cell value, any neighbors if the cell has not been visited yet, or a `.` if it has been visited and all neighbors are `.` or equal to the cell itself.

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


title: Unlooped Factorials

text:
# Question
Title: Unlooped Factorials
Write a program to determine if a number is a factorial. You should take the number from standard input.

**Rules:**

* **No using *any* loops** (hint: recursion)
* **Maximum of *one* if statement**
* **No accessing the Internet or external resources**

**Scoring:**

* **+1 per character**
* **-20 for each of the following: (I don't know if any of these are possible)**
    + **Don't use any if statements**
    + **Don't use recursion**

**Lowest score wins**.

**Clarification:**

* **Only if statements in your *source* code count, but any form of if counts.**
* **Any loop constructs in source code count.**
* **You *may* assume int32**

# Answer
# Mathematica ~~42~~ 41-40 = 1

No recursion or `If` is used (-40)

```
MemberQ[Table[Times@@Range@k,{k,9^4}],#]&

```

**How it works**.

`Times` is `Listable`. It does not loop when applied to a list. It does the multiplication all at once.

```
Range[6]

```

> {1,2,3,4,5,6}

```
Times@@Range[6]

```

> 720

---

**Testing**

```
MemberQ[Table[Times@@Range@k,{k,9^4}],#]&[720]
MemberQ[Table[Times@@Range@k,{k,9^4}],#]&[721]
MemberQ[Table[Times@@Range@k,{k,9^4}],#]&[10000!]

```

> True
> False
> True
> 3 votes

# Answer
## GolfScript: 13, no loops or recursion

```
.,{,(;{*}*}%?

```

Admittedly very inefficient. Compute every factorial up to `n!` and find `n` in the list. The top of the stack will be -1 if and only if the input was not a factorial.

Changed to a GolfScript answer I liked better because question was closed.
> 2 votes

# Answer
### GolfScript, 32

Plain approach using recursion (no loops, also no internal loops) and exactly one *if*:

```
~1{1$1$%!@2$/*\)1$2<{;}{f}if}:f~

```

Test the code online. It'll print `1` if the input is a factorial number, `0` if not.

We can hide also the *if* using string evaluation:

```
~1{1$1$%!@2$/*\)1$2<'f;'1/=~}:f~

```
> 1 votes

# Answer
# Ruby, 46 characters (26 points?)

```
f=->x,m{x>1 ?f[x/m,m+1]:x==1}
p f[gets.to_r,1]

```

This version is pretty straightworward. It divides by successive integers until the number drops at one or below using bignum rational arithmetic, then returns whether it's exactly one, except it uses tail recursion to do so.

If it's allowed to output the condition inverted, use `x<1` instead of `x==1` for a one-character saving.

The looping version is just 6 characters shorter:

```
x,m=gets.to_r,1
x/=m+=1 while x>1
p x==1

```

Also, can I get a 20-point bonus for using a ternary instead of an `if` statement? If not, can I get it for a pair of short-circuiting boolean operators **(53 characters)**?

```
f=->x,m{p x,m;x>1&&f[x/m,m+1]||x==1}

```

If not, what about an array of functions? This one is too long (even with the bonus) (and unreadable), but it does demonstrate an important point: what does actually count as an `if`?

```
f=->x,m{{true=>f,false=>->_,_{x==1}}[x>1][x/m,m+1]}

```
> 1 votes

# Answer
## Tcl 53 (93-40)

Only int32?

```
 expr [gets stdin]in{1 2 6 24 120 720 5040 40320 362880 3628800 39916800 479001600 6227020800}

```

Fine.
> 1 votes

# Answer
## Haskell - 49 (or 29 or 9)

This is one bends unwritten rules: It will not halt for non-factorial inputs. In practice it does determine if a number is a factorial or not, but then again theoretically you can never know.

```
main=getLine>>=print.(`elem`scanl1(*)[1..]).read

```

Edit: sorry for initially not reading the problem description.
> 0 votes

# Answer
## Haskell, 31 = (71C - 20 - 20)

No if statements, no recursion.

```
c n=n`elem`[product[1..n]|n<-[1..n]]
main=do;s<-getLine;print$c$read s

```
> 0 votes

---
Tags: code-golf
---


title: List the first 20 friendly number pairs

text:
# Question
Title: List the first 20 friendly number pairs
I just started reading about friendly numbers and I think they sound great.

> In number theory, **friendly numbers** are two or more natural numbers with a common **abundancy**, the ratio between the sum of divisors of a number and the number itself. Two numbers with the same abundancy form a **friendly pair**; *n* numbers with the same abundancy form a **friendly *n*-tuple**.

So, how small a program can you write to output a list of the first 20 friendly numbers.

Assuming I've understood everything I've read correctly the output of your program should be:

```
6,28
30,140
80,200
40,224
12,234
84,270
66,308
78,364
102,476
6,496
28,496
114,532
240,600
138,644
120,672
150,700
174,812
135,819
186,868
864,936
222,1036
246,1148

```

I'd also like to add that the program must calculate the answers and not use any external resources or hard coded answers (thanks Peter).

# Answer
> 5 votes
## APL (50)

```
↑⊃,/{g/⍨{=/{⍵÷⍨+/z/⍨0=⍵|⍨z←⍳⍵}¨⍵}¨g←⍵∘.,⍳⍵-1}¨⍳936

```

The list is slightly different but oeis.org agrees with me.

Output:

```
 28   6
140  30
200  80
224  40
234  12
270  84
308  66
364  78
476 102
496   6
496  28
532 114
600 240
644 138
672 120
700 150
812 174
819 135
868 186
936 864

```

# Answer
> 5 votes
# C (132)

```
x=1,e;float d(a,b){return b?1.f*(a%b==0)*b/a+d(a,--b):0;}main(){while(x<1148)for(e=x++;--e;)d(x,x)-d(e,e)||(printf("%d,%d\n",e,x));}

```

Thanks to shiona for the ideas on shorter code. And Felix Eve for the Code(counting down makes more sense if you only search pairs). With the added Pairs even shorter.

Readable Version:

```
x=1,e;

float d(a,b)
{
    return b?1.f*(a%b==0)*b/a+d(a,--b):0;
}

main()
{
    while(x<1148)
        for(e=x++;--e;)
            d(x,x)-d(e,e)||(printf("%d,%d\n",e,x));
}

```

# Answer
> 5 votes
# Ruby, 90 characters

```
h={}
1.upto(1150){|n|s=0
1.upto(n){|x|s+=x if n%x<1}
r=s/n.to_r
p [h[r],n] if h[r]
h[r]=n}

```

# Answer
> 4 votes
# Mathematica ~~114 112 99~~ 90

**Numbers having same abundancy.** (90 chars)

This displays integers with a common abundancy. Notice that 6, 28, and 496 have the same abundancy, which means that (6,28), (6,496) and (28, 496) are friendly number pairs. Likewise, 84, 270, 1488, 1638 have the same abundancy.

Because, as Peter Taylor noted, there is no method suggested for total ordering, it is unclear which pairs constitute the "first 20" friendly number pairs.

```
Grid@Cases[GatherBy[{k, 1~DivisorSigma~k/k}~Table~{k, 2000}, Last], x_ /; Length@x > 1
:> x[[All, 1]]]

```

# Answer
> 4 votes
## Mathematica ~~62~~ ~~58~~ 55

```
Grid@Cases[GatherBy[Range[6!],Tr@Divisors@#/#&],{_,__}]

6   28  496
12  234
30  140
40  224
66  308
78  364
80  200
84  270
102 476
114 532
120 672
138 644
150 700
240 600

```

You may go up to `9!` without affecting the char count

# Answer
> 1 votes
Using awk (303, uncompressed)

```
 awk 'BEGIN{for (i=1;i<=1150;i++)
             { for (j=1;j<=int(i/2);j++)
                  if (i%j=="0") a[i]+=j
                v=sprintf("%.10f",(a[i]+i)/i)
                #print v,i
               b[v]=b[v] FS i
              }
           for (i in b) {l=split(b[i],x,FS);if (l>1) print b[i]}}' file|sort -n

 6 28 496
 12 234
 30 140
 40 224
 66 308
 78 364
 80 200
 84 270
 102 476
 114 532
 120 672
 135 819
 138 644
 150 700
 174 812
 186 868
 222 1036
 240 600
 246 1148
 864 936

```

# Answer
> 0 votes
## C - 188

I assume someone will do this with a language that supports literal newlines and requires less boilerplate.

```
main(){puts("6,28\n30,140\n80,200\n40,224\n12,234\n84,270\n66,308\n78,364\n102,476\n114,532\n240,600\n138,644\n120,672\n150,700\n174,812\n135,819\n186,868\n864,936\n222,1036\n246,1148");}

```

# Answer
> 0 votes
# PHP - 260

```
$x=1;while($i<20){$d=0;$y=$x;for($y=$x;$y>0;$y--){if($x%$y==0)$d+=$y;}$f=$d/$x.'';$s[$f][]=$x;if(count($s[$f])>1) {$i++;if(count($s[$f])>2){$o[]=$s[$f][0].','.$s[$f][2];$o[]=$s[$f][1].','.$s[$f][2];}else $o[]=implode(',',$s[$f]);}$x++;}echo implode('<br>',$o);

```

Uncompressed:

```
$x=1;
$o = array();
while($i<20) {
    $d = 0;
    $y = $x;
    for($y=$x;$y>0;$y--) {
        if($x%$y==0) $d += $y;
    }
    $f = $d / $x.' ';
    $s[$f][] = $x;
    if(count($s[$f])>1) {
        $i++;
        if(count($s[$f])>2) {
            $o[] = $s[$f][0].','.$s[$f][2];
            $o[] = $s[$f][1].','.$s[$f][2];
        } else {
            $o[] = implode(',', $s[$f]);
        }
    }
    $x++;
}
echo implode('<br>', $o);

```

This answer is longer than my other answer but works properly (doesn't skip any numbers and only has 2 numbers per row) so I'm more happy with this one.

# Answer
> 0 votes
C#: 208

```
public class A{static double D(int n){return 1f*Enumerable.Range(1,n).Where(i=>n%i==0).Sum()/n;}static void Main(){for(int j,i=1;i++<865;)for(j=1;j++<1000;)if(A.D(i)==A.D(j)&&i<j)Console.WriteLine(i+" "+j);}}

```

---
Tags: code-golf, kolmogorov-complexity, number-theory
---


title: Desperately Seeking Santa

text:
# Question
Title: Desperately Seeking Santa
Find Santa and his reindeer in a crowded scene.

## Input

Input will be on STDIN and will be a variable number of lines of characters of equal, but variable, length. If Santa (represented by the character `S`) is in the scene, his sack of presents (represented by the character `P`) will be in one of the positions adjacent to him (horizontally, vertically or diagonally). His reindeer (each represented by the character `R`) will all be within the 5x5 square surrounding him. If an `S` appears in the scene that does not have a sack of presents, or is not accompanied by at least 4 reindeer, then it is not Santa.

## Output

The scene cleared of all obfuscation (all non-Santa, non-presents, non-reindeer characters replaced with a space), showing Santa, his sack of presents, and his reindeer - all other characters should be replaced with spaces. If Santa and his reindeer are not in the scene, output it unchanged. It is guaranteed that there will only be one solution, so there will never be more than one valid Santa and he will never be carrying more than one sack of presents.

## Examples

In these examples I'm just using the `*` character to make it easy to see the `S`, `P`, and `R` characters, but your program should be able to handle any ascii character from `!` to ``` (33 to 96). I've left out lower case characters and above to avoid confusion.

**Input:**

```
***********
***********
***********
*****R*****
******P****
*****S*****
*****R*****
****R**R***
***********
***********
***********
***********

```

**Output:** (ignore dots, they're to force the page to show the blank lines)

```
.
.
.
     R
      P
     S
     R
    R  R
.
.
.
.

```

**Input:** (not enough reindeer)

```
***********
***********
***********
***********
******P****
*****S*****
*****R*****
****R**R***
***********
***********
***********
***********

```

**Output:**

```
***********
***********
***********
***********
******P****
*****S*****
*****R*****
****R**R***
***********
***********
***********
***********

```

**Input:** (no sack of presents)

```
***********
***********
***********
*****R*****
***********
*****S*****
*****R*****
****R**R***
***********
***********
***********
***********

```

**Output:**

```
***********
***********
***********
*****R*****
***********
*****S*****
*****R*****
****R**R***
***********
***********
***********
***********

```

**Input:** (presents not close enough)

```
***********
***********
***********
*****R*****
***********
*****S*P***
*****R*****
****R**R***
***********
***********
***********
***********

```

**Output:**

```
***********
***********
***********
*****R*****
***********
*****S*P***
*****R*****
****R**R***
***********
***********
***********
***********

```

**Input:** (one of the reindeer not within the 5x5 square around Santa)

```
***********
***********
***********
*****R*****
******P****
*****S*****
*****R*****
****R******
*******R***
***********
***********
***********

```

**Output:**

```
***********
***********
***********
*****R*****
******P****
*****S*****
*****R*****
****R******
*******R***
***********
***********
***********

```

## Test Scripts

As in some of my past questions, I've once again butchered some test scripts originally created by Joey and Ventero to provide some test cases for this question:

Usage: `./test [your program and its arguments]`

Plain text version of the tests for reference: Plain text

## Rewards

Each entry which I can verify that meets the spec, passes the tests and has obviously had some attempt at golfing will receive an upvote from me (so please provide usage instructions with your answer). The shortest solution by the end of 31/12/2013 will be accepted as the winner.

# Answer
## MATLAB: 110 ~~,95~~ characters

```
f=@(x,y) filter2(ones(x),y);a=M==83;b=M==82;c=M==80;d=f(5,a&f(5,b)>3&f(3,c))&(a|b|c);if ~d,M,else,M(~d)=32,end

```

Not sure about the way input is supposed to be processed, but the rest is pretty straightforward.

Normally formatted version:

```
f=@(x,y) filter2(ones(x),y);
a=M==83;
b=M==82;
c=M==80;
d=f(5,a&f(5,b)>3&f(3,c))&(a|b|c);
if ~d
  M
else
  M(~d)=32
end

```

Example input:

```
M=['***********'
'***********'
'***********'
'*****R*****'
'******P****'
'*****SQL_2*'
'*****R*****'
'****R**R***'
'***********'
'***********'
'***********'
'***********'];

```
> 2 votes

# Answer
# Python 2 (~~353~~ 381)

```
import re,sys
a=sys.stdin.readlines()
h=len(a)
w=len(a[0])
a=''.join(a)+' '*99
print a
b=[''.join(q) for x in range(0,w) for y in range(0,h) for q in [[a[(y+z)*w+x:(y+z)*w+x+5] for z in range(0,5)]]]
for c in b:
 if c[12]=='S' and 'P' in ''.join([c[1+5*z:4+5*z] for z in range(1,4)]) and c.count('R')>3:
  a=re.sub('[^RPS]','.',c)
  w=h=5
for y in range(0,h):
 print a[y*w:(y+1)*w]

```

First attempt at writing code as compact as possible. Python is not really the language for that, as indentation and newlines are simply required by design. I mainly choose to use this language, because of the way you can play with lists, and strings as lists. A language with easy matrix manipulation would be ideal for this task, but sadly I don't know any of them.

~~To test thing, something needs to be assigned to a, e.g.~~

~~```
a=['1**********','*2*********','**3********','***4*******','****5*P****','*****S*****','*****,*****','****R**R***','***********','***********','****R******','**RPSRRR***']

```~~

Main interesting thing in this code is probably:

```
b=[''.join(q) for x in range(0,w) for y in range(0,h) for q in [[a[(y+z)*w+x:(y+z)*w+x+5] for z in range(0,5)]]]

```

which is a fancy way of writing: "b becomes a list of a representation (string of 25 characters) of every 5x5 square in the original representation".
> 1 votes

# Answer
There should be only one Santa in file (if more than 2 "S", I need update the code).

Using awk

```
cat santa.awk

BEGIN{FS=""}
{ for (i=1;i<=NF;i++)
         { a[NR FS i]=$i
           if ($i=="S") {l=NR;c=i}
         }
     }
END{ if (l=="") {print "No Santa";exit}
     for (i=l-1;i<=l+1;i++)
        for (j=c-1;j<=c+1;j++)
          if (a[i FS j]=="P") p++
     if (p<1) {print "Santa has no presents";exit}
     for (i=l-2;i<=l+2;i++)
        for (j=c-2;j<=c+2;j++)
          if (a[i FS j]=="R") r++
     if (r<4) {print "Santa has no enough reindeers";exit}
     else {  print "found Santa "
             for (i=1;i<=NR;i++)
               { for (j=1;j<=NF;j++)
                   if (a[i FS j]~/[R|S|P]/) {printf a[i FS j]} else {printf " "}
                 printf RS
                }
           }
    }

```

Run awk command as below

```
awk -f santa.awk file

```

Result

```
found Santa

     R
    R R
    PS
    RR
    R  R

```
> 0 votes

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


# Question
Title: Convert arbitrary roman numeral input to integer output
The usual rules: no external resources, or the like. Input will be a positive integer in valid Roman numeral format less than 10 thousand, say.

Use all the Roman numeral characters:

* I = 1
* V = 5
* X = 10
* L = 50
* C = 100
* D = 500
* M = 1,000

Respect subtractive notation (copied from the Wikipedia page):

* the numeral I can be placed before V and X to make 4 units (IV) and 9 units (IX) respectively
* X can be placed before L and C to make 40 (XL) and 90 (XC) respectively
* C can be placed before D and M to make 400 (CD) and 900 (CM) according to the same pattern\[5\]

# Answer
# Mathematica, 33 chars

```
FromDigits[InputString[],"Roman"]

```
> 8 votes

# Answer
**JavaScript, ~~98~~ 91 characters**:

```
for(k=d=l=0,a=prompt();i={I:1,V:5,X:10,L:50,C:100,D:500,M:1e3}[a[k++]];l=i)d+=i>l?i-2*l:i;d

```

Expanded form:

```
a = prompt(), // a is input string
d = 0,        // d is result sum
l = 0,        // l is last value processed (for comparison with current val)
k = 0,        // k is current position in string

v = {I:1,V:5,X:10,L:50,C:100,D:500,M:1e3}; // map of values

// for each char in string a[k] (left to right), put its base-10 value in i
while(i = v[a[k++]]) {

    // if previous left-side value is lower than this value,
    //     it should have been substracted, so subject twice its value
    //     (once to negate the past addition, and again to apply negative value)
    // regardless, add this value
    if(i>l) {
        d += i - 2*l;
    } else {
        d += i;
    }

    // store this value as previous value
    l=i;
}

// yield result
d;

```
> 6 votes

# Answer
**Scala 195**

```
val t=Map('I'->1,'V'->5,'X'->10,'L'->50,'C'->100,'D'->500,'M'->1000)
def f(n:String)={val r=n.substring(1).foldLeft((0,t(n.head)))((a,x)=>(if(a._2>=t(x))a._1+a._2 else a._1-a._2,t(x)));r._1+r._2}

```
> 3 votes

# Answer
## GolfScript: 83

```
0\{[77 68 67 76 88 86 73]?[1000 500 100 50 10 5 1]=}%{)@.@.@<{~)}{}if@.}do;{+\.}do;

```
> 3 votes

# Answer
# MS Excel,12

Enter a value in A1, then enter this in A2

```
=ARABIC(A1)

```
> 3 votes

# Answer
**Python 201 characters**

```
m={'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900,'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
f=lambda s:m[s] if s in m else(m[s[:2]]+f(s[2:])if s[:2]in m else m[s[0]]+f(s[1:]))
f(raw_input())

```

Example:

```
>>> m={'IV':4,'IX':9,'XL':40,'XC':90,'CD':400,'CM':900,'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000};f=lambda s:m[s] if s in m else(m[s[:2]]+f(s[2:])if s[:2]in m else m[s[0]]+f(s[1:]));f(raw_input())
MMMCMLXXXVII
3987

```

**~~119~~ 117 characters**

```
>>> X=[dict(zip('MDCLXVI',(1e3,500,100,50,10,5,1)))[x]for x in raw_input()];sum((x,-x)[x<y]for x,y in zip(X,X[1:]))+X[-1]
MMMCMLXXXVII
3987.0

```

Expanded form:

```
>>> # Maps roman numbers to their decimal counterpart
>>> roman_map = dict(zip('MDCLXVI',(1e3,500,100,50,10,5,1)))
>>> # Maps the list of input number to the corresponding decimals
>>> X=[roman_map[x]for x in raw_input()]
>>> # A number will be added (x) or subtracted (-x) depending on its value vs the next number
>>> # For instance CM -> [100, 1000], 100 < 1000, therefore -100, +1000
>>> result = sum((x,-x)[x<y] for x,y in zip(X,X[1:])) # True = 1, False = 0
>>> # Adding the last element (which is always added)
>>> result += X[-1]

```
> 2 votes

# Answer
## JavaScript, 198 characters

```
n={I:1,V:5,X:10,L:50,C:100,D:500,M:1e3,IV:4,IX:9,XL:40,XC:90,CD:400,CM:900},s=prompt(),a=i=0;for(;i<s.length;i++){b=(j)=>s.substr(j,1);c=b(i);d=b(i+1);e=n[c+d];if(e){a+=e;i++}else{a+=n[c]}}alert(a);

```

The ungolfed code:

```
n = {
    I: 1,
    V: 5,
    X: 10,
    L: 50,
    C: 100,
    D: 500,
    M: 1e3,
    IV: 4,
    IX: 9,
    XL: 40,
    XC: 90,
    CD: 400,
    CM: 900
}, s = prompt(), a = i = 0;
for (; i < s.length; i++) {
    b = (j) => s.substr(j, 1);
    c = b(i);
    d = b(i + 1);
    e = n[c + d];
    if (e) {
        a += e;
        i++
    } else {
        a += n[c]
    }
}
alert(a);

```

How this works: first, you store all values inside an object. Then, you prompt for input and you loop over all characters in the string. If the current character + the next character are a number (`CM` for example), then look up `current char + next char` in the object. If `current char + next char` isn't available in the object, just look up the current char.

Demo: http://jsfiddle.net/vSLfM/
> 1 votes

# Answer
## Ruby, 134

```
i=gets
%w[IV,4 IX,9 XL,40 XC,90 CD,400 CM,900 I,1 V,5 X,10 L,50
C,100 D,500 M,1000].map{|s|k,v=s.split ?,;i.gsub!(k,?++v)}
puts eval i

```
> 1 votes

---
Tags: code-golf, roman-numerals
---


# Question
Title: Write a program to compose a quine of a specified length
Write a program, in a language of your choice, that will compose a quine program of a requested size. The generated program may be in the same or a different language, if desired.

Programs are scored based on the following formula:

> generating\_program\_length + smallest\_supported\_size + 512 * number\_of\_supported\_sizes ^ (-3/4)

Halve your score if you support *every size* between the minimum and maximum supported sizes.

Lowest score wins.

# Answer
## GolfScript → GolfScript: (4 + 0 + 0) / 2 = 2

```
~1`*

```
* Program length: **4**
* Minimum supported size: **0**
* Maximum supported size: *unbounded*
* All sizes supported: *yes*

This program simply reads an integer *n* from its input, and outputs an *n*-digit integer consisting of *n* `1` digits. For example, the input `5` yields the output `11111`. In GolfScript, any integer literal (without leading zeros) is a quine, and since GolfScript integers can be arbitrarily large, the maximum supported length is only bounded by the amount of memory available.

For the input `0`, the code outputs an empty program, which is also a quine in GolfScript.

Ps. The generated quines work for several other languages too, including PHP.
> 9 votes

# Answer
# Ruby -\> JavaScript, 38

45 character program
31 smallest supported size
Infinity possible sizes
Supports any size in range
(45 + 31 + 512 * Infinity ^ -3/4) / 2 = 38

```
"function f(){alert(f+'f()')#{?;*(i-31)}}f()"

```

# GolfScript -\> JavaScript, 37.5

1 char less :P

```
"function f(){alert(f+'f()')"";"i 31-*"}f()"

```

---

Example output for `i = 31`:

```
function f(){alert(f+'f()')}f()

```

For `i = 41`:

```
function f(){alert(f+'f()');;;;;;;;;;}f()

```

The output quines work on latest Chrome (31.0.1650.63), at least. (Untested for any other browser)
> 4 votes

# Answer
# Ruby or GolfScript -\> HQ9+, 6

11 character program
1 smallest supported size
Infinity possible sizes
Supports any size in range
(11 + 1 + 512 * Infinity ^ -3/4) / 2 = 6

```
?Q+?+*(i-1)

```

Same size program written in GolfScript:

```
"Q""+"i 1-*

```

---

Example output for `i = 1`:

```
Q

```

For `i = 10`:

```
Q+++++++++

```
> 3 votes

# Answer
# Befunge 98 - (14 + 0 + 0) / 2 = 7

```
'1&k:$$>,:# _@

```

Output is in ~~HQ9+~~ Golfscript (Thanks to Ilmari)

Output for 0:

```

```

Output for 1:

```
1

```

Output for 10:

```
1111111111

```

Explanation:

```
'1             ;push the character `'1'` onto the stack
  &            ;get the inputted number (`n`), push on stack
'1&k:          ;duplicate the `'1'`, `n + 1` times, leaving `n + 2` of `'1'` on the stack
'1&k:$$        ;drop the top two `'1'`s on the stack
       >,      ;print the top element of the stack
       >,:# _  ;duplicate the next, then check if it is `0`.
             @ ;if it is `0`, execute this, which ends the program.
        , # _  ;otherwise, go back the other way and continue printing
       >       ;turn back to the right.
'1&k:$$>,:# _@

```
> 3 votes

# Answer
# Python 2 - 62.6 points

```
s='s=%r;print(s%%s+s*99)[:input()]#';print(s%s+s*99)[:input()]

```

This code is both the generator and the core of the quine. It expects you to provide a length on standard input, and prints to standard output a version of itself of that length (larger sizes get a trailing comment full of junk).

So, if you pass it 62, it prints itself (this is the minimum size). If you call it with some longer length (up to the maximum length of 3231), it will produce output of that length. Any version will be a quine if passed its own length.

The length limit was the result of my attempts at minimizing the number of characters used. Supporting more lengths was costing more in points for code length than it was reducing the penalty for a limited range. It's not hard to make a variant that will work for unlimited sizes, but it will need to be longer by about 20 characters (and so score worse).

Note that requesting a shorter length than 62 will produce output of the desired size, but that output will not be working code. Passing a larger length than 3231 will produce the 3231-character version of the quine. Passing something other than an integer will raise an exception.

**Scoring:**

* Generator length: 62 characters, 62 points
* Minimum quine size: 62 characters, 62 points
* Number of supported sizes: 3169, 1.2 points
* All sizes between minimum and maximum accepted: Half off all points above.
* Total: (62+62+1.212)/2 = 62.6 points
> 3 votes

# Answer
# Ruby -\> Ruby (79 points)

char: 51
min size: 28
max size: infinite
`(0..num){|x|print "eval s=\"print 'eval s=';p s\""}`
> 0 votes

# Answer
## Golf-Basic 84 -\> Golf-Basic 84

**(54 + 0 + 0) / 2 = 27**

* Program length: *54*
* Minimum supported size: *0*
* Maximum supported size: *none*
* All sizes supported: *yes*

Only limited by the calculator's RAM.

```
i`A:""_Str1:"1"_Str2l`1:A--A:Str1+Str2_Str1@Ag`1d`Str1

```
> -2 votes

---
Tags: code-golf, quine, metagolf
---


title: Is it a Diff or not?

text:
# Question
Title: Is it a Diff or not?
Your program will be run an undetermined amount of times. On all but the last, there will be a file called `data` in the same directory of your program that has the same value each time. On the last run, the file will be there but will have different data in it. On all the times *except* the last, you can do whatever you want, as long as the following rules are met:

* **Don't output anything**
* **Don't change `data` file**

On the *last* run, you must print out the diff of the first `data` file and the current `data` file.

**Rules:**

* **You *may* save whatever you want in any files you want, just don't edit the `data` file**

**Scoring:**

* **Lowest char score wins**

Cheating encouraged. You have *no* indication of which run you're in *except* that the `data` file is changed.

# Answer
> 6 votes
## Bash (31)

```
[ -e x ]&&diff data x;cp data x

```

Kinda obvious.

# Answer
> 0 votes
Here it is with good ol' Windows batch:

```
@echo off
  if exist lastdata goto compare_data
  type data > lastdata
  goto end
:compare_data
  fc data lastdata > nul
  if errorlevel 1 goto last
  if errorlevel 0 goto end
:last
  fc data lastdata
  del lastdata
:end

```

---
Tags: code-golf
---


title: (Python) Implementing incrementation

text:
# Question
Title: (Python) Implementing incrementation
Challenge: Implement incrementation without addition, multiplication, exponentiation, and any higher binary operators (and their opposites) in Python. Winner is the person who can do it in the least amount of code. You score 5 characters less if you can do it for negative numbers and without unary operators.

# Answer
### 3

```
-~i

```

Just good ol' unary `-` and bitwise-NOT.

**Demo**

```
>>> i = 3
>>> -~i
4
>>> i = 0
>>> -~i
1
>>> i = -3
>>> -~i
-2

```
> 16 votes

# Answer
### 14

I'm not a python guy, so here we go:

```
len(' '*i+' ')

```

According to the docs, I don't use addition, only string concatenation and repetition.
> 10 votes

# Answer
# 17 characters

Not shortest, but another way. This time no maths or binary operators involved *at all*. But it only works on numbers greater than -1.

```
len(range(-1,x))

```

Proof:

```
>>> inc = lambda x: len(range(-1,x))
>>> inc(7)
8
>>> inc(100)
101

```

# 28 = 33-5 characters

Definitely out of contention but this does it for all positive and negative integers, again no math, no unary tricks.

```
len(range(-1,x)) or range(x,1)[1]

```

Proof:

```
>>> inc = lambda x:len(range(-1,x)) or range(x,1)[1]
>>> for i in range(-2,2): print i, inc(i)
...
-2 -1
-1 0
0 1
1 2

```
> 1 votes

# Answer
### 10 - 5 = 5

```
sum((i,1))

```

**Demo**

```
>>> i = -3
>>> sum((i,1))
-2
>>> i = 0
>>> sum((i,1))
1
>>> i = 3
>>> sum((i,1))
4

```
> 0 votes

# Answer
**27-5=22**

It's not really very short, but it doesn't use len(), range(), sum() and other stuff which definitely has a lot of increments and additions in it. Works with negative numbers, and no unary operations. Only pure, natural, raw, organic bitwise magic :)

```
j=i
k=1
while i<=j:i^=k;k<<=1

```

**Demo:**

```
>>> def inc(i):
...     j=i
...     k=1
...     while i<=i:i^=k;k<<=1
...     return i
...
>>> inc(1)
2
>>> inc(2)
3
>>> inc(20)
21
>>> inc(-24)
-23
>>>

```

(UPD: Sorry, I'm not sure whether newlines are counted as chars, if yes, it should be 29 not 27...)
> 0 votes

---
Tags: code-golf, python
---


title: Party all week end for my birthday?

text:
# Question
Title: Party all week end for my birthday?
Knowing a given date (`11/28/1973`), and supposing I will die when I'm 99, what are the years when my birthday will be a thursday so that I will be able to party all week-end?

# Answer
> 0 votes
js

```
var y = 1973 + 99;
while(y-- > 1973) 4!=new Date('11/23/'+y).getDay()||console.log(y);

```

# Answer
> -1 votes
Something like this:

**c#**

```
        var birthdate = new DateTime(1973,11,28);
        for (int i = 0; i <= 99; i++)
        {
            var date = birthdate.AddYears(i);
            if (date.DayOfWeek.Equals(DayOfWeek.Thursday))
            {
                Console.WriteLine(date.Year);
            }
        }

```

---
Tags: date
---


# Question
Title: how to find n'th number in the decimal expansion of a proper fraction?
Given three integers N,D,R write a program to output Rth digit after the decimal point in the decimal expansion for a given proper fraction N/D.

# Answer
## GolfScript 17

```
10\?@abs*\abs/10%

```

GolfScript can't handle real numbers well, but multiplying by powers of 10 is equivalent.

Here's an explanation and walkthrough with sample input, for any of you who are new to GolfScript, since I think this is a nice simple introduction:

```
59 -17 5
10\ #Place 10 on the stack and then switch the top 2 elements
-> 59 -17 10 5
? #Exponentiate
-> 59 -17 100000
@ #Rotate top 3 elements
-> -17 100000 59
abs #Take absolute value of top element
-> -17 100000 59
* #Multiply the top 2 elements
-> -17 5900000
\ #Switch top 2 elements
-> 5900000 -17
abs #Take absolute value of top element
-> 5900000 17
/ #Do integer division
-> 347058
10% #Place 10 on the stack and then take modulo
-> 8

```
> 4 votes

# Answer
## Java

```
static int digit(int N, int D, int R) {
    if (D < 0) D = -D;
    if (N < 0) N = -N;
    int Q=0;
    while (R-- > 0) {
        while (N >=D) N -=D;
        int P=N = ((N+N)<<1)+N;
        for (Q=P^P; N >D; N -=D) Q++;
        while (P >=D) P -=D;
        N = P<<1;
    }
    for (; N >= 0; N -=D) R++;
    return (Q<<1) + R;
}

```

This code

* avoids multiplication and division
* splits decimal digit in 5- and 2-digit (Q and final R) internally

---

*Explanation*

When dividing manually you get digits by multiplying remainders by 10 and comparing the results to multiples of the divisor

```
10 / 17 = Digit 0, Remainder 10 (x 10)
100 / 17 = Digit 5, Remainder 15 (x 10)
 150 / 17 = Digit 8, Remainder 14 (x 10)
  140 / 17 = Digit 8, Remainder 4 (x 10)
etc.

```

So the basic code (ignoring all digits except the R-th) would be

```
static int digitA(int N, int D, int R) {
    while (R-- > 0) {
        N = N % D;
        N = N * 10;
    }
    return N / D;
}

```

Replacing multiplications and divisions by adding/subtracting and shifting results in

```
while (R-- > 0) {
    while (N >= D) N = N - D;
    N = ((N << 2) + N) << 1;
}
int digit = 0;
while (N > D) { digit++; N = N - D; }
return digit;

```

As `R` is `-1` after the first loop, it can be used to replace `digit` afterwards. With avoiding shifting by more than 1 and introducing intermediate `P` the code becomes

```
while (R-- > 0) {
    while (N >= D) N = N - D;
    int P = ((N + N) << 1) + N;
    N = P << 1;
}
for ( ; N >= D; N = N - D) R++;
return R;

```

The number of loop runs can be reduced by "splitting the decimal digit into two digits with base 5 and 2". The above manual division schema would become something like

```
10 / 17 = 2-Digit 0, Remainder 10 (x 5)
50 / 17 = 5-Digit 2, Remainder 16 (x 2)
32 / 17 = 2-Digit 1, Remainder 15 (x 5) --> 10-digit = 2*2 + 1
75 / 17 = 5-Digit 4, Remainder 7 (x 2)
14 / 17 = 2-Digit 0, Remainder 14 (x 5) --> 10-digit = 4*2 + 0
70 / 17 = 5-Digit 4, Remainder 2 (x 2)
4 / 17 = 2-Digit 0, Remainder 4 (x 5) --> 10-digit = 4*2 + 0
etc.

```

As only the R-th decimal digit is to be returned, only the R-th 5-digit before the R-th 2-digit is required to compose the R-th decimal digit.

```
int P=N = ((N+N)<<1)+N; // N = N * 5
for (Q=P^P; N >D; N -=D) Q++; // Q=digit(5)
//...
return (Q<<1) + R;

```

The rest is some "obfuscation"

* `P^P` is zero - inspired by machine code where XORing may be the most efficient way to set a register to zero :-)
* The line `while (P >=D) P -=D;` is the same as `P=N;` \- but is more "smiling" :-)
> 3 votes

# Answer
## Mathematica: 36 chars

```
f = RealDigits[#1/#2, 10, 1, -#3][[1, 1]] &

```

Test case:

```
f[1, 70000, 5]

```

> 1
> 2 votes

# Answer
# Python: 96 bytes

The following code counts the number of digits after the decimal point, e.g. for `N = 3` and `D = 17`, `fracnum(N,D,7) = 5` since N/D = 0.176470588235.
```
def fracnum(N,D,R):
    v, d = abs(N)*10, abs(D)
    while R:
        (v, r, R) = (v*10, v, R-1) if v < d else ((v%d)*10, v//d, R-1)

    return r

```

This function can be written more compact as:

```
def f(N,D,R):
 v,d=abs(N)*10,abs(D)
 while R:v,r=(((v%d)*10,v//d),(v*10,v))[v<d];R-=1
 return r

```
> 1 votes

# Answer
## Awk: 38

```
BEGIN{b=n/d"";print substr(b,r+2,1)}

```

Called by the slightly cumbersome `awk -f division.awk -v n=? -v d=? -v r=?` where `?` represents the variable you want in there. Note that this is limited by precision, so choice of `1 4 3` would result in a blank line.
> 1 votes

# Answer
## PHP — 54 (Exact precision)

```
echo bcdiv(bcmul(bcpow(10,$r+1),abs($n)),abs($d))[$r];

```

## PHP — 41 (Not so exact precision (eventual floating point errors))

```
echo strval(abs(pow(10,$r+1)*$n/$d))[$r];

```
> 0 votes

# Answer
# Mathematica ~~63~~ 65

This now handles rational numbers close to zero. Should work to (one million places - no. places to the left of decimal point).

```
f[n_,d_,r_]:=({w,z}=RealDigits[N[n/d,10^6]];If[z+r<1,0,w[[z+r]]])

```

**Testing**

The following returns the digits at positions `min` through `max`, allowing for easy checking of results.

```
g[n_, d_, {min_, max_}] := Grid@{{"num", "den", "decimal", "digits " <> ToString@min <>
" to " <> ToString@max}, {n, d, N[n/d, max], Table[f[n, d, k], {k, min, max}]}}

```

Verify the digits of 1/7 from 3 to 7 places to the right of the decimal point.

```
g[1, 7, {3, 7}]

```

---

```
g[1, 7000, {3, 6}]

```

---

```
g[1, 2, {1, 5}]

```
> 0 votes

# Answer
## Python: 69 bytes

```
def f(N,D,R):
    return ('%.{0}f'.format(R+1)%(float(N)/float(D)))[-2]

```

(first time posting here, please be gentle for any formatting/misc errors :D)
> 0 votes

# Answer
# BASH - 52

```
f=$(echo "scale=$R; $N/$D"|bc -l)
n=${f:$((${#f}-1))}

```
> 0 votes

# Answer
## JavaScript - 40

```
function f(n,d,r){return(n/d%1+'')[r+1]}

```
> 0 votes

---
Tags: code-golf, arithmetic
---


title: Just Another Polyglot Hacker!

text:
# Question
Title: Just Another Polyglot Hacker!
Make a program which prints `just another #{LANG} hacker` where `#{LANG}` is the name of the language with which the program is being run.

For example, if I run your program with Bash, I'd expect `just another Bash hacker` as the output, but when running the same program through C++, I'd expect the output to be `just another C++ hacker`.

Your program must run in and produce correct output in at least **two** different languages.

---

**This is in no way a duplicate of the other suggested question, Write a polyglot that prints the language's name;** that question asks for a rather short (and in my opinion) uninteresting output, increasing the easiness of writing and number of languages in an answer, and then it assesses them (these polyglots) based on the source's length!

A correct response to this question, however, would produce longer outputs, and thus would have actually been fairly challenging and fun to write and it would be more difficult to add languages to your polyglot. I then assess the polyglots in a natural way; by the number of languages they support!

I think that this will lead to very different answers being submitted on either question, but also different uses for these answers; the programs which will be submitted here are the type of programs which would be flaunted around the internet for their ingenuity and creativity, "look! Here's a guy who can pull off a swaggy polyglot in 4 different languages! They're cool!"

When I asked this question, I thought I'd put a twist on the popular and well known Just Another Perl Hacker competition, but add some creativity and an extra "Wow!" factor; JAPH programs are often sported as signatures in forums etc., and I believe entries here will inspire similar use, unlike entries for the other question.

Also, because this isn't a form of code-golf like the other question, but I'm actually assessing answers on the number of languages they support, I believe we can expect some rather incredible entries, making use of language features and loopholes we never knew existed!

---

**Rules:**

* *Two different versions of the same language only count separately if:*
    + You print out the version as well as the language name, for each version.
    + You detect which version is running thraough a less trivial method than running a `ver()` function or similar built-in of your language.
    + The two have different major version numbers.

For example, if you say your program runs in both Python 3.4.1 and 2.7.8, here are the necessary outputs:

Python 3.4.1

```
just another Python 3.4.1 hacker

```

Python 2.7.8

```
just another Python 2.7.8 hacker

```

If your program doesn't produce the above outputs for each version, then you cannot list the two separate versions as different languages under which your code runs.

* You may *not* have any errors on the *maximum* level of warning in any of the languages.
* Program must terminate.

---

# Winner:

* Whoever's (valid) answer supports the most languages. In the case of a tie, the shorter answer (by program byte count) wins.

# Answer
> 11 votes
# C, C++, Perl, Bash – 230

```
#include <stdio.h>
#define c const char*\
s="just another %s hacker\n"
//bin/test;printf "$s" Bash;exit
int main(){c;printf(s,sizeof'a'-1?"C":"C++");}
/*==;seek DATA,0,0;@a=readline DATA;eval'$'.$a[2];printf $s,"Perl";
__DATA__*/

```

This was fun! :-)

230 chars including a newline at end of file. To run, save as both `poly.c` *and* `poly.cpp` and do:

```
$ gcc -Wall -Wextra -pedantic poly.c && ./a.out
just another C hacker
$ g++ -Wall -Wextra -pedantic poly.cpp && ./a.out
just another C++ hacker
$ perl poly.c
just another Perl hacker
$ bash poly.c
just another Bash hacker

```

# Answer
> 2 votes
# ANSI C/C++

```
#ifdef __cplusplus
#    include <iostream>
#    define LANG "C++"
#    define PRINT(text) { std::cout << text; }
#else
#    include <stdio.h>
#    define LANG "C"
#    define PRINT(text) { printf("%s", text); }
#endif

int main(void) {
    PRINT("just another ");
    PRINT(LANG);
    PRINT(" hacker\n");

    return 0;
}

```

Compiling and executing:

```
$ gcc -ansi -Wall -Wextra -pedantic -o prog-c prog.c
$ ./prog-c
just another C hacker
$ g++ -ansi -Wall -Wextra -pedantic -o prog-cpp prog.c
$ ./prog-cpp
just another C++ hacker

```

# Answer
> 2 votes
# BASH + BrainF\*ck + PHP, 269 characters

```
#><?="Just another PHP hacker\n";die();?><
echo Just another BASH hacker #++++++++++[>+++++++>++++++++++++>++++++++++>+++++++++++>+++>+<<<<<<-]>++++.>---.--.+.>>>++.<<---.>.+.<<.>+++++++.---.>+++.>.<<<<<++++[>--<-]>.++++.>>>>.<<+++.-------.++.>-------.<++.>+++++++.>>.

```

Running the program:

```
$ php langs.sh
#>Just another PHP hacker
$ ./2langs.sh
Just another BASH hacker
$ bf 2langs.sh
Just another BF hacker

```

A bit of stretching the rules with that PHP one, but it seems to work. I can fix it if it doesn't count.

# Answer
> 1 votes
# JavaScript, HTML, BF

```
<!--
    // > to fix previous comment delim
    /*
        ++++++++++[>+++++++>++++++++++++
        >++++++++++>+++++++++++>+++>+<<<<<<-]>++++
        .>---.--.+.>>>++.<<---.>.+.<<.>+++++++.---
        .>+++.>.<<<<<++++[>--<-]>.++++.>>>>.<<+++.
        -------.++.>-------.<++.>+++++++.>>.
    */
    alert('Just another JavaScript hacker')
// --> Just another HTML hacker

```

Relies on the fact that most JS implementations ignore `<!--`.

BF code shamelessly stolen from @Tyzoid, all credit to him :-)

Make sure your BF interpreter supports pointer wrapping.

# Answer
> 0 votes
# Lua 5.3/5.2/5.1/5.0/4.0/3.2

You said as long as I don't use `_VERSION` it is fine

```
print("Just another Lua"..(string and(loadstring"return 0//0"and"5.3"or(_ENV and"5.2"or(string.gmatch and"5.1"or"5.0")))or tremove(next({[{"4.0","3.2"}]=1},nil))).." hacker")

```

---
Tags: code-challenge, polyglot
---


title: Pascal's Trapezoid

text:
# Question
Title: Pascal's Trapezoid
Write a function which for any given input array of numbers and a row number r, returns the r-th vector or array where each subsequent vector or array is constructed from the previous following the rules used in Pascal's Triangle. For example, for an input vector of \[3 1 2\] and a row number of 1 (indicating the 'next' row), the correct return vector or array is \[3 4 3 2\].

As an example, a Clojure solution to this problem might be:

```
(defn pascals-trapezoid-row [r n]
  (last (take (+ n 1) ((fn p [c] (cons c (lazy-seq (p (flatten (conj [(first c)] (map #(apply +' %) (partition 2 1 c)) [(last c)] )))))) r))))

```

The winning and accepted solution will be the one with the fewest number of characters in the solution code. Legibility is not a requirement. You're on your honor as to whether or not your proposed solution actually works, but remember that while cheaters often win nobody likes them very much, and karma is real (except in Fortran). Solutions must be posted by 07-Jan-2014 at 12:00 noon Eastern Standard Time (-5 timezone) to be considered. Extra credit (i.e. upvotes) will be awarded by me (and perhaps others) for interesting or novel solutions, including but not limited to those done in unusual languages, one-liners, unbelievably ugly solutions, unbelievably beautiful solutions, and anything I happen to like. I will not downvote any answer, although I make no guarantees about what others may do.

GO!

# Answer
> 4 votes
## Golf-Basic 84 - 10 characters

Executed from a TI-84 calculator.

```
i`N,Rd`N11

```

**Sample run**

```
?(3;1;2)            <== Array of numbers
?1                  <== Row number
            3432

```

# Answer
> 2 votes
## APL (16 / 14)

```
{{2+/0,⍵,0}⍣⍺⍨⍵}

```

Takes the vector as the right argument, and the row number as the left argument, like so:

```
      1{{2+/0,⍵,0}⍣⍺⍨⍵}3 1 2
3 4 3 2
      2{{2+/0,⍵,0}⍣⍺⍨⍵}3 1 2
3 7 7 5 2
      3{{2+/0,⍵,0}⍣⍺⍨⍵}3 1 2
3 10 14 12 7 2

```

If I get to take input from the keyboard, instead of as a function, I can shave off two characters:

```
{2+/0,⍵,0}⍣⎕⍨⎕

```

Takes the vector on the first line and the row number on the second.

# Answer
> 1 votes
### GolfScript, 14 characters

```
{[0\{.@+\}/]}*

```

Takes input (vector plus number of rows) on top of stack and replaces that by the result. Example (also online):

```
[3 1 2] 3    {[0\{.@+\}/]}*      # -> [3 10 14 12 7 2]

```

# Answer
> 1 votes
## R, 45

```
function(x,r){for(i in 1:r)x=c(x,0)+c(0,x);x}

```

Example usage:

```
fun <- function(x,r){for(i in 1:r)x=c(x,0)+c(0,x);x}

fun(c(3, 1, 2), 1)
[1] 3 4 3 2

fun(c(3, 1, 2), 2)
[1] 3 7 7 5 2

fun(c(3, 1, 2), 5)
[1]  3 16 37 50 45 28 11  2

```

# Answer
> 1 votes
## Ruby, 51

```
a=eval$_;a.pop.times{a<<j=0;p a.map!{|i|(v=j)+j=i}}

```

Run from command line with `[array,R]` as input. It shows each increment of `R` along the way. The last line is the solution.

For example, if the array is `[3,1,2]` and `R=7`:

```
$ ruby -ne 'a=eval$_;a.pop.times{a<<j=0;p a.map!{|i|(v=j)+j=i}}' <<< [3,1,2,7]
[3, 4, 3, 2]
[3, 7, 7, 5, 2]
[3, 10, 14, 12, 7, 2]
[3, 13, 24, 26, 19, 9, 2]
[3, 16, 37, 50, 45, 28, 11, 2]
[3, 19, 53, 87, 95, 73, 39, 13, 2]
[3, 22, 72, 140, 182, 168, 112, 52, 15, 2]   <-- answer

```

For the same char count but different calling convention:

```
lambda{|a,r|r.times{a<<j=0;a.map!{|i|(v=j)+j=i}};a}

```

# Answer
> 0 votes
## iX2Web, 94

```
**iX2004FB 800345MTAJ Tj18fAkwDQ oxMAlSPXx8 CTANCjIyCU 89W05dKjEx fEMJMA0KMw lbT118XzAJ MA0K=*

```

Not likely to beat my Golf-Basic solution. Makes up for it with pretty GUI and output. Windows only.

---
Tags: code-golf
---


# Question
Title: The most pointless shell command you can concoct, based upon a often used shell command
Let's waste some time coming up with stupid ideas which are close cousins of good ideas.

* Your useless command doesn't have to fit any minimum or maximum length.
* Do, however, try to turn it into a one-liner if you can.
* No particular requirement for what shells and utilities are used, within reason.
* He who wins, wins.
* More rules will be added if they are added.

# Answer
> 3 votes
Mine is the inverse of "print the kernel arguments you booted with on Linux":

```
cat /proc/cmdline
# turns into...
fgrep -x -f <(awk -F\= 'BEGIN { RS = " "} ; {print $1"="}' </proc/cmdline)\
-v <(curl 'https://www.kernel.org/doc/Documentation/kernel-parameters.txt'
2>/dev/null | awk '/\t+[a-z._]+=/ {print $1}' | tee test2) | tr '\n' ' ' &&
echo

```

# Answer
> 2 votes
```
ls > /dev/null

```

Simple yet utterly pointless. :-P

For people who don't know shell commands: `ls` lists the files in a directory, and `> /dev/null` basically hides the output.

# Answer
> 2 votes
Once or twice a week i tend to misspell `ls` so i run `sl`. It's not installed by default in Ubuntu (or perhaps other), so if no magic happens try installing it.

It's quite cool, at least the first few times, as it behaves differently with some common options to `ls` as well and it seems to have blocked signals so you cannot quit it until it's shown you what it can do...

# Answer
> 2 votes
Not sure if invoking python counts. This'll start a web server, open your default browser, and show the information you'd usually see on the console **`:-)`**

```
python -m SimpleHTTPServer &> index.html & x-www-browser localhost:8000

```

Press F5 a few times, and...

> 127.0.0.1 - - \[31/Dec/2013 20:27:59\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:02\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:03\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:03\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:03\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:03\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:04\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:04\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:04\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:04\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:04\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:05\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:05\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:05\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:05\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:06\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:06\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:07\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:07\] code 404, message File not found 127.0.0.1 - - \[31/Dec/2013 20:28:07\] "GET /favicon.ico HTTP/1.1" 404 - 127.0.0.1 - - \[31/Dec/2013 20:28:07\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:08\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:08\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:08\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:08\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:08\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:09\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:09\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:09\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:09\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:09\] "GET / HTTP/1.1" 200 - 127.0.0.1 - - \[31/Dec/2013 20:28:10\] "GET / HTTP/1.1" 200 -

To shut down the server, run the `fg` command, and then press Ctrl-C.

---
Tags: popularity-contest
---