text:
Solve the 15 Puzzle (the tile-sliding puzzle)
The 15 Puzzle is a famous puzzle involving sliding 15 tiles around on a 4x4 grid. Starting from a random configuration, the goal is to arrange the tiles in the correct order. Here is an example of a solved 15 Puzzle:
01 02 03 04
05 06 07 08
09 10 11 12
13 14 15

Each move on the puzzle is of the form Up/Down/Left/Right. The move "Down" consists of sliding the tile that is above the empty spot downward. The move "Right" consists of sliding a tile to the right, into the empty spot. Here is how the board looks after the moves Down and Right.
01 02 03 04
05 06 07 08
09 10    11
13 14 15 12

The goal of this challenge is to write a program that can output the series of moves needed to solve the 15 Puzzle. The winner is the program who solves the five test cases (below) in the fewest total moves. The generated solution does not need to be a perfect solution, it merely has to be better than the competitors. For each individual test case, the program should not take more than ten seconds on a reasonable machine.
Your program must be able to solve any puzzle that is solvable, I'm just using these five test cases as the scoring.
Your program will receive the unsolved 15 Puzzle as input in the format of a 2D array. The 2D array can be formatted according to the language used, or changed if the language does not have 2D arrays. The first element of the first sub-array will be the number in the upper left, and the last element of the first sub-array will be the number in the upper right. A 0 will be the empty space.
As output, your program should print a list of moves in the order that they need to be performed. Each step should be numbered in order to increase the usability of the results.
EDIT: Based on comments, I will allow output to be in either the form of Down/Up/etc or in the form of the coordinates of the piece to move. As this is not code golf, the most important part is to solve the puzzle.
Some other general rules involve no using an outside source, etc.

Test Case 1
([5,1,7,3],[9,2,11,4],[13,6,15,8],[0,10,14,12])

Example Output:
1: Down
2: Down
3: Down
4: Left
....

Test Case 2
([2,5,13,12],[1,0,3,15],[9,7,14,6],[10,11,8,4])

Test Case 3
([5,2,4,8],[10,0,3,14],[13,6,11,12],[1,15,9,7])

Test Case 4
([11,4,12,2],[5,10,3,15],[14,1,6,7],[0,9,8,13])

Test Case 5
([5,8,7,11],[1,6,12,2],[9,0,13,10],[14,3,4,15])

Must the solver be able to solve more than just these 5?

Similar to http://codegolf.stackexchange.com/questions/1351/solve-the-8-puzzle

@Matt It should be able to solve any puzzle that is solvable. I thought that was implied, but I'll make it more explicit.

the way i am doing would be more easy to output the moves as single coordinates. like, you move that coordinate to the only legal move (the withe space). Is outputing in this way allowed?

@ajax333221 I like that style of output more since it is easier to generate from most languages.

Well, the output is not the most important part of the challenge (it's not code golf), so I will allow it.

Does and entire column or row shift count as 1 move, or 3 moves?

It counts as 3 moves.

PyPy, 195 moves, ~12 seconds computation
Computes optimal solutions using IDA* with a 'walking distance' heuristic augmented with linear conflicts. Here are the optimal solutions:
 5  1  7  3
 9  2 11  4
13  6 15  8
 0 10 14 12
Down, Down, Down, Left, Up, Up, Up, Left, Down, Down, Down, Left, Up, Up, Up

 2  5 13 12
 1  0  3 15
 9  7 14  6
10 11  8  4
Left, Down, Right, Up, Up, Left, Down, Down, Right, Up, Left, Left, Down, Right, Right, Right, Up, Up, Left, Left, Down, Left, Up, Up, Right, Down, Down, Left, Up, Up, Right, Right, Right, Down, Left, Up, Right, Down, Down, Left, Left, Down, Left, Up, Up, Right, Up, Left

 5  2  4  8
10  0  3 14
13  6 11 12
 1 15  9  7
Left, Up, Up, Right, Right, Down, Left, Up, Left, Left, Down, Down, Right, Right, Up, Left, Left, Down, Down, Right, Right, Up, Right, Up, Left, Left, Up, Right, Down, Down, Right, Down, Left, Left, Up, Up, Left, Up

11  4 12  2
 5 10  3 15
14  1  6  7
 0  9  8 13
Down, Left, Down, Right, Up, Left, Left, Left, Down, Down, Right, Right, Right, Up, Left, Left, Left, Down, Right, Right, Up, Left, Up, Up, Left, Down, Down, Right, Down, Right, Up, Up, Right, Up, Left, Left, Left, Down, Right, Right, Right, Up, Left, Down, Left, Down, Left, Up, Up

 5  8  7 11
 1  6 12  2
 9  0 13 10
14  3  4 15
Up, Right, Down, Left, Left, Down, Left, Up, Right, Up, Right, Down, Down, Right, Up, Up, Left, Left, Left, Down, Down, Down, Right, Right, Up, Right, Down, Left, Up, Left, Up, Left, Down, Right, Down, Left, Up, Right, Down, Right, Up, Up, Left, Left, Up

And the code:
import random

class IDAStar:
    def __init__(self, h, neighbours):
        """ Iterative-deepening A* search.

        h(n) is the heuristic that gives the cost between node n and the goal node. It must be admissable, meaning that h(n) MUST NEVER OVERSTIMATE the true cost. Underestimating is fine.

        neighbours(n) is an iterable giving a pair (cost, node, descr) for each node neighbouring n
        IN ASCENDING ORDER OF COST. descr is not used in the computation but can be used to
        efficiently store information about the path edges (e.g. up/left/right/down for grids).
        """

        self.h = h
        self.neighbours = neighbours
        self.FOUND = object()

    def solve(self, root, is_goal, max_cost=None):
        """ Returns the shortest path between the root and a given goal, as well as the total cost.
        If the cost exceeds a given max_cost, the function returns None. If you do not give a
        maximum cost the solver will never return for unsolvable instances."""

        self.is_goal = is_goal
        self.path = [root]
        self.is_in_path = {root}
        self.path_descrs = []
        self.nodes_evaluated = 0

        bound = self.h(root)

        while True:
            t = self._search(0, bound)
            if t is self.FOUND: return self.path, self.path_descrs, bound, self.nodes_evaluated
            if t is None: return None
            bound = t

    def _search(self, g, bound):
        self.nodes_evaluated += 1

        node = self.path[-1]
        f = g + self.h(node)
        if f > bound: return f
        if self.is_goal(node): return self.FOUND

        m = None # Lower bound on cost.
        for cost, n, descr in self.neighbours(node):
            if n in self.is_in_path: continue

            self.path.append(n)
            self.is_in_path.add(n)
            self.path_descrs.append(descr)
            t = self._search(g + cost, bound)

            if t == self.FOUND: return self.FOUND
            if m is None or (t is not None and t < m): m = t

            self.path.pop()
            self.path_descrs.pop()
            self.is_in_path.remove(n)

        return m

def slide_solved_state(n):
    return tuple(i % (n*n) for i in range(1, n*n+1))

def slide_randomize(p, neighbours):
    for _ in range(len(p) ** 2):
        _, p, _ = random.choice(list(neighbours(p)))
    return p

def slide_neighbours(n):
    movelist = []
    for gap in range(n*n):
        x, y = gap % n, gap // n
        moves = []
        if x > 0: moves.append(-1)    # Move the gap left.
        if x < n-1: moves.append(+1)  # Move the gap right.
        if y > 0: moves.append(-n)    # Move the gap up.
        if y < n-1: moves.append(+n)  # Move the gap down.
        movelist.append(moves)

    def neighbours(p):
        gap = p.index(0)
        l = list(p)

        for m in movelist[gap]:
            l[gap] = l[gap + m]
            l[gap + m] = 0
            yield (1, tuple(l), (l[gap], m))
            l[gap + m] = l[gap]
            l[gap] = 0

    return neighbours

def slide_print(p):
    n = int(round(len(p) ** 0.5))
    l = len(str(n*n))
    for i in range(0, len(p), n):
        print(" ".join("{:>{}}".format(x, l) for x in p[i:i+n]))

def encode_cfg(cfg, n):
    r = 0
    b = n.bit_length()
    for i in range(len(cfg)):
        r |= cfg[i] << (b*i)
    return r

def gen_wd_table(n):
    goal = [[0] * i + [n] + [0] * (n - 1 - i) for i in range(n)]
    goal[-1][-1] = n - 1
    goal = tuple(sum(goal, []))

    table = {}
    to_visit = [(goal, 0, n-1)]
    while to_visit:
        cfg, cost, e = to_visit.pop(0)
        enccfg = encode_cfg(cfg, n)
        if enccfg in table: continue
        table[enccfg] = cost

        for d in [-1, 1]:
            if 0 <= e + d < n:
                for c in range(n):
                    if cfg[n*(e+d) + c] > 0:
                        ncfg = list(cfg)
                        ncfg[n*(e+d) + c] -= 1
                        ncfg[n*e + c] += 1
                        to_visit.append((tuple(ncfg), cost + 1, e+d))

    return table

def slide_wd(n, goal):
    wd = gen_wd_table(n)
    goals = {i : goal.index(i) for i in goal}
    b = n.bit_length()

    def h(p):
        ht = 0 # Walking distance between rows.
        vt = 0 # Walking distance between columns.
        d = 0
        for i, c in enumerate(p):
            if c == 0: continue
            g = goals[c]
            xi, yi = i % n, i // n
            xg, yg = g % n, g // n
            ht += 1 << (b*(n*yi+yg))
            vt += 1 << (b*(n*xi+xg))

            if yg == yi:
                for k in range(i + 1, i - i%n + n): # Until end of row.
                    if p[k] and goals[p[k]] // n == yi and goals[p[k]] < g:
                        d += 2

            if xg == xi:
                for k in range(i + n, n * n, n): # Until end of column.
                    if p[k] and goals[p[k]] % n == xi and goals[p[k]] < g:
                        d += 2

        d += wd[ht] + wd[vt]

        return d
    return h

if __name__ == "__main__":
    solved_state = slide_solved_state(4)
    neighbours = slide_neighbours(4)
    is_goal = lambda p: p == solved_state

    tests = [
        (5,1,7,3,9,2,11,4,13,6,15,8,0,10,14,12),
        (2,5,13,12,1,0,3,15,9,7,14,6,10,11,8,4),
        (5,2,4,8,10,0,3,14,13,6,11,12,1,15,9,7),
        (11,4,12,2,5,10,3,15,14,1,6,7,0,9,8,13),
        (5,8,7,11,1,6,12,2,9,0,13,10,14,3,4,15),
    ]

    slide_solver = IDAStar(slide_wd(4, solved_state), neighbours)

    for p in tests:
        path, moves, cost, num_eval = slide_solver.solve(p, is_goal, 80)
        slide_print(p)
        print(", ".join({-1: "Left", 1: "Right", -4: "Up", 4: "Down"}[move[1]] for move in moves))
        print(cost, num_eval)

Would it be ok with you if I posted this solution on Rosetta Code and made sure that it was clear that it came from you and this post? I've been working on a Python based 15 puzzle solver for this RC task: http://rosettacode.org/wiki/15_puzzle_solver but it has been a challenge to get my code to solve a length 52 path in a reasonable length of time. Your solution runs in a few seconds. I was just thinking about doing my own IDA* version but yours already works. My current solver is based on A*. We just need a Python example. Anyway, let me know if it is ok to use this one.

@BobbyDurrett That's more than fine. It's not particularly clear code though.

Thanks. I think I will keep working on mine for my own education and post it too if I get it working well enough. I thought I might as well put yours up there so there is a Python example.

JavaScript (ES6) total steps 329 for all 5 test cases in ~1min
Edit Same strategy, different targets, better solution. Slower ...
This is more or less how I solve it by hand: using intermediate targets
After each target the relative tiles are not moved again
Each intermediate target is reached using a parametric BSF function. The 2 params are the loop condition L (repeat while true) and the select condition S (select what tile can be moved). The steps:

Place 1 top/left
Place 2
Place 5
Place 3,4 - top row ok
Place 9,13 - left column ok
All the rest

Side note I don't check the position of tiles 14 and 15. Unsolvable puzzles like [11,4,12,2,,15,10,3,5,,14,1,6,7,,0,9,8,13] will have 14 and 15 swapped.
F=b=>(
  s=[],
  [[_=>b[0]!=1, (o,p)=>b[o+p]]
  ,[_=>b[1]!=2, (o,p)=>(p=b[o+p])>1&&p]
  ,[_=>b[5]!=5, (o,p)=>(p=b[o+p])>2&&p]
  ,[_=>b[2]!=3|b[3]!=4, (o,p)=>(p=b[o+p])>2&&p!=5&&p]
  ,[_=>b[10]!=9|b[15]!=13, (o,p)=>(p=b[o+p])>5&&p]
  ,[_=>b[6]!=6|b[7]!=7|b[8]!=8|b[11]!=10|b[12]!=11|b[13]!=12|b[18]!=0, (o,p)=>(p=b[o+p])>5&&p!=9&&p!=13&&p]
  ].forEach(([L,S])=>{
    for(v={},v[b]=1,t=0,m=[];L();)
    {
      b.forEach((x,p)=>
        x=='0'&&[-1,5,1,-5].forEach((o,d)=>
          (x=S(o,p))&&(c=b.slice(0),c[p]=x,c[o+p]=0,v[k=''+c]?0:v[k]=m.push([c,s.concat(d)]))
        )
      );[b,s]=m[t++]
    }
  }),
  ,s.map((d,i)=>i+': '+'RULD'[d]).join('\n') // multi line output
  // ,s.map(d=>'RULD'[d]).join(' ') // single line output (easier to test)
)

Open snippet to test or play (Firefox only)

F=b=>(
  s=[],
  [[_=>b[0]!=1, (o,p)=>b[o+p]]
  ,[_=>b[1]!=2, (o,p)=>(p=b[o+p])>1&&p]
  ,[_=>b[5]!=5, (o,p)=>(p=b[o+p])>2&&p]
  ,[_=>b[2]!=3|b[3]!=4, (o,p)=>(p=b[o+p])>2&&p!=5&&p]
  ,[_=>b[10]!=9|b[15]!=13, (o,p)=>(p=b[o+p])>5&&p]
  ,[_=>b[6]!=6|b[7]!=7|b[8]!=8|b[11]!=10|b[12]!=11|b[13]!=12|b[18]!=0, (o,p)=>(p=b[o+p])>5&&p!=9&&p!=13&&p]
  ].forEach(([L,S])=>{
    for(v={},v[b]=1,t=0,m=[];L();)
    {
      b.forEach((x,p)=>
        x=='0'&&[-1,5,1,-5].forEach((o,d)=>
          (x=S(o,p))&&(c=b.slice(0),c[p]=x,c[o+p]=0,v[k=''+c]?0:v[k]=m.push([c,s.concat(d)]))
        )
      );[b,s]=m[t++]
    }
  }),
  //,s.map((d,i)=>i+': '+'RULD'[d]).join('\n') // multi line output
  //,s.map(d=>'RULD'[d]).join(' ') // single line output (easier to test)
  s
)
B.value=PZ.value,show()

function show(s='') {
  var b = eval(B.value)
  var t = b.map((c,i)=>''+c+'	').join()
  .replace(/,,/g,'

').replace(/,/g,'')
  G.innerHTML='
'+t+'
'
  S.value=s
}
function solve() {
  show('... solving ...')
  var b = eval(B.value)
  setTimeout(_=>{
    var s = F(b), zp = b.indexOf(0), sp = 0
    S.value=s.map(d=>'RULD'[d]).join(' ');
    (A=_=>{
      d=[-1,5,1,-5][m=s[sp++]]
      b[zp]=b[zp+d],zp+=d,b[zp]=0
      var t = b.map((c,i)=>''+c+'	').join()
      .replace(/,,/g,'

').replace(/,/g,'')
      G.innerHTML='
'+t+'
'
      if (sp<s.length)
        setTimeout(A, 300);
    })()
  },100)
}
#D { position: relative }
#D input { position: absolute; width: 300px; top:2px; left:2px; border:0 none }
#D select { position: relative; width: 400px; height:1.8em; top:0; left:0; }
textarea{ width: 600px; height: 40px }
td{ width: 1.5em; text-align:right }
Puzzles (select or edit)

<select id=PZ onchange="B.value=PZ.value,show()">
<option>[5,1,7,3,,9,2,11,4,,13,6,15,8,,0,10,14,12]</option>
<option>[2,5,13,12,,1,0,3,15,,9,7,14,6,,10,11,8,4]</option>
<option>[5,2,4,8,,10,0,3,14,,13,6,11,12,,1,15,9,7]</option>
<option>[11,4,12,2,,5,10,3,15,,14,1,6,7,,0,9,8,13]</option>
<option>[5,8,7,11,,1,6,12,2,,9,0,13,10,,14,3,4,15]</option>
</select>
<button onclick="solve()">Solve</button>
<input id=B>

<textarea id=S></textarea>

Test suite In Firefox/FireBug console
T=~new Date
;[[5,1,7,3,,9,2,11,4,,13,6,15,8,,0,10,14,12]
,[2,5,13,12,,1,0,3,15,,9,7,14,6,,10,11,8,4]
,[5,2,4,8,,10,0,3,14,,13,6,11,12,,1,15,9,7]
,[11,4,12,2,,5,10,3,15,,14,1,6,7,,0,9,8,13]
,[5,8,7,11,,1,6,12,2,,9,0,13,10,,14,3,4,15]]
.forEach(t=>console.log(t+'',F(t)))
console.log('Time ms ',T-=~new Date)

Output
"5,1,7,3,,9,2,11,4,,13,6,15,8,,0,10,14,12" "D D D L U L D L U R R U U L D D L U U"
"2,5,13,12,,1,0,3,15,,9,7,14,6,,10,11,8,4" "D R U L U L L U R D L D R D L U R U L D R D L U R U L U R R R D L L U R D R U L L D L D R U U L D R U R D L U L D D R R U L U L D R U L"
"5,2,4,8,,10,0,3,14,,13,6,11,12,,1,15,9,7" "R U U L D D R U L D D R U U L L D D R U L D L U U R R D L U R R D L L U L D D R U U L D D R U U U R R D L L U R R D L L L U R D D L U R D R U U L L D R D L U U"
"11,4,12,2,,5,10,3,15,,14,1,6,7,,0,9,8,13" "D L D R U L D D R U L L D L U R R D L U R U R D L U R U L L D R D L L D R U U L D R D L U R U U L D R R U L D R R U L L D L D R U U L D R R D L L U U R D R U L L"
"5,8,7,11,,1,6,12,2,,9,0,13,10,,14,3,4,15" "D D R U L L L D R U R D L U U R R D L U L U R D D L U U L D D D R U U L D D R U U U R D R U L D D L U U R D R U L D L L D R U L U R D L D R R U L L U R D D L U U"
"Time ms " 62234

I started working on this problem and wanted to contribute with my code so far.
As stated by Gareth, the problem is comparable to the 8-tile puzzle and so the code is based on the magnificient solution of Keith Randall and thus in Python.
This solution can solve all 5 test cases with a total sum of less than 400 moves, and other puzzles, too. It contains an optimized and a brute force solution. The code is a bit bloated by now. Output is abbrevated like "llururd.." Hope its helpful.
http://www.penschuck.org/joomla/tmp/15Tile.txt (explanation)
http://www.penschuck.org/joomla/tmp/tile15.txt (python code)
# Author: Heiko Penschuck
# www.penschuck.org
# (C) 2012

# import os;os.chdir('work')
# os.getcwd()

# def execfile(file, globals=globals(), locals=locals()):
#   with open(file, "r") as fh: exec(fh.read()+"\n", globals, locals)
#
#
# execfile("tile15.py");
#
## run these
# solve_brute();
# solve();

# some boards to play with
board2=(15,14,7,3,13,10,2,9,11,12,4,6,5,0,1,8);
# best: 76(52)
#    72(56)
#   68(51)      uurddlurrulldrrdllluuruldrddlururulddruurdllldrurddlurdruuldrdluurdd

board3=(13, 8, 9, 4, 15, 11, 5, 3, 14, 6, 12, 7, 1, 10, 2, 0)
# best: 106(77)
#best: 90(64)   ullldruuldrrdrlluurulldrrdldluruulddrulurrdrddlluuurdldrrulddrulldrurullldrdluurrrddllurdr

board4=(4, 8, 12, 1, 13, 7, 3, 11, 9, 15, 6, 14, 5, 2, 10, 0) ;# best  100(74)

board5=(15,2,3,4,5,6,7,8,9,10,11,12,13,1,14,0); # best 44(32)
board6=( 1, 2,  3,  4, 6, 11,  0, 12, 8, 14,  9, 13, 5, 10,  7, 15);

# testcases
board7=(5,1,7,3,9,2,11,4,13,6,15,8,0,10,14,12); #   15 (7)
board8=(2,5,13,12,1,0,3,15,9,7,14,6,10,11,8,4); #  124 (94)
board9=(5,2,4,8,10,0,3,14,13,6,11,12,1,15,9,7) ; #  72 (56)
board10=(11,4,12,2,5,10,3,15,14,1,6,7,0,9,8,13) ;# 71 (57)
board11=(5,8,7,11,1,6,12,2,9,0,13,10,14,3,4,15) ;# 99 (73)

board12=(1,2,3,4,5,6,7,8,9,10,11,12,13,0,14,15); #pretty simple board
board13=(4, 10, 5, 12, 11, 7, 15, 2, 13, 1, 14, 8, 6, 3, 9, 0)

board=board3 ; # used by solve()
bboard=list(board) ;# used by solve_brute()

# init
clean=(1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0)
i=0;
solution={};
invsolution={};
E={board:0}

# derived from Keith Randall 8-tile solution
# a: a board, d: offset to move from i: index in board
def Y(a,d,i):
 b=list(a); # b is now an indexable board
 b[i],b[i+d]=b[i+d],0; # make a move (up down left right)
 b=tuple(b); # now back to searchable
 if b not in E:E[b]=a;# store new board in E

def Calc():
 ii=0;
 # memory error when x is 21
 for x in ' '*14:
  if ii>10:
   print(ii);
  ii+=1
  for a in E.copy():
   # for all boards, make possible moves (up,left,right,down) and store the new boards
   i=list(a).index(0)
   if i>3:Y(a,-4,i)
   if i%4:Y(a,-1,i)
   if i%4 <3:Y(a,1,i)
   if i<12:Y(a,4,i)

def weigh(a,goal):
    factor=[26,8,4,6, 8,8,4,4, 4,4,1,1, 3,2,1,0]
    weight=0;
    for element in a:
        i=list(a).index(element);
        ix,iy=divmod(i,4); # ist
        if element == 0:
            # special for gap
            weight=weight+ix;
            #weight+=(ix+iy)
            continue;
        i=list(a).index(element);
        ix,iy=divmod(i,4); # ist
        j=list(goal).index(element);
        sx,sy=divmod(j,4); # soll
        #k=list(a).index(0); # gap
        #kx,ky=divmod(k,4)
        # try solving from topleft to bottom right (because clean board has gap at bottomright)
        tmp= abs(sx-ix)*abs(sx-ix)*factor[j]+ abs(sy-iy)*abs(sy-iy)*factor[j]
        #tmp += ((sx!=ix )& (sy!=iy)) *(4-sx)*(4-sy)*4
        weight+=tmp
        #(10-sx-sy-sy)
        # 8*abs(sx-ix) + (16-j)*(sx!=ix)
        #print('%2d   %2d_%2d (%2d_%2d)=> %d'%(element,i,j,(sx-ix),(sy-iy),weight))
    return weight

# read numbers seperated by a whitespace
def readboard():
    global E,D,board,clean,i
    reset()
    g=[]
    for x in' '*4:g+=map(int,input().split())
    board=tuple(g)

# read 'a' till 'o'
def readasciiboard():
    global E,D,board,clean,i
    trans={"0":0,"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9,"j":10,"k":11,"l":12,"m":13,"n":14,"o":15}
    reset()
    g=[]
    vec=tuple(input().split());
    for x in vec: g.append(trans[x])
    board=tuple(g)

def printasciiboard(a):
    trans={"0":0,"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9,"j":10,"k":11,"l":12,"m":13,"n":14,"o":15}
    itrans={}
    for x in trans: itrans[trans[x]]=x
    g=[]
    for x in a: g.append(itrans[x])
    for i in(0,4,8,12): print('%s %s %s %s'%tuple(g[i:i+4]))

# find the board with the smallest weight
def minimum():
    global minn,E,clean
    minn=1111111;# start with a huge number
    qq=board
    for q in E:
        if weigh(q,clean) < minn:
            minn=weigh(q,clean)
            qq=q
    return qq

# run this and printsolution()
# (you might have to reverse the order of the printed solution)
def solve():
    global start,board,E,clean,minn,solution
    start=board;
    solution={};
    E={ board:0 }
    for x in range(0,11):
        Calc(); # walks all possible moves starting from board to a depth of 10~20 moves
        if clean in E:
            print('Solution found')
            q=clean;
            tmp=[];
            while q:
                tmp.append(q)
                q=E[q]
            for x in reversed(tmp):
                solution[len(solution)]=x;
            printsolution();
            return
        q=minimum();  # calculates the "weight" for all Calc()-ed boards and returns the minimum
        #print("Len %3d"%len(E))
        print("weight %d"%minn)
#       stitch solution
        newboard=q;
        tmp=[];
        while q:
            tmp.append(q)
            q=E[q]
        for x in reversed(tmp):
            solution[len(solution)]=x;
        board=newboard;
        E={board:0}; #reset the Calc()-ed boards
    print("No Solution")

# collects and prints the moves of the solution
# from clean board to given board
# (you have to reverse the order)
def printsolution():
    global invsolution,solution,moves,clean,start
    moves=""
    g=start; # start from board to clean
    y=g
    #invsolution[clean]=0;
    for x in solution:
        # uncomment this if you want to see each board of the solution
        #print(g);
        g=solution[x];
        #sys.stdout.write(transition(y,g))
        if (transition(g,y)=="E"): continue
        moves+=transition(g,y)
        # or as squares
        #print('%10s %d %s'%("step",len(moves),transition(g,y)));
        #print(" %s -- %s "%(y,g))
        #for i in(0,4,8,12): print('%2d %2d %2d %2d'%g[i:i+4])
        y=g
    llen=len(moves)
    print(" moves%3d "%llen)
    print(moves)
    # processing moves. funny, but occysionally ud,du,lr or rl appears due to the stitching
    while 'lr' in moves:
        a,b,c=moves.partition('lr')
        moves=a+c
        llen-=2
    while 'rl' in moves:
        a,b,c=moves.partition('rl')
        moves=a+c
        llen-=2
    while 'ud' in moves:
        a,b,c=moves.partition('ud')
        moves=a+c
        llen-=2
    while 'du' in moves:
        a,b,c=moves.partition('du')
        moves=a+c
        llen-=2
    # processing moves. concatenating lll to 3l
    while 'lll' in moves:
        a,b,c=moves.partition('lll')
        moves=a+' 3l '+c
        llen-=2
    while 'rrr' in moves:
        a,b,c=moves.partition('rrr')
        moves=a+' 3r '+c
        llen-=2
    while 'uuu' in moves:
        a,b,c=moves.partition('uuu')
        moves=a+' 3u '+c
        llen-=2
    while 'ddd' in moves:
        a,b,c=moves.partition('ddd')
        moves=a+' 3d '+c
        llen-=2

    while 'll' in moves:
        a,b,c=moves.partition('ll')
        moves=a+' 2l '+c
        llen-=1
    while 'rr' in moves:
        a,b,c=moves.partition('rr')
        moves=a+' 2r '+c
        llen-=1
    while 'uu' in moves:
        a,b,c=moves.partition('uu')
        moves=a+' 2u '+c
        llen-=1
    while 'dd' in moves:
        a,b,c=moves.partition('dd')
        moves=a+' 2d '+c
        llen-=1
    print(" processed:%3d "%llen)
    print(moves)

    return

def transition(a,b):
    # calculate the move (ie up,down,left,right)
    # between 2 boards (distance of 1 move and a weight of 1 only)
    i=list(a).index(0);
    j=list(b).index(0);
    if (j==i+1): return "l"
    if (j==i-1): return "r"
    if (j==i-4): return "d"
    if (j==i+4): return "u"
    #print("transition not possible")
    return "E"

###################################################

# below this line are functions for the brute force solution only
# added for comparision
#
# its using a global variable bboard and works destructively on it

def solve_brute():
    global bboard,board;
    bboard=list(board); # working copy
    move(1,0);move(2,1);
    move(3,14); # <== additional move, move 3 out of way
    move(4,2);move(3,6);
    gap_down();gap_down();gap_right();gap_right();gap_up();gap_up();gap_up();gap_left();gap_down();
    #first line solved
    print("first line");printbboard();
    move(5,4);move(6,5);move(7,14);move(8,6);move(7,10);
    gap_down();gap_down();gap_right();gap_right();gap_up();gap_up();gap_left();gap_down();
    #second line solved (upper half)
    print("2nd line");printbboard();
    move(9,15);move(13,8);move(9,9)
    gap_down();gap_left();gap_left();gap_up();gap_right();
    print("left border");printbboard();
    #left border solved
    move(10,15);move(14,9);move(10,10);
    gap_down();movegap(1+3*4);gap_up();gap_right();
    print("left half");printbboard();
    #left half solved

    #rotating last 4 tiles 5 times
    for x in ' '*5:
        gap_right();gap_down(); # gap is now on 15
        if (bboard==[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,0]):
            print("solution found");printbboard();
            return;
        gap_left();gap_up();
    print("No solution found");
    printbboard();
    return

def printbboard():
    global bboard
    for i in(0,4,8,12): print('%2d %2d %2d %2d'%tuple(bboard[i:i+4]))

def gap_up():
    global bboard
    i=bboard.index(0);
    if (i<4):
        print("Err up()")
        return
    bboard[i],bboard[i-4] = bboard[i-4] , 0 ;

def gap_down():
    global bboard
    i=bboard.index(0);
    if (i>11):
        print("Err down()")
        return
    bboard[i],bboard[i+4] = bboard[i+4] , 0 ;

def gap_left():
    global bboard
    i=bboard.index(0);
    if (i%4<1):
        print("Err left()")
        return
    bboard[i],bboard[i-1]= bboard[i-1] , 0 ;

def gap_right():
    global bboard
    i=bboard.index(0);
    if (i%4>2):
        print("Err right()")
        return
    bboard[i],bboard[i+1] = bboard[i+1] , 0 ;

def movegap(d):
    global bboard;
    # d: destination location (0-15)
    k=bboard.index(0);
    ky,kx=divmod(k,4);
    dy,dx=divmod(d,4);
    # moving the gap
    while (ky>dy):
        gap_up();ky-=1;
    while (ky<dy):
        gap_down();ky+=1;
    while (kx>dx):
        gap_left();kx-=1;
    while (kx<dx):
        gap_right();kx+=1;

def move(s,d):
    global bboard
    i=bboard.index(s);
    iy,ix=divmod(i,4);
    dy,dx=divmod(d,4);
    #moving a number
    while (ix<dx):
        move1right(s);
        print("1right ");
        ix+=1;
    while (ix>dx):
        move1left(s);
        ix-=1;
        print("1left ");
    while(iy<dy):
        move1down(s);
        print("1down ");
        iy+=1;
    while(iy>dy):
        move1up(s);
        print("1up");
        iy-=1;

def move1up(s):
    global bboard
    i=bboard.index(s);
    iy,ix=divmod(i,4);
    k=bboard.index(0);
    ky,kx=divmod(k,4);
    if (ky<iy):
        # above: move 1 above, then leftorright, then 1 down
        movegap(kx+4*(iy-1))
        movegap(ix+4*(iy-1))
        movegap(ix+4*iy)
        return; # fin
    if (ky==iy):
        # if equal, then first try 1 down
        # (not nescessary if gap is right of s)
        if (kx<ix):
            if (ky<=2):
                movegap(kx+4*(iy+1))
                movegap(ix+1+4*(iy+1)); # 1right 1down of s
                movegap(ix+1+4*(iy-1)); # 1right 1up of s
                movegap(ix+4*(iy-1));# right over s
                gap_down(); # fin
                return;
            # bottom border, must go up first
            movegap(kx+4*(iy-1));
            movegap(ix+4*(iy-1));
            gap_down();
            return; # fin
        else:
            movegap(ix+1+4*iy); # move 1 right of s
            gap_up()
            gap_left()
            gap_down();
            return; # fin
    movegap(ix+1+4*ky); # move 1 right of s
    movegap(ix+1+4*(iy+1)); # move 1 right and 1 down of s
    gap_up();
    gap_up();
    gap_left();
    gap_down();

def move1left(s):
    global bboard
    i=bboard.index(s);
    iy,ix=divmod(i,4);
    k=bboard.index(0);
    ky,kx=divmod(k,4);
    if (ky<iy):
        # if above gap move 1 over s
        if (kx<ix):
            movegap(kx+4*iy);
            movegap(ix+4*iy);
            return;# fin
        if (kx==ix):
            #gap over s
            if (ix<3):
                # try to move under s and then left
                if (iy<3):
                    movegap(ix+1+4*ky)
                    movegap(ix+1+4*(iy+1))
                    movegap(ix-1+4*(iy+1))
                    movegap(ix-1+4*iy)
                    movegap(ix+4*iy)
                    return; #fin
            # have to move left
            movegap(kx-1+4*ky)
            movegap(ix-1+4*iy)
            movegap(ix+4*iy)
            return;# fin
        # move 1 right of s
        if (iy==3):
            # cant go under, have to go left over
            movegap(kx+4*(iy-1))
            movegap(ix-1+4*(iy-1))
            movegap(ix-1+4*iy)
            movegap(ix+4*iy);
            return; #fin
        movegap(ix+1+4*(iy-1))
        gap_down();gap_down();gap_left();gap_left();gap_up();gap_right();
        return; #fin
    if (ky==iy):
        if (kx<ix):
            movegap(ix-1+4*iy)
            gap_right();
            return; # fin
        if (ky<3):
            gap_down();
            ky+=1;
        else:
            #have to move up
            movegap(ix+4*(iy-1))
            movegap(ix-1+4*(iy-1))
            movegap(ix-1+4*iy)
            gap_right();
            return; #fin
    # gap below s
    movegap(ix+4*(iy+1));
    gap_left();gap_up();gap_right();

def move1right(s):
    global bboard
    i=bboard.index(s);
    iy,ix=divmod(i,4);
    k=bboard.index(0);
    ky,kx=divmod(k,4);
    if (ky<iy):
        if (kx==ix):
            movegap(kx+1+4*ky)
            movegap(kx+1+4*iy)
            movegap(ix+4*iy);
            return; #fin
        movegap(kx+4*iy)
        if (kx>ix):
            movegap(ix+4*iy);
            return; #fin
        movegap(kx+4*(iy+1))
        movegap(ix+1+4*(iy+1))
        movegap(ix+1+4*iy);
        movegap(ix+4*iy);
        return; #fin
    if (ky==iy):
        if (kx<ix):
            if (ky>2):
                # bottom row, left of s, have to move 1 up
                gap_up()
                # move 1 right 1 up of s
                movegap(ix+1+4*(ky-1));
                gap_down()
                gap_left()
                return; # fin
            # first 1 down
            movegap(kx+4*(ky+1))
            # to the right of s
            movegap(ix+1+4*(ky+1))
            gap_up()
            gap_left()
            return; # fin
        # already 1 right of s
        movegap(ix+4*iy);
        return; #fin
    # move gap 1 right and 1 down of s
    movegap(kx+4*(iy+1))
    movegap(ix+1+4*(iy+1))
    gap_up();
    gap_left();

def move1down(s):
    global bboard
    i=bboard.index(s);
    iy,ix=divmod(i,4);
    k=bboard.index(0);
    ky,kx=divmod(k,4);
    if (ky<iy):
        # gap is over s, move it below
        if (kx==ix):
            if (ix>2):
                # right border, have to move 1 to the left
                movegap(kx+4*(iy-1))
                movegap(kx-1+4*(iy-1))
                movegap(kx-1+4*(iy+1))
                gap_up();
                return; #fin
            # move right of s
            movegap(kx+4*(iy-1))
            movegap(kx+1+4*(iy-1))
            movegap(kx+1+4*(iy+1))
            movegap(kx+4*(iy+1))
            gap_up(); #fin
        movegap(kx+4*(iy+1))
        movegap(ix+4*(iy+1))
        gap_up(); #fin
    if (ky==iy):
        gap_down();
        ky+=1;
    # gap is below s, move 1 under s
    movegap(ix+4*(iy+1))
    gap_up();
    #fin


text:
Ridiculous Runtime Errors
Write programs that produce crazy, obscure, ridiculous, or just plain nutty runtime errors.  Obfuscation and golfitude (shortness) not required.

solutions that look like they should work fine are better.
solutions that look like they should break one way but break another are better.
solutions that are nondeterministic are better as long as they are reproducible sometimes.
solutions with long distance between error cause and manifestation are better.
bonus points for producing errors that should be impossible.
bonus points for errors that crash the runtime (like making python segment fault) or operating system.

The unit of score shall be upvotes.
Addendum 1
Compiler misbehaviors are fine too.

Making Python segfault is easy: import sys; sys.setrecursionlimit(~-2**31); x=lambda x:x(x); x(x);

Peter: whoops.  I repurposed the question half way through writing it :S

...what about malbolge or INTERCAL?  i'm pretty sure they'd have some pretty insane errors, probably can do it with a single char as well.

This is definitely the best link to go for the solution: https://www.destroyallsoftware.com/talks/wat :-)

I've seen that one. :D

Possible duplicate of http://stackoverflow.com/q/1146014/736054.

There's a whole book on these for Java: http://www.javapuzzlers.com/

Also see http://codegolf.stackexchange.com/q/1956/7416

Damn, I have so many of them but I don't remember how to produce them... I've found a way to make EDT consistently generate a runtime exception during compilation, and I've got me some SQL where a comparison generates an overflow error but I never write down exactly how to get those :p

The obligatory PHP one (which still hasn't been fixed as of 5.4):
<?::

Outputs:
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM on line 1
Whaa?

I do like this one.  It might be my favorite error message.  Apart from the one time my friend tried to boot his windows laptop to the recovery partition, and it turned the entire screen into a white box with giant red letters spelling "ERROR".

Deliberate, but weird nevertheless: "Paamayim Nekudotayim would, at first, seem like a strange choice for naming a double-colon. However, while writing the Zend Engine 0.5 (which powers PHP 3), that's what the Zend team decided to call it. It actually does mean double-colon - in Hebrew!" http://php.net/manual/en/language.oop5.paamayim-nekudotayim.php

@HansEngel: Yes, it means double-colon in Hebrew. Using English for every token except this one makes sense because...? I guess I'd just have to ask the PHP team.

Sorry dude, but you are simply calling the static method/variable '' (empty string) from the class '' (empty string)

@IsmaelMiguel: It’s confusing because of the Hebrew, not because it’s wrong.

Still, there are better ones like this one: foreach($a as &$a);

@IsmaelMiguel: Thank you, please feel free to add an answer whenever

@minitech Thank you for your suggestion, but I don't think it would get any vote.

Nice easter egg, they make programming alive and fun.

@minitech Sorry, here is the actual error: foreach(array() as $a=>&$a);

Gcc compile error:
int main()
{
        long long long a;
}

error: long long long is too long for GCC

They just knew that somebody will try long long long, if long and long long are both valid.

I think "a is too long!" would have been a better error message, but this is still a great answer.

Windows Command Prompt
If you're happy and you know it clap your hands!

Output:

happy was unexpected at this time.

I tried that command to check the result, but it displayed ^V :( hard days these

@Fabricio, was that just from pressing CTRL+V to paste the line?  In Command Prompt, the keyboard "shortcut" for paste is ALT+SPACE, E, P.

PHP
$ cat error.php
<?php
function echo_string(string $string) {
    echo $string;
}
echo_string("Hello, world!");
$ php error.php
PHP Catchable fatal error:  Argument 1 passed to echo_string() must be an instance of string, string given, called in error.php on line 5 and defined in error.php on line 2

You cannot pass a string to a function, you have to pass a string instead!
Update: This code is NOT an error in PHP 7. Hover on/click/touch a spoiler to check why (contains spoilers about how the code works).

 A new feature known as scalar type declarations was added in PHP 7. This feature allows using scalar types in function declarations.

What the f*** php.

PHP is trying to get the class string (which is valid). Type-hinting (that thing that you are doing) only works for classes. Since the class string doesn't exist, it throws an error.

You can check here yours code working properly: http://sandbox.onlinephpfunctions.com/code/21fa0a717daedf220feacfda1303d07a5afa9278

@IsmaelMiguel: Yeah, I understand why it happens, but the error is still ridiculous in my opinion.

Then try array(''=>array()'').

bash
$ echo "Hello, world!"
bash: !": event not found

And you would think that bash would accept a simple "Hello, world!" program.

Explanation of this: strings passed in double quotes as arguments to programs in bash are expanded, meaning \echo hi`turns intohiinside of the double-quoted string.!is used as a prefix to [event designators](https://www.gnu.org/software/bash/manual/html_node/Event-Designators.html). So, bash tries to evaluate!"`, but can't find the referenced event.

Python 2.7
# Look I'm actually coding: see my happy face?
print ':)'

Generates the rather unhelpful:
SyntaxError: encoding problem: with BOM

How can a simple comment generate an error?

In latest Python interpreters: if first 2 lines starts with # and contain string coding: next word used as encoding description

Mathematica
When using Mathematica to create graphical output, one sometimes triggers error messages formatted according to specifications being used in the program itself. Here is a trivial example.
Rotate[f/0, .6]

That's not really an error message, though, is it? It's just the value Mathematica returns when you divide something by zero.

TI-89 Graphing Calculator
I discovered this when learning about implicit differentiation in high school calculus. If you input:
d(xy+x=0,x)

You get the following:
1 = 0

With this caveat, printed in tiny letters at the bottom of the screen:
Warning: May produce false equation

This happens because xy is not interpreted as x * y, but rather as its own symbol, xy.
Oddly, if you do d(xy=0,x), you get 0 = 0 with the same warning.

You can make the Haskell compiler's brain explode:
C:\Windows\system32>ghci
...
Prelude> :set -XExistentialQuantification
Prelude> data Foo = forall a. Foo a
Prelude> let foo f = 1 where Foo a = f

<interactive>:4:21:
    My brain just exploded
    I can't handle pattern bindings for existential or GADT data constructors.
    Instead, use a case-expression, or do-notation, to unpack the constructor.
    In the pattern: Foo a
    In a pattern binding: Foo a = f
    In an equation for `foo':
        foo f
          = 1
          where
              Foo a = f
Prelude>

Ruby
Rules abuse.
class StandardError

  def to_s
    words = File.open('/usr/share/dict/words'){|f|f.readlines.map &:chop}.sample(100)
    words.last.capitalize!
    super.gsub(/\w+/){words.pop}
  end

  to_s(3)

end

If run on OSX, produces, e.g.
$ ruby weird_runtime_error.rb
weird_runtime_error.rb:9:in `to_s': Sculpturation contingence explicate tappet(phonendoscope ethopoeia nannandrous) (ArgumentError)
    from weird_runtime_error.rb:9:in `<class:StandardError>'
    from weird_runtime_error.rb:1:in `<main>'

What on earth does that mean?

It means wrong number of arguments(1 for 0). It is expressing that through a language that is generated lazily and stochastically using English vocabulary with little regard for linguistic plausibility.

DOS Prompt
c:\>make love

gives you
Fatal Error: 'love' does not exist. Don't know how to make it.

Stumbled upon this while I was trying to insult my computer for being uncooperative. Made me kinda sad for a while until I found out, that this only happens if love does not exist. If it exists he will gladly make it.

This is actually dedicated to make utility, not DOS itself.

I get: make: *** No rule to make target 'love'.  Stop.

@agtoever You are running the wrong make.

I get: make: Fatal error: Don't know how to make target 'love' but that's on Unix. On DOS, I get make is not recognized as an internal or external command, operable program or batch file.

Bash (Quine error)
This error is a Quine in Bash!
$ bash: bash:: command not found...
bash: bash:: command not found...

Of course you must have the relevant locale (english here).

Mine did not print the ... at the end, so I had to omit it in the original input as well.

CSH
A really classical csh joke:
% make fire?
make: No match.

Bash - accurate recreation of a rare historical error message
echo -ne $(tail -n +257 /usr/src/linux*/drivers/char/lp.c | head -1 | cut -d '"' -f 2 | sed 's/%d/0/')

Output:
lp0 on fire

Requires the linux kernel source to be unpacked in the usual place.
Fun fact: i once received this message in earnest, when running an old ribbon printer.

Is it an error message, or just an output of a program?

@yo' the bash one-liner itself returns successfully, but the output it produces is a genuine error message; the script simply pulls the error from the printer driver source.

ah ok, that's a tricky thing to do :-)

Incidentally, the error means it's continuing to print to a paper jam, which is a fire hazard.

Ruby
Feel like it's weird that this can happen in a high-level language.
$*<<$*<<$**$/

produces
ArgumentError: recursive array join

C(++)
If compile-time errors count here's one (assuming a file named "crash.c").
#include "crash.c"

int main(){ return 0; }

It fills the screen with this upon compilation (have Ctrl-C ready)
                 from crash.c:1,
                 from crash.c:1:
crash.c:3:1: error: redefinition of ‘main’
crash.c:3:1: note: previous definition of ‘main’ was here
In file included from crash.c:1:0,
                 from crash.c:1,
                 from crash.c:1,

Another snippet which compiles perfectly well (no warnings under -Wall and illustrates the beautiful type safety of C </s>
#include <stdio.h>
int i;

int main(){
  sprintf(NULL, "%s", (char *) (void *) (1/i));
  return 0;
}

Running it gives:
Floating point exception (core dumped)

This is very old, but for those who remember BCPL,
GET "LIBHDR"

LET START() = VALOF
$8
        RESULTIS 0
$)

would complain
$8
 ^
"( ) or 8 expected"

R
This is technically not an error but a warning but nevertheless it's ridiculous, and occurs for completely esoteric reasons.
[[EDIT]] It seems that the cause of some parts of the funny warnings resides in RStudio rather than R per se, so it's less interesting than I first thought. The first example i.e plot(1:2, NotAGraphicalParameter = "ignore.me") is, however, still reproducible in "naked" R and is funny enough on its own right.[[/EDIT]]
> plot(1:2, NotAGraphicalParameter = "ignore.me")
# produces a nice scatterplot with two points, [1,1] and [2,2]
Warning messages:
1: In plot.window(...) :
  "NotAGraphicalParameter" is not a graphical parameter
2: In plot.xy(xy, type, ...) :
  "NotAGraphicalParameter" is not a graphical parameter
3: In axis(side = side, at = at, labels = labels, ...) :
  "NotAGraphicalParameter" is not a graphical parameter
4: In axis(side = side, at = at, labels = labels, ...) :
  "NotAGraphicalParameter" is not a graphical parameter
5: In box(...) : "NotAGraphicalParameter" is not a graphical parameter
6: In title(...) : "NotAGraphicalParameter" is not a graphical parameter
> plot(2:3)
# another nice scatterplot: [2,2] and [3,3]
# but there should be nothing wrong this time!
# however ...
There were 12 warnings (use warnings() to see them)
> warnings()
Warning messages:
1: "NotAGraphicalParameter" is not a graphical parameter
2: "NotAGraphicalParameter" is not a graphical parameter
3: "NotAGraphicalParameter" is not a graphical parameter
4: "NotAGraphicalParameter" is not a graphical parameter
5: "NotAGraphicalParameter" is not a graphical parameter
6: "NotAGraphicalParameter" is not a graphical parameter
7: "NotAGraphicalParameter" is not a graphical parameter
8: "NotAGraphicalParameter" is not a graphical parameter
9: "NotAGraphicalParameter" is not a graphical parameter
10: "NotAGraphicalParameter" is not a graphical parameter
11: "NotAGraphicalParameter" is not a graphical parameter
12: "NotAGraphicalParameter" is not a graphical parameter
# but let's try once more:
> plot(2:3)
# yup. no warnings this time. we had to do it twice

It's like R remembers our insults. But not for long.
I can't really explain why this happens - but it is reproducible. Actually it occurs every time when you supply some "not a graphical parameter" to plot 1, and then do a plot 2 in a completely impeccable way. It is especially funny that we get 12 "not a graphical parameter" warnings for the second plot but only 6 for the first one. Another funny thing is that if you supply "not a graphical parameter" with a value NULL then no condition is thrown:
plot(1:2, Nonsense=NULL)
# no warnings
# however
plot(1:2, Nonsense="gibberish")
# gives the usual 6-pack of warnings

And to get even more ridiculous, let's draw some lines on top of the previously drawn plot:
plot(1:2)
# you will see the number of warnings growing with each line:
lines(1:2, 1:2, mumbo = 1)
lines(1:2, 1:2, jumbo = 2)
lines(1:2, 1:2, bimbo = 3)
lines(1:2, 1:2, cucaracha = 4)
lines(1:2, 1:2, karaoke = 5)
lines(1:2, 1:2, radiogaga = 6)
lines(1:2, 1:2, reptiles = 7)
lines(1:2, 1:2, cowsonmoon = 8)
lines(1:2, 1:2, stainlessSteelLadderToTheMoon = 9)
lines(1:2, 1:2, frambuesa = 10)
lines(1:2, 1:2, fresa = 11)
lines(1:2, 1:2, limonYNada = 12)
lines(1:2, 1:2, slingsAndArrows = 13)
# ... and now you have 25 warnings:
warnings()

Warning messages:
1: "mumbo" is not a graphical parameter
2: "jumbo" is not a graphical parameter
3: "bimbo" is not a graphical parameter
4: "cucaracha" is not a graphical parameter
5: "karaoke" is not a graphical parameter
6: "radiogaga" is not a graphical parameter
7: "reptiles" is not a graphical parameter
8: "cowsonmoon" is not a graphical parameter
9: "stainlessSteelLadderToTheMoon" is not a graphical parameter
10: "frambuesa" is not a graphical parameter
11: "fresa" is not a graphical parameter
12: "limonYNada" is not a graphical parameter
13: "mumbo" is not a graphical parameter
14: "jumbo" is not a graphical parameter
15: "bimbo" is not a graphical parameter
16: "cucaracha" is not a graphical parameter
17: "karaoke" is not a graphical parameter
18: "radiogaga" is not a graphical parameter
19: "reptiles" is not a graphical parameter
20: "cowsonmoon" is not a graphical parameter
21: "stainlessSteelLadderToTheMoon" is not a graphical parameter
22: "frambuesa" is not a graphical parameter
23: "fresa" is not a graphical parameter
24: "limonYNada" is not a graphical parameter
25: In plot.xy(xy.coords(x, y), type = type, ...) :
  "slingsAndArrows" is not a graphical parameter

This should not win big time unless there is no justice.

What version of R are you using? Because i can't reproduce the pack of warnings you're getting with plot(2:3) right after using plot(1:2, NotAGraphicalParameter = "ignore.me"). DId you redefine something in your .Rprofile?

looks like this is specific to running R in Rstudio (both on Windows and Ubuntu) but doesn't occur when you run R in linux terminal or windows Rgui.

I think I have seen something similar with modelling functions (lm or glm) without Rstudio but can't reproduce it now. (That is, earlier warnings were coming up when not relevant any more.)

Windows Command Script
WARNING, this is a fork bomb!
This will output garbage questions about quitting if you try to quit the console in any way.
%0|%0|%0

Bonuses:

Will make the system pretty much unusable until restart
Prevents quitting the script, which should be impossible

Danger Will Robinson?

How about compiler optimisation errors:
#include <stdio.h>

#define N 4

int main(void)
{
    int sum;
    int i;
    int arr[N];

    for (i = 0, sum = 0; i < N; i++, arr[i] = sum) {
        sum += arr[i];
    }
    printf("%d\n", sum);
    return 0;
}

This is specific to gcc >= 4.7.
Compiles and runs fine with gcc -O0 -Wall.
Compiles with gcc -O2 -Wall but results in an inf-loop.
Also note, how gcc does see the problem for smaller N, e.g. N = 3:
test.c:11:38: warning: array subscript is above array bounds [-Warray-bounds]
  for (i = 0, sum = 0; i < N; i++, arr[i] = sum) {
                                       ^
test.c:12:13: warning: 'arr[0]' is used uninitialized in this function [-Wuninitialized]
  sum += arr[i];
         ^

Btw, this has been taken from a bug report, I can't recall the bug number though.

Well, this is undefined behavior, so the compiler is allowed to do anything. But it still feels strange that the compiler decided to change an assignment outside of the local array that is never used, and use of undeclared value to an infinite loop, even if the C standard allows this (after all, it depends on undefined behavior - accessing arr[N] (outside of array), and accessing arr[0] (which is uninitialized)). As anything is allowed for undefined behavior, this is not optimization error, but very unlikely to be what user wanted.

This is explicitly not a compiler optimization error. UB is UB, and the compiler would be right even if it decided to eradicate all your data from your hard drive.

q insults you
q)`u#1 1
'u-fail
q)

```u#`` tells q that every element in a list is unique (so it can build some sort of hash-based index, presumably). this is what happens when it's not actually true.

What is the language? I tried searching for "q insults you" language, but I couldn't have found anything.

Sorry for being unintentionally cryptic, the language is [q](http://en.m.wikipedia.org/wiki/Q_(programming_language_from_Kx_Systems). It also works in k4, BTW.

I've always liked this weirdness in APL:

      ⍝ obviously a syntax error
      { (] } 3
SYNTAX ERROR
      {(]}3

      ⍝ but:
      { (] } 1÷0
DOMAIN ERROR
      {(]}1÷0

      ⍝ it even works with statically defined functions
      ∇z←f x
[1]  z←[{]}x
[2]  ∇
      f 1÷0
DOMAIN ERROR
      f 1÷0
     ∧
      f 3
SYNTAX ERROR
f[1] z←[{]}x

It parses the inside of functions lazily!

Python
Nested blocks
for a in range(26):
 for b in range(26):
  for c in range(26):
   for d in range(26):
    for e in range(26):
     for f in range(26):
      for g in range(26):
       for h in range(26):
        for i in range(26):
         for j in range(26):
          for k in range(26):
           for l in range(26):
            for m in range(26):
             for n in range(26):
              for o in range(26):
               for p in range(26):
                for q in range(26):
                 for r in range(26):
                  for s in range(26):
                   for t in range(26):
                    for u in range(26):
                     for v in range(26):
                      for w in range(26):
                       for x in range(26):
                        for y in range(26):
                         for z in range(26):
                          print a

Python 2.7: SystemError: too many statically nested blocks
Self-referencing lists
def printList(myList):
    for element in myList:
        if isinstance(element, list):
            printList(myList)
        else:
            print(element)

a = []
a.append(a)
printList(a)

Python 2.7
True is not a constant
The problem in the following example is that in Python 2.7, True and False are not constants. And True and False can automatically get casted to 1 and 0:
True=False
a=10/True

Traceback (most recent call last):
  File "/home/moose/.config/pluma/tools/new-tool-2", line 11, in <module>
    exec(sys.stdin.read())
  File "<string>", line 2, in <module>
ZeroDivisionError: integer division or modulo by zero

Python 2.7:
Intendation
def f(n):
    if n <= 1:
        return n
    else:
        return f(n-1)+f(n-2)

Do you get the error?
Traceback (most recent call last):
  File "/home/moose/.config/pluma/tools/new-tool-2", line 11, in <module>
    exec(sys.stdin.read())
  File "<string>", line 4
    else:
       ^
SyntaxError: invalid syntax

Mixing tabs and spaces was ok in Python 2.7 ... but mind the indentation level!

The mixing spaces and tabulators example doesn't work correctly, as Stack Exchange platform doesn't allow tabulators in code.

@xfix: Ok, but I think people who read this get the point. Most editors don't show space / tabs either (except for trailing whitespace) and if they show it, it's most of the time gray. And in every other language (except for whitespace) whitespaces don't matter, as long as at least one is there.

You should write your programs in the Whitespace programming language.

PHP
<?php
[][] = 42;

[] is used in order to push elements. However, if you use it for array literal, the PHP makes crazy error message, even if you assign to it in order to push. Requires PHP >= 5.4, as before that you couldn't have indexed array literals.
Output:

Fatal error:  Cannot use [] for reading in [...][...] on line 2

I'll start:
#include <iostream>

using namespace std;

class A
{
public:
    A()
    {
    }

    void doSomethingDiabolical()
    {
        delete this;
    }

    virtual void breakHorribly()
    {
        cout << "still alive" << endl;
        doSomethingDiabolical();
        cout << "still alive" << endl;
    }
};

class B : public A
{
public:
    B() : A()
    {
    }

    void breakHorribly()
    {
        cout << "still alive" << endl;
        ((A *) this)->breakHorribly();
        cout << "still alive" << endl;
        doSomethingDiabolical();
        cout << "still alive" << endl;
        breakHorribly();
        cout << "dead" << endl;
    }
};

int main()
{
    jane();
}

void jane()
{
    cout << "still alive" << endl;
    A * o = new B;
    cout << "still alive" << endl;
    o->breakHorribly();
}

Any guesses why this program crashes? :D
See jane run: http://ideone.com/gtaZ3

Isn't this a rather straightforward infinite recursion? B::BreakHorribly calls itself before doSomethingDiabolical is called, so delete this is never reached.

This program explodes for a large number of reasons.  Its behavior changes if you remove different print statements.  However, you're right.  I didn't have the time to reproduce the undefined behavior I had once, but I ended up getting a pure virtual function call at runtime.

You're not saying you once accidentally typed something like delete this, are you?

No, it was much more subtle than that, but the end result was the same: a destructor was called for a class during execution of a member function

CPython
import ctypes
import sys
(ctypes.c_char * sys.getsizeof(None)).from_address(id(None))[:4] = '\x00' * 4

The result:
Fatal Python error: deallocating None

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

Even better in Python 3: ctypes.pythonapi._Py_Dealloc(ctypes.py_object(None)).

Bash
I got this today when I tried to find out whether it is possible to protect the system from rm -rf /.
mkdir /tmp/a
mkdir /tmp/a/b
sudo mount --bind /tmp/a /tmp/a/b
rm -rf /tmp/a

The error message with LANG=C:
rm: WARNING: Circular directory structure.
This almost certainly means that you have a corrupted file system.
NOTIFY YOUR SYSTEM MANAGER.
The following directory is part of the cycle:
  '/tmp/a/b'

This warning is coming from rm, not bash. Not sure what language you should declare in the title, given that you used bash to set it up.

TeX
This simple TeX program:
\def~{x~}~

gives the following error in the log file:
! TeX capacity exceeded, sorry [main memory size=5000000].
l.1 \def~{x~}~

If you really absolutely need more capacity,
you can ask a wizard to enlarge me.

You better know which wizard it the right wizard :-)

TeX: second error message
This is a small LaTeX table with 260 columns, for which we want a cell that spans all the columns.
\documentclass{article}
\begin{document}
\begin{tabular}{*{260}{l}}
\multicolumn{260}{c}{Table Title}
\end{tabular}
\end{document}

The error message is also hilarious:
! This can't happen (256 spans).
<template> \endtemplate

l.5     \end{tabular}

I'm broken. Please show this to someone who can fix can fix

How many programs are humble enough to admit they are broken?

Bash - counterintuitive escape failure
echo "this should definitely work!!!11!"

returns
-bash: !11: event not found

(history expansion on the commandline is not prevented by double quotes)
Bonus:
echo "I don't know what's gone wrong!! !echo is usually pretty foolproof!-1"

The output is unlikely to be what's expected.  Press up to get the command again, and notice it's changed from what you typed.  If you press up and enter a couple of times, it's likely your output will begin to look somewhat horrific.  Try it for yourself.

This answer is a duplicate of http://codegolf.stackexchange.com/a/17776.

C# - Recursive, lazy Fibonacci generator
static void Main()
{
    Console.WriteLine(string.Join(",", fib().Take(141)));
    Console.ReadLine();
}

static IEnumerable<decimal> fib(decimal n = 0, decimal m = 1)
{
    if (n == 0)
    {
        yield return 0;
        yield return 1;
    }
    while (true)
    {
        yield return n + m;
        foreach(var x in fib(m, n+m))
        {
            yield return x;
        }
    }
}

This code looks fine, right? A fairly simple Fibonacci generator, spiced up with some recursion and lazy enumeration. Should work.
Nope! Running this will cause an OverflowException. This is because we are using decimal, and the 141st Fibonacci number (~8.1E28) exceeds the maximum value of decimal (~7.9E28).
The int, however does not throw an OverflowException when you exceed its maximum value. Instead it, as expected, overflows to a negative value. So if we replace int instead with decimal, like in the following code, it should work, right?
static void Main()
{
    Console.WriteLine(string.Join(",", fib().Take(141)));
    Console.ReadLine();
}

static IEnumerable<int> fib(int n = 0, int m = 1)
{
    if (n == 0)
    {
        yield return 0;
        yield return 1;
    }
    while (true)
    {
        yield return n + m;
        foreach(var x in fib(m, n+m).ToList())
        {
            yield return x;
        }
    }
}

If you read the code it should be obvious why this won't work. If you didn't... I didn't just change the type from decimal to int; I also snuck in a call to ToList() in the foreach statement. This will force the enumerator returned to be eagerly evaluated. This will cause not 141 recursions, but instead an infinite number of recursions. Actually, long before it hits infinity it will of course overflow the stack, causing the runtime to throw a StackOverflowException. (bonus: this exception cannot be caught, so it will crash the runtime)

R
Another one which is not ridiculous and, again, a warning rather than an error, but still nice:
> sapply(as.list(-1:-51), log)
 [1] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
[20] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
[39] NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN NaN
There were 50 or more warnings (use warnings() to see the first 50)

I like the last bit: 50 or more :)
And the actual warnings:
1: In lapply(X = X, FUN = FUN, ...) : NaNs produced
2: In lapply(X = X, FUN = FUN, ...) : NaNs produced
....
50: In lapply(X = X, FUN = FUN, ...) : NaNs produced

FUN = FUN!

Nyan Code?! Well, that is weird indeed!

I don't see what's unexpected or surprising. log of a negative produce Not A Number (NaN) as it should.

Not to compete but Burlesque is pretty easy to crash :D.
blsq ) rs
blsq: Burlesque/Eval.hs:(2900,3)-(2904,33): Non-exhaustive patterns in case

and there are literally dozens of these crashes still hanging around. It's just that nobody ever reports them so they won't be fixed anytime soon.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Convert from binary to unary in 7x7 Manufactoria
In the game manufactoria, take in a binary number and output that number of red pieces.
The catch? The board-size is only 7x7:
Here's the manufactoria code for the problem:
http://pleasingfungus.com/Manufactoria/?ctm=Razors;Treat_the_input_as_a_binary_number_and_output_that_number_of_reds;b:r|brr:rrrr|brb:rrrrr|brbb:rrrrrrrrrrr|:|brrrr:rrrrrrrrrrrrrrrr|brbr:rrrrrrrrrr;7;3;0;
I have a solution, so it most definitely exists.
EDIT: Least "total parts" wins (as reported by manufactoria engine)

How do you win the competition?

Lets say least pieces.  I really just want to see if people come up with different solutions than I did

21 20 19 parts! Ha!

http://pleasingfungus.com/Manufactoria/?lvl=32&code=q12:9f0;c12:8f3;g9:8f1;q9:9f4;b10:8f3;p10:9f0;r10:10f1;y11:9f0;g12:5f3;c12:6f3;r9:6f3;c9:7f2;r10:6f0;p10:7f2;q11:7f1;i12:7f7;p13:7f6;r13:6f0;c13:8f0;&ctm=Razors;Treat_the_input_as_a_binary_number_and_output_that_number_of_reds;b:r|brr:rrrr|brb:rrrrr|brbb:rrrrrrrrrrr|:|brrrr:rrrrrrrrrrrrrrrr|brbr:rrrrrrrrrr;7;3;0;
Edit 2: Back to the original design, but with two parts shaved off by creative reuse of conveyors.  The 7 × 7 board really does start to feel confining — I've come up with several ways to shrink this further, if I only had one more row of vertical space...

Way to steal the win over a year after the question was asked.

30 26 24 22 Parts

Here is my entry, with 22 parts and a time of 4:16. This can be rearranged slightly to fit into a 5 wide by 7 tall space.
It works by dividing the tape into three sections: the instructions (blue and red), the data (green), and a data terminator symbol (yellow). Each cycle of operation, it reads and replaces the first instruction. It then cycles the rest on the instructions to the back of the tape until it reaches the data. For each data symbol read, it adds two of them to the back of the tape. Once the data terminator is read, the instructions are once again at the front of the tape. It deletes the first instruction (which was just executed). It then adds one more data symbol to the end of the tape if the current instruction (read earlier) is blue. The yellow symbol is then re-appended. Once there are no more instructions, then all of the green symbols are converted to red and are output.
Example: input is BBR (110 or 6)
These are the important steps in execution, in more detail than before
BBR
BBRY     #yellow is appended
YBBR     #the instructions are cycled through, execution is on the left half
YBBR     #all of the greens (none yet) are duplicated
BRG      #Y and B are removed and a G appended
BRGY     #yellow is appended
GYBR     #instructions are cycled, execution is on left half
YBRGG    #Gs are duplicated
RGGG     #Y,B removed; G added
RGGGY    #Y added
GGGYR    #instructions are cycled, execution is on RIGHT half
YRGGGGGG #Gs duplicated
GGGGGG   #YR removed, G NOT added
GGGGGGY  #Y added
YRRRRRR  #Greens are changed to red
RRRRRR   #output

You appear to have me beaten by one.  I'm amazed at how few movers you used and it's planar.

I just shrunk it by two more parts. It's still planar and uses even fewer movers.

Once again, shrunk by two parts, still planar, with even fewer movers. I've done a good job of compressing.

I managed 27 parts, but it would fit on a 5x7 grid:

I'm using the double-and-add method.  Start by putting a green to mark the start of the number and then a green or a yellow to determine whether the next digit pulled off is a zero or a one.
Skip past the rest of the number and then double the number of reds currently in place.  Finally add one more if the next piece is yellow. Repeat until the number goes to zero.

17 13 parts
I took some liberty with the specification.  I'm going to define the input binary number to appear in little-endian order.  You never say explicitly whether the input is little or big endian, but it appears you assume big endian because your tests assume that.  I'm going to use these little-endian tests instead.
http://pleasingfungus.com/Manufactoria/?ctm=RazorsLE;Treat_the_input_as_a_little_endian_binary_number_and_output_that_num_of_red;b:r|rrb:rrrr|brb:rrrrr|bbrb:rrrrrrrrrrr|:|rrrrb:rrrrrrrrrrrrrrrr|rbrb:rrrrrrrrrr;7;3;0;

The code works by decrementing the binary number by 1 each loop and adding one yellow mark.  At the end, it replaces the yellow with red and deletes the binary number (all blue at this point, representing -1).

No, in Manufactoria all binary numbers are bigendian.  It should pass the tests

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/


text:
Find the first n digits of the square root of a number
Given two integers m and n, return the first m digits of sqrt(n), with the decimal point. They will be given with a space in between.
You only have to produce m digits: so if m=5, n=500, then the output will be 22.360, not 22.36067.
Do not use anything that will increase the precision of any operation.
Test Cases:
20 99 -> 9.9498743710661995473
15 12345678 -> 3513.64170057221
16 256 -> 16.00000000000000
2 10000 -> 10
Shortest code wins.

Looks like your second test case gives the square root of 12345678 not 1234567 (which is 1111.11070555548 according to my J program).

When you say 'do not use anything that will increase the precision of floating points.' does that disqualify arbitrary precision languages (such as bc)

@Gareth: Yeah, it's probably 12345678, I probably copied it from WA wrong.

@Matt: No, as long as you don't use any command that explicitly sets the precision.

@beary605 If I can't change the precision of my square root operator (set at 6 figures by default in J) how am I supposed to complete the task? If you want us to calculate the square root without using a square root function shouldn't you just ask us to do that?

@Gareth: It doesn't cover all of the points. You could use Newton's Method with x^2 as the input, but the precision would be finite if you did it the obvious way.

What should 2 10000 output? 100?

@Inkbug: 10. I will add that to the test examples

Python, 143 chars
m,n=map(int,raw_input().split())
d=10**m
n*=d*d
a=0
b=n
while a<b-1:c=(a+b)/2;a,b=[[c,b],[a,c]][c*c>n]
print('%d.%0*d'%(a/d,m,a%d))[:m+(a/d<d)]

Computes the answer by multiplying n by 10^2m, doing an integer square root (using binary search), then "dividing" the result by 10^m.

This doesn't work for large perfect squares that request small numbers of digits. ex: m=2 n=1000000 will print 100 instead of 10

@Matt: fixed...

Mathematica 66 272 240 chars
New approach
This uses the same, reasonably efficient (59 chars), method for obtaining the smallest useful convergent of Sqrt[n]. It takes a slightly different approach for dividing the numerator by the denominator, accurate to m places.
t = ToString; q = QuotientRemainder;
w = FixedPoint[(# + n/# )/2 &, 1, SameTest -> (Abs[#1 - #2] < 10^(-m) &)];
r = q[Numerator@w, k = Denominator@w];
h[{c_, d_, e_}] := {Append[c, q[d, e][[1]]], 10 q[d, k][[2]], k};
t@r[[1]] <> "." <> t@FromDigits@Nest[h, {{}, 10 r[[2]], k}, m][[1]]

Example: Find the Square root of 5 accurate to 18 places
n=5; m=18;
<run the above code>

(* out *)
"2.236067977499789696"

By the way, the convergent, w, for the above case is given below.
This is still long-winded but it works.

Old approach
The following 59 chars suffice to produce a fraction that will, in decimal form, solve the problem, assuming m, n are entered programmatically:
FixedPoint[(# + n/# )/2 &, 1, SameTest -> (Abs[#1 - #2] < 10^(-m) &)]

When m=18, n=5, here's the fraction:
(* out *)
562882766124611619513723647/251728825683549488150424261

The trick is to convert this fraction into a decimal.
The easy way is to use N;
N[%, m+1]
(* out *)
2.236067977499789696

However, N violates the rules by specifying the precision to work with.

Back to the drawing board:
q = FixedPoint[(# + n/# )/2 &, 1, SameTest -> (Abs[#1 - #2] < 10^(-m) &)];
f[{a_, n_, d_}] :=
   With[{q = QuotientRemainder[n, d]}, {Append[a, q[[1]]], q[[2]], d/10}]
   StringInsert[IntegerString@FromDigits@#[[1]],  ".", -1/Log[Denominator@#[[3]], 10]]
   &[NestWhile[f, {{}, Numerator@q, Denominator@q}, Length@#[[1]] < m &]]

Unfortunately, it takes another 205 characters (by my reckoning) to generate a decimal expression from the fraction.  Surely there must be a more direct way to divide one integer by another to m decimal places!

Haskell 126
main=interact$(\[x,y]->(\s->if '.'`elem`s then(x+1)`take`s else x`take`s)$(show.sqrt.fromIntegral)y++cycle"0").map read.words

Darn sqrt not taking Ints, and fromIntegral being so long!

C# 41 chars
Math.Sqrt(n).ToString().Substring(0,m+1);

Version-1
C# 364 Characters (Short Version)
using System;namespace X{class T{static void Main(string[] a){int m=int.Parse(Console.ReadLine()),n=int.Parse(Console.ReadLine());Console.WriteLine("{2}",f(n,m));}static string f(long s,int l){decimal x=s;for(int i=0;i<20;x=(((x*x)+s)/(2*x)),i++);var b=x.ToString(string.Format("F{0}",l));return(x.ToString().Contains("."))?b.Substring(0,l+1):b.Substring(0,l);}}}

code can be ran from OneIDE - http://ideone.com/9tZsD.
C# Normal  Version
using System;

namespace X
{
    class T
    {
        static void Main(string[] a)
        {
            int m = int.Parse( Console.ReadLine()), n = int.Parse( Console.ReadLine());
            Console.WriteLine("m:{0}, n:{1} -> {2}", m, n, f(n,m));
        }
        static string f(long s,int l)
        {
            decimal x = s;
            for(int i = 0; i < 20; x = (((x * x) + s) / (2 * x)), i++) ;
            var b=x.ToString(string.Format("F{0}", l));
            return(x.ToString().Contains("."))?b.Substring(0,l+1):b.Substring(0,l);
        }
    }
}

It doesn't work for all the test cases: test case #4 (2, 10000) should output 10, not 100.00. As well, #1 and #2's outputs are cut off at 13 digit precision.

tx @beary605 for pointing out issues around #4, updated code with new oneide link

Pascal, 142 bytes
This full program requires a processor supporting features of “Extended Pascal” (ISO standard 10206).
The program will crash if m is negative.
program p(input,output);var n,m:integer;p:string(maxInt);begin read(m,n);writeStr(p,sqrt(abs(n)):1:m);write(p:m+ord(index(p,'.')in[1..m]))end.

Ungolfed:
program findFirstNDigitsOfSquareRootOfANumber(input, output);
    var
        number, digit: integer;
        print: string(maxInt);
    begin
        readLn(digit, number);

        { `Sqrt` only works on non-negative integers and always returns
          the principal root as a `real` value. The `writeStr` routine is
          defined by Extended Pascal. The `:1` specifies the minimum width
          of the given argument. The write routines in combination with a
          `real` argument accept a second format specifier (here `:digit`)
          that disables scientific notation and determines the number of
          post-decimal (i.e. fractional) digits. }
        writeStr(print, sqrt(abs(number)):1:digit);

        { The format specifier `:digit…` in combination with a `string`
          argument specifies the _exact_ width. We will need to take
          account of the radix mark (`'.'`) _if_ it is printed, though. }
        writeLn(print:digit + ord(index(print, '.') in [1..digit]));
    end.

It is not possible to request maxInt digits since one char value will be occupied by the radix mark (.).
You will probably need to replace maxInt by a sufficiently small natural number, though.

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Finding variables in code
Given some code in your language as a string, find and display all the variable names.
Examples in pseudocode:
a=2
b=3
for(i, 0->9) do b=b-10
if a=b then write "a equals b"

Returns: a b i
abcdefgh=20000000000000
bcdifhgs="hello"
if abcdefgh=bcdifhgs then da44="hax"
if abcdefgh*2=da44 then write da44

Returns: abcdefgh bcdifhgs da44
2=3
3=5
5=7
if 2=7 then exit

Returns:
a=2
while True do b=3

Returns: a b
Shortest code wins.
For stack-based languages, display the highest height of the stack.
For memory cell based languages, display all the memory cells that have been changed.

How is the code given, as a string input to our program, or are we to append our code to the 'input' program?

I was soo excited to answer with an empty brainfuck program until I read the last line.

Someone should solve this without using regular expressions :)

Could you please explain the last two lines in your question or show an example?

@MikeDtrick: Stack-based: push 2 items pull 1 item push 2 items pull 3 items will return 3. Memory-cell: think Brainfuck, and all cell values which have been changed by + or -.

More interesting, in case of while false { b = 3 } should it return b? Please clarify.

@ArtemIce: Yes.

Python 3, 73 66 86
Now follows the updated test cases:
import sys
print(*set(compile(sys.argv[1],'','exec').co_names)-set(dir(__builtins__)))

Note that this also prints the names of non-builtin objects and methods / attributes of objects (e.g. if you use sys.argv in the input code it'll print sys and argv). Still, it does technically fit the test cases.
Assuming we're allowed to simply run the code, it can be done in 66 characters. Note that this fails the while True test case and, unlike the above solution, does not print things like sys and argv:
import sys
print(*(lambda:(exec(sys.argv[1]),set(locals())))()[1])

Only problem is, you have to actually run the code to get the variables.

I have put in another test case, please modify your answer to fit it.

Alright, I've changed my answer.

Very interesting... I've never heard of a code object or the compile built-in before.

This is really the only answer which runs correctly for the last test case, so answer to you!

Haskell, 2
[]

Only if you take the word "variable" literally.

For all those not knowing Haskell: It actually doesn't have any variables; anything is constant.

Python, 111
I am pretty new to code golf.. tips are appreciated, but here is an alternative approach
import ast as a
s=set()
v=a.NodeVisitor
v.visit_Name=lambda t,n:s.add(n.id)
v().visit(a.parse(input()))
print s

Ruby
Kind of cheating, I guess... If code contains Ruby code, then:
pre = global_variables
eval code
(global_variables - pre + local_variables + self.instance_variables - [:code, :pre]).each do |x|
  puts x.to_s
end

Example:
code = "a = 3; @b = 5; $c = 6, @@d = 10"
Output:
$c
@b

Works only with global and instance vars so far.
zsh
set > /tmp/set.1
eval $code
set > /tmp/set.2
diff -a /tmp/set.1 /tmp/set.2 | grep -vE "HISTCMD|LINENO|RANDOM|SECONDS|pipestatus" | grep -E ">[^=]+"

Example:
$code = 'zzz=3; xxx="hello"'
Output
> xxx=hello
> zzz=3

Clojure, 53
(pr(map #(last %)(re-seq #"\( *def +([a-z-])+"code))

Example:
user=> (def code "(def a 1) (     def    b     ( +  3 5 )))")
#'user/code
user=> (pr(map #(last %)(re-seq #"\( *def +([a-z-]+)"code)))
("a" "b")nil
user=>

I have put in another test case, please modify your answer to fit it.

Python 104
import sys,re,keyword
print(set(re.findall(r"\b\w+\b",sys.argv[1]))-set(keyword.kwlist+dir(__builtins__)))

This also prints integers and words inside of strings...

@Fraxtil: Yes, I realized this the other day :/ Still trying to think of a way to handle string literals without adding to much to the character count.

HQ9+ (or H9+), 0
Is cheating allowed? In this case, the solution is a program of zero length, because the language has no variables, and has no memory cells, stack or any other form of storage. So it outputs nothing.
First I wanted to write Brainf*ck, but then I realized the "memory cell" rule.

Actually, you have a memory cell. (Remember that nice operator called + [increment the counter]? It's pretty pointless since you can't read out the counter at all, but the counter is definitly a variable. )

I always assumed it is the program counter. If you require to also print the PC, it would invalidate all other answers, because none of them print it :)

This is code golf. Cheating is encouraged.

MATLAB, 12
eval('<PROGRAM STRING HERE>');who

I have put in another test case, please modify your answer to fit it.

@beary605 no need to change anything :)

Even better for you. ;D

I'm fairly certain, although can't test it, that if the  is a piece of code that never terminates that your program will never print the variables.


text:
Breaking Perfect Hangman in reverse, in reverse
this is the follow-up question to Perfect Hangman in reverse
golfers are now asked to develop a program that uses all rules in Perfect Hangman in reverse, instead, playing the player.
the program shall ask how many letters you want the word to be, a single required letter, then pick what word is LEAST LIKELY to be guessed by the Perfect Hangman in reverse program.
Example:

you state 6 letters, and the letter M, the program knows that its counterpart will guess E first, so it rules out any words with E, it knows the next letter is G, so it also rules out all words with G, the 3rd letter is A, however no words remain without an A, E, and G, and also contains M, so it assumes that its counterpart will get the A correct, and starts analyzing the next step to determine the best way to fool the program.

Example may not be exactly correct, if anybody wants to edit the example with a real-world result, go for it.
bonus example:

program sees letter E is most common, however by taking the word enigma, it realizes that the program is LEAST likely to guess the total word.

tiebreaks:

all tiebreaks in code should assume that the result that expands all lives, with the most remaining undiscovered letters, is the best. if the tie is still unbroken, you should select the alphabetical first.

A winning program will be scored based on the following criteria.

length - 1 point per byte
smarts - if your program can accept a letter, when it is only acceptable because a LATER step becomes harder than if it didn't accept, award yourself -300 points
incorrect - to stop cheating and 0 length, if your program doesn't solve the problem, award yourself 10 million points, and refrain from posting.

Contest ends 8/17/2012, noon CST.

You can use bolded tags to show headers, and bullet points (which I forget how to do).

I'm voting to close this question as off-topic because the contest finished in 2012.


text:
Output a number in PrettyFont
I've designed a new font which I call PrettyFont. I've put much much time into perfecting it, but since I'm a working man I don't have time to finish it. Therefore it only contains 4 characters right now. One day when I've become rich it will become my life-long goal to finish it, but for now...
This is PrettyFont: (0, 1, 2, 3)
####  ##  #### ####
#  #   #  #  #    #
#  #   #    #   ###
#  #   #   #      #
####  ### #### ####

Each character is 4 pixels wide and 5 pixels high. Now! I want you to write me a program that outputs a number in PrettyFont so I can start sending designs to print.
Rules:
The input is a string number in base 4 (only characters 0-3), for example "01321". The program should be able to handle at least 10 characters in the string. BONUS points is given to the program that takes an actual base 10 integer instead of a string. EDIT clarification: the integer bonus means that one can enter any base 10 number, like 54321, and the program will convert it to base 4 and output it (in this case 31100301).
The output will be the number printed with PrettyFont. Example input and output:
> "321"
####
   #
 ###
   #
####

####
#  #
  #
 #
####

 ##
  #
  #
  #
 ###

Huge bonus to the program that can output it in a single row-fashion like this:
> "321"
#### ####  ##
   # #  #   #
 ###   #    #
   #  #     #
#### ####  ###

The '#' character is not a requirement, and can be replaced by any character.
In vertical output, an empty row is required between each PrettyFont character. If anyone makes the horizontal output, one white space character ' ' or a tab character is required between each PrettyFont character.
This is code golf, shortest code wins! (I need it short because my office computer has limited storage.)

It's not exactly a duplicate, but the only fundamental difference between this and http://codegolf.stackexchange.com/questions/3628/flag-semaphore-encoder is the lookup table.

PrettierFont - banner -c '#' 0123

with 4 pixels wide you're gonna have issues with 'M'

How many chars is bonus for taking 10 base number as input?

I'm not really sure. I need to see some more solutions to get an idea of how hard it would be to do it. I'm not very good at code golf myself so... Suggestions appreciated!

k (118 117 72 71 69 66 chars)
I haven't made much of an effort to golf this yet but it achieves the desired horizontal output in not too many chars:
-1'" "/:'+(5 4#/:4 20#"# "@,/0b\:'0x066609ddd806db00e8e0)"I"$'0:0;

Takes input from stdin, prints output to stdout.
edit: By implementing a form of compression on the output "bitmap", I've reduced it to 72. The bitmap is now built by converting  64bit ints to binary and mapping the 0s and 1s to "#" or " ". I could do it from hex like a few of the other solutions but I think this would end up longer. Turns out hex is better.
Sample output for 012301:
####  ##  #### #### ####  ##
#  #   #  #  #    # #  #   #
#  #   #    #   ### #  #   #
#  #   #   #      # #  #   #
####  ### #### #### ####  ###

//edit: -6 char

Impressive. Shortest code yet! It might fit on my limited storage drive. Good job.

Down to 71. Given that the combined kdb+/q/k exe weighs in at a slim 392kB, this might be ideal for your limited storage drive ;)

Python3 (124)
s=input();[print(*["".join(" #"[0xf171ff429f72226f999f>>(20*int(x)+4*y+i)&1]for i in(3,2,1,0))for x in s])for y in range(5)]

Sorry, vertical was not interesting for me.
???/golf.py
1230012301203012030102301230
 ##  #### #### #### ####  ##  #### #### ####  ##  #### #### #### ####  ##  #### #### #### ####  ##  #### #### #### ####  ##  #### #### ####
  #  #  #    # #  # #  #   #  #  #    # #  #   #  #  # #  #    # #  #   #  #  # #  #    # #  #   #  #  # #  #    # #  #   #  #  #    # #  #
  #    #   ### #  # #  #   #    #   ### #  #   #    #  #  #  ### #  #   #    #  #  #  ### #  #   #  #  #   #   ### #  #   #    #   ### #  #
  #   #      # #  # #  #   #   #      # #  #   #   #   #  #    # #  #   #   #   #  #    # #  #   #  #  #  #      # #  #   #   #      # #  #
 ### #### #### #### ####  ### #### #### ####  ### #### #### #### ####  ### #### #### #### ####  ### #### #### #### ####  ### #### #### ####

Awesome one! Didn't expect so few characters for the horizontal one. Nice job.

Thx. I guess my idea (hex-number and shifts) should be even shorter in Ruby implementation.

J, 84 82 81 80 75 69 characters
' #'{~(,4,.(4*".,' ',.1!:1[1)+/i.4){"1#:63231 37521 37415 37441 63487

Takes input from the keyboard:
   ' #'{~(,4,.(4*".,' ',.1!:1[1)+/i.4){"1#:63231 37521 37415 37441 63487 63487
0123210
 ####  ##  #### #### ####  ##  ####
 #  #   #  #  #    # #  #   #  #  #
 #  #   #    #   ###   #    #  #  #
 #  #   #   #      #  #     #  #  #
 ####  ### #### #### ####  ### ####

Magic numbers FTW (or for the second place in this case) :-)

Very nice... very nice... I'm impressed! Many good answers today. Maybe my designer-prints will turn out fine.

You could encode all  digits into one binary number and do a reshape on the result to get the corresponding number matrices.

@FUZxxl I did try to find the number for the full 80 bits, but #: didn't seem to work for that size of number. #:1166416635908028473935870 and #:1166416635908028473931775 both give the same answer for me.

C - 164 151 characters horizontal
On IDEone: http://ideone.com/gljc3
The code (164 bytes):
i,j;main(){char n[99];gets(n);for(;j<5;++j){for(i=0;n[i];++i)printf("%.4s ","#####  # ##   #  ### #     #"+4*("01110233340135006460"[(n[i]-48)*5+j]-48));puts("");}}

EDIT - 151 bytes
I added the suggestions from the comments and then some. It isn't exactly safe (0-length array that I gets() in to...) though.
char i,j=5,n[];main(){for(gets(n);j--;)for(i=puts("");n[i];printf("%.4s ","#####  # ##   #  ### #     #"+4*(0x1A600BA136E0248>>15*n[i++]-720+3*j&7)));}

Note, i=puts("") is undefined behavior since I'm treating void as int! It consistently returns 0 on my version of MinGW, but it returns 1 on the compiler IDEOne uses.
Accepts decimal, outputs base 4 (167 bytes)
char i,j=5,n[];main(p){for(itoa(atoi(gets(n)),n,4);j--;)for(i=puts("");n[i];printf("%.4s ","#####  # ##   #  ### #     #"+4*(0x1A600BA136E0248>>15*n[i++]-720+3*j&7)));}

Ooh, a short one in C! That will surely run in under a minute on my old CPU. Good one.

Couldn't you save 3 chars by removing "!=0"?

Yea, thanks. I didn't catch that one.

Put gets within for (save 1). Move puts to the external for's increment and save braces. Save paranthesis: (n[i]-48)*5+j->n[i]*5-240+j, same trick with +4*(...

Okay down to 153 bytes. Not too bad for C I guess.

151 bytes. I don't think it's going to get any better with the permitted built in types and rudimentary math functions that C provides. I could get it down another 10 bytes if I could have 128 bit numbers though =/

Very nice with the decimal version also. Wish I could upvote this again!

Ruby, 0123 chars + a bonus ([0123] vs '#')
f=15
0.upto(4){|n|$*[0].chars{|x|$><<"%4s "%eval(:f6ff929192279241f7ff[x.to_i+4*n]).to_i.to_s(2).tr(?0,' ').tr(?1,x)}
puts}

Example:
% ruby ./font.rb 01231231
0000  11  2222 3333  11  2222 3333  11
0  0   1  2  2    3   1  2  2    3   1
0  0   1    2   333   1    2   333   1
0  0   1   2      3   1   2      3   1
0000  111 2222 3333  111 2222 3333  111
% ruby ./font.rb 01231231102020103201301203212302230
0000  11  2222 3333  11  2222 3333  11   11  0000 2222 0000 2222 0000  11  0000 3333 2222 0000  11  3333 0000  11  2222 0000 3333 2222  11  2222 3333 0000 2222 2222 3333 0000
0  0   1  2  2    3   1  2  2    3   1    1  0  0 2  2 0  0 2  2 0  0   1  0  0    3 2  2 0  0   1     3 0  0   1  2  2 0  0    3 2  2   1  2  2    3 0  0 2  2 2  2    3 0  0
0  0   1    2   333   1    2   333   1    1  0  0   2  0  0   2  0  0   1  0  0  333   2  0  0   1   333 0  0   1    2  0  0  333   2    1    2   333 0  0   2    2   333 0  0
0  0   1   2      3   1   2      3   1    1  0  0  2   0  0  2   0  0   1  0  0    3  2   0  0   1     3 0  0   1   2   0  0    3  2     1   2      3 0  0  2    2      3 0  0
0000  111 2222 3333  111 2222 3333  111  111 0000 2222 0000 2222 0000  111 0000 3333 2222 0000  111 3333 0000  111 2222 0000 3333 2222  111 2222 3333 0000 2222 2222 3333 0000

EDIT: Ruby, 87 chars
0.upto(4){|n|$*[0].bytes{|x|$><<"%04b0"%:f6ff929192279241f7ff[x-48+4*n].to_i(16)}
puts}

A creative one! Very nice. This will look fabulous in my designs. Have an upvote.

Tricky! Will take me some time to understand it.

Ruby
Vertical: 116 characters
f="f999f62227f924ff171f".chars.map{|c|c.hex.to_s(2).rjust(4).tr"01"," #"}
$<.chars{|c|i=c.to_i*5;$><<f[i,5]*$/+$/*2}

Sample run:
bash-4.2$ echo -n 321 | ruby -e 'f="f999f62227f924ff171f".chars.map{|c|c.hex.to_s(2).rjust(4).tr"01"," #"};$<.chars{|c|i=c.to_i*5;$><<f[i,5]*$/+$/*2}'
####
   #
 ###
   #
####

####
#  #
  #
 #
####

 ##
  #
  #
  #
 ###

Horizontal: 150 148 characters
f="f999f62227f924ff171f".chars.map{|c|c.hex.to_s(2).rjust(4).tr"01"," #"}
o=(0..4).map{""}
$<.chars{|c|5.times{|j|o[j]<<f[c.to_i*5+j]+" "}}
$><<o*$/

Sample run:
bash-4.2$ echo -n 321 | ruby -e 'f="f999f62227f924ff171f".chars.map{|c|c.hex.to_s(2).rjust(4).tr "01"," #"};o=(0..4).map{""};$<.chars{|c|5.times{|j|o[j]<<f[c.to_i*5+j]+" "}};$><<o*$/'
#### ####  ##
   # #  #   #
 ###   #    #
   #  #     #
#### ####  ###

I was going to encode it like that. Don't think I can beat this is my language though!

Mathematica 174 145 139 118 119 123 chars
Now works with input in base 10 (Integer bonus).  Earlier versions can be found in edits.

Using ArrayPlot:
With ArrayPlot we can directly convert the 1's and 0's to black and white squares, saving a few chars in the process.  For example, with n = 58021, which is 32022211 in base 4:
i = IntegerDigits; i[n, 4] /. Thread@Rule[0~Range~3, ArrayPlot /@ ((PadLeft[#, 4] & /@ i[#, 2]) & /@ (i@{89998, 62227, 89248, 81718} /. {8 -> 15}))]

Explanation
Input is program parameter, n.
Zero can be represented by {{1,1,1,1},{1,0,0,1},{1,0,0,1},{1,0,0,1},{1,1,1,1}
or by the hex counterpart f999f.
The expression, f999f62227f924ff171f, holds the information to display all the numbers {0,1,2,3}. (Note: it begins with f999f, which as we noted, is zero in disguise.)  Because Mathematica does not recognize this as a number, I used  89998622278924881718 (in four integer strings) instead, broke up the number into its integer digits, and then used 15 in every place an 8 appeared.  (That allowed me to use digits instead of strings throughout.)

Your output doesn't match the input.

Can't you just transpose that for the vertical bonus?

As I understand the rules, the bonus is for the horizontal configuration.

Mr. Lister Good catch. I copied and pasted the picture of zero in the place of 1.

My bad, misread.

Pretty cool to output is as matrices. Nice one.

@Accatyyc Thanks. Btw, were you able to figure out what 89998622278924881718 stands for?

I haven't really analyzed it since I'm on a bus right now, but my initial thought was that it is a bitmap representation of the characters. Not sure about the format though!

I'll explain it in the text.

That's not bending the rules. It says clearly in the OP that '#' can be replaced by any character :)

@Accatyyc Thanks. I hadn't noticed.

Mathematica, 112 107 103
My take on David's method.
i=IntegerDigits;Grid/@i@n/.Thread[0~Range~3->("#"i[i@#/.8->15,2,4]&/@{89998,62227,89248,81718}/.0->"")]

105 with the BONUS:
(for n = 54321)
i=IntegerDigits;Grid/@n~i~4/.Thread[0~Range~3->("#"i[i@#/.8->15,2,4]&/@{89998,62227,89248,81718}/.0->"")]

Very nice indeed. So few characters with the bonus. Good work!

APL (58 57)
{' #'[1+5 4⍴1022367 401959 1020495 988959[1+⍎⍵]⊤⍨20⍴2]}¨⍞

Output:

0123
 ####   ##   ####  ####
 #  #    #   #  #     #
 #  #    #     #    ###
 #  #    #    #       #
 ####   ###  ####  ####

Python 2.7
Vertical 160
for i in input():print['****\n*  *\n*  *\n*  *\n****',' ** \n  * \n  * \n  * \n***','****\n*  *\n  * \n *  \n****','****\n   *\n ***\n   *\n****'][int(i)]+'\n'

Horizontal 234 216
x=[['****\n*  *\n*  *\n*  *\n****',' ** \n  * \n  * \n  * \n ***','****\n*  *\n  * \n *  \n****','****\n   *\n ***\n   *\n****'][int(i)]for i in input()]
for i in range(5):print' '.join([y.split('\n')[i]for y in x])

Both take input as a quoted string on stdin
example:
$./pretty
"0123"

How you run this? I get errors. Python 2: "TypeError: 'int' object is not iterable", Python 3: "TypeError: 'builtin_function_or_method' object is not subscriptable".

@manatwork This is in python 2.7, I have edited the answer to make that clear.

@manatwork Also, it looks like you may have been entering the numbers without quotes around them ie: 0123. You should try entering "0123" on stdin.

Got it working now. Sorry, that quoting trick was not evident for me.

@manatwork in python versions before 3 the input() function evaluates the input as if it were a python expression. If the quotes are not there, the program tries to iterate over an integer, giving you the error you got.


text:
Output a Dance Dance Revolution arrow chart
If you're not familiar, Dance Dance Revolution is a rhythm game where you hit four receptors (left, down, up, right) with your feet as arrows scroll up the screen. One of the file formats used to lay out the arrow patterns looks something like this:
1000
0100
0000
0011
,

A 1 represents a tap note. This chart has a left tap, a down tap, an empty line, and an up-right jump, respectively. The comma at the end indicates the end of a measure, and there can be any number of measures in a song.
Now here's an example of a more complicated chart:
1000
0010
0100
0001
0010
0100
2000
0000
,
0010
0001
3100
1001
,

The first measure has eight lines, so each line represents an eighth note, but the second measure only has four lines, all of which are quarter notes. All measures are the same duration; measures containing more lines are simply denser. You can assume that all measures will have lengths that are powers of two greater than or equal to 4. So measures can have 4 lines, 8 lines, 16 lines, and so on.
A 2 indicates the start of a hold arrow and a 3 represents its end. You can assume that each 2 will have a corresponding 3 in the same column, without anything between them other than zeroes and/or measure boundaries.
Your task is to print the stepchart in a more human-readable format. It's probably best if I just give you an example. Here's the expected output for the chart given above:
<
  ^
 v
   >
  ^
 v
<
|
| ^
|
|  >
|
|v

<  >

(If this is confusing to you, perhaps looking at this will help.)
Left, down, up, and right taps are indicated by <, v, ^, and >, respectively. Hold arrows are indicated by pipes that trail beneath the starting taps.
Additionally, the chart needs to be stretched so that each measure is the same length: in the above example, the measures have lengths of 8 and 4, so the output shows all measures as if they contained eighths. If you have a chart where all measures are 4 lines long except for one that's 64 lines, the output needs to render all measures as 64 lines long!
I/O: Assume the chart exists in a file whose name is given as the first argument to the program (e.g. python arrows.py input.txt). Write to standard output. If (and only if) your language of choice doesn't have filesystem access for whatever reason, it's acceptable to load it as a string at the beginning of the program.
Goal: The program with the fewest characters will be accepted a week from now, the 17th of August, around 8:00 EST.

Can the held steps be exclusive? By that I mean that the location in the file where a '3' is present, there is no '|', but they are present in the previous lines? Also is it necessary to prevent an error if the file name is invalid?

@Aslai, there should be a pipe on the location of the 3 because otherwise, if there were a 2 immediately followed by a 3, it would look identical to a tap note. You don't have to handle invalid input (bad filename, malformed chart data) in any way.

Can there be more that one hold active at a time? (Common sense suggests there can't be more than two since humans have but two feet.. assuming humans.. and feet...)

@baby-rabbit, there can potentially be four active holds simultaneously, although that doesn't show up in actual dance charts too often. :)

GolfScript 132 129
','/{n/{},}%{},.{,}%.$):§;;{§\/(}%]zip{~:¥;{['0'4*]¥*~}%}%{+}*zip 1:¤;{0:^;{.^2=5@48=!¤*if\48-^or:^;' <v^>|'=}%¤):¤;}%zip{+}*4/n*

Online demo here

C, 364, 331, 310, 293
#define L(A)for(p=b+9;*p;)if(*p-44){A;t++;p+=5;}else{m=t>m?t:m;p[4-5*t]=t;t=0;p+=2;}
c,j,t,m,x;char b[9999],*p;main(int i,char*v[]){read(open(v[1],0),b+9,9999);L()L(x=t?x:m/p[4];for(j=x*4;j-->0;){i=j%4;b[i]=" |"[b[i+5]];c=p[i]&3;p[i]=0;if(c&&c<3)b[i]="<v^>"[i];if(c>1)b[i+5]=3-c;i?:puts(b);})}

Limits:

max input file size of 9990 chars
max measure of 128

Run:
./a.out test.dance

output:
<
  ^
 v
   >
  ^
 v
<
|
| ^
|
|  >
|
|v

<  >

Ungolfed commented version:
#define L(A)\
  for(p=b+9;*p;)/* loop through file */\
    if(*p-44){     /* line */\
          A;\
          t++;\
          p+=5;       /* 4 steps+linefeed */\
    }else{         /* comma line */\
          m=t>m?t:m;  /* max measure */\
          p[4-5*t]=t; /* store measure in '\n' char of first line */\
          t=0;\
          p+=2;       /* comma+linefeed */\
    }

c,j,t,m,x;char b[9999],*p; // b[0..4] output, b[5..8]=hold, b[9..9999]=file
main(int i,char*v[]){
    read(open(v[1],0),b+9,9999);
    // pass 1 - determine max measure
    L()
    // pass 2 - process steps and output
    L(x=t?x:m/p[4]; // repeats per line (first line p[4] is measure)
      for(j=x*4;j-->0;){ // 4 steps per repeat
          i=j%4;         // the step
          b[i]=" |"[b[i+5]];
          c=p[i]&3;      // step type 0,1,2,3
          p[i]=0;        // reset step to 0 for future iterations
          if(c&&c<3)b[i]="<v^>"[i];
          if(c>1)b[i+5]=3-c; // set/reset hold
          i?:puts(b);    // every 4th step
      }
    )
}

Good game, sir.

C - 466 460 438 bytes
#define C while(fgets(b,6,f))
p[9]={'>^v<',0,'||||',0,'    '},Y,M,T,R,E,*W,Q,i;char b[9];main(int n,char*v[]){int*f=fopen(v[1],"r");W=malloc(4e5);C if(*b!=44)++T;else{W[++Q-1]=T;Y=T>Y?T:Y;T=0;}fseek(f,0,0);Q=0;C{if(*b!=44){R=0;M=E;for(i=0;i<4;++i){R|=(b[i]>48&&b[i]<51)*255<<i*8;E|=b[i]==50?255<<i*8:0;E&=~(b[i]==51?255<<i*8:0);}p[6]=*p&R|(~R^M)&p[4]|(M&R^M)&p[2];puts(p+6);p[6]=p[4]&~E|p[2]&E;for(i=0;i<Y/W[Q]-1;++i)puts(p+6);}else++Q;}}

The output from this, using the given input file, is:
<
  ^
 v
   >
  ^
 v
<
|
| ^
|
|  >
|
|v

<  >

Should be fairly compliant to most compilers.

I count 466 chars here, guess it's a typo. You can save 12 bytes by using multi-character character constants: p[9]={'>^v<',0,'||||',0,'    '}

Aha, I forgot about multicharacter char literals. I also fixed it up according to my comment on the main question. Hooray for bitwise manipulation!

PHP 274 chars
My first code golf. All comments are welcome.
<?php
    $i = '1000 0010 0100 0001 0010 0100 2000 0000 0010 0001 3100 1001 ,';
    $f=explode(' ', $i);$a=array("<","v","^",">");$t=-1;foreach($f as$n){if($n==',')return;else{$j=str_split($n);$o=0;foreach($j as$h){switch($h){case 2:$t=$o;case 1:$h=$a[$o];break;case 0:$h=" ";if($t>=0&&$t==$o){$h="|";}break;case 3:$t=4;$h="|";break;}echo$h;$o++;}echo"\n";}}
?>

Should I count the <?php ?> tags?
Thank you.

Whenever I golf with my friend who uses PHP, he has a . The official PHP parser handles this, but it's out of spec. But hey, this is codegolf, where undefined behavior rules the school.

Mathematica 283 chars
The following works with measures of 2^(2 n) lines.
v = Import["a.xls"];
g@p_ := 2~Log~p; t = Transpose; l = Length; s = Sequence;
r_~h~o_ := t[Flatten[
    Riffle[#, x, {2, -1, 2}] /. x -> s @@ ConstantArray[{0, 0, 0, 0},
          2^(g@Max[l /@ v] - g@l@#) - 1] & /@ v, 1]][[r]]
    /. {a___, 2, b__, 3, c___} :>  {a, 2, s @@ Cases[{b}, 0 :> "|"], "|", c}
    /. {0 -> " "} /. {1 | 2 -> o};
t@{1~h~"<", 2~h~"v", 3~h~"^", 4~h~">"} // Grid

Data file, imported as v, is structured as follows:
{{{1,0,0,0},{0,0,1,0},{0,1,0,0},{0,0,0,1},{0,0,1,0},{0,1,0,0},{2,0,0,0},{0,0,0,0}},{{0,0,1,0},{0,0,0,1},{3,1,0,0},{1,0,0,1}}};