text:
The number of reachable snake orientations
This challenge is not about the game Snake.
Imagine a 2d snake formed by drawing a horizontal line of length n.  At integer points along its body, this snake can rotate its body by 90 degree. If we define the front of the snake to be on the far left to start with, the rotation will move the back part of the snake and the front part will stay put. By doing repeated rotations it can make a lot of different snake body shapes.
Rules

One part of the snake's body can't overlap another.
It has to be possible to reach the final orientation without any parts of the snake's body overlapping in between. Two points that touch are counted as overlapping in this problem.
I regard a snake and its reverse as being the same shape.

Task

Up to rotation, translation and mirror symmetry, what is the total
  number of different snake body shapes that can be made?

Example of a rotation of part of the snakes body. Imagine n=10 and the snake is in its start orientation of a straight line. Now rotate at point 4 90 degrees counter-clockwise. We get the snake from  4 to 10 (the tail of the snake) lying vertically and the snake from 0 to 4 lying horizontally. The snake now has one right angle in its body.
Here are some examples thanks to Martin Büttner.
We start with the horizontal snake.

Now we rotate from position 4.

We end up after the rotation in this orientation.

Now let us consider this orientation of a different snake.

We can now see an illegal move where there would be an overlap caused during the rotation.

Score
Your score is the largest n for which your code can solve the problem in less than one minute on my computer.
When a rotation happens it will move one half of the snake with it. We do have to worry about whether any of this part which is rotated might overlap a part of the snake during the rotation.  For simplicity we can assume the snake has width zero.  You can only rotate at a particular point in snake up to 90 degrees clockwise of counter clockwise. For, you can never full fold the snake in two as that would have involved two rotations at the same point in the same direction.
Shapes that can't be made
A simple example of a shape that can't be made is a capital T.   A more sophisticated version is

(Thank you to Harald Hanche-Olsen for this example)
In this example all the adjacent horizontal lines are 1 apart as are the vertical ones. There is therefore no legal move from this position and as the problem is reversible there is therefore no way to get there from the starting position.
Languages and libraries
You can use any language which has a freely available compiler/interpreter/etc. for Linux and any libraries which are also freely available for Linux.
My machine
The timings will be run on my machine. This is a standard ubuntu install on an AMD FX-8350 Eight-Core Processor. This also means I need to be able to run your code. As a consequence, only use easily available free software and please include full instructions how to compile and run your code.

You say up top that "At integer points along its body, this snake can rotate its body by 90 degree" but later state that "When a rotation happens it will move one half of the snake with it" which suggests that not all integer positions are allowed.
Additionally, with your second example, I'm a bit confused as to why that is an illegal snake. Wouldn't the following transforms lead to that configuration. Starting with the upper endpoint, moving left:
Forward for a while. 90 CC. Move 2. 90 CC. Forward. 90 C. Move 1. 90 C. Forward. 90 C. Forward. 90C. Forward. 90 C. Move 2. 90 C. Forward.

@TApicella Thanks for the questions. When I say "When a rotation happens it will move one half of the snake with it" I didn't mean 50 percent. I was just referring to the part before the rotation point and the part after it. If you rotate from 0 along the snake you rotate the whole thing!

@TApicella About your second question. The point is that there is no legal rotation from the position I gave. If it was reachable it must be possible to get back to the horizontal starting orientation by a sequence of rotations (the reverse of the ones you would have taken to get to the end orientation.)  Can you describe one legal rotation you think you can make from this position?  To be clear, the snake doesn't grow. It always stays the same length throughout.

@TApicella It sounds like you expect the snake to be growing. It's size is fixed though. You start with one long snake and all you are allowed to do is fold parts of it by 90 degrees. From the current position you can't apply any fold at all that would lead to a previous stage of the snake.

Can you fold at a point more than once (back and forth)? If you can that makes it pretty complex.

@randomra You can indeed as long as you never go further than ninety degrees from straight on.

Could you illustrate the section “Example of a rotation of part of the snakes body.” with some diagrams? I have problems imagining it.

@FUZxxl Lots of diagrams now added.

If two submissions have the same largest n solvable in under 1 minute, would you consider using the time to solve with n+1 as a tie breaker?

@trichoplax That's a good idea.

@Lembik: How will you confirm that results are accurate?  How can we confirm that results are accurate?  Maybe post results for n=1..10 or something so we can debug, and insist that results must be calculated and code cannot use any knowledge about the results for n>4 to help reach the results.

@MooingDuck I was just going to check the answers for the first few values by hand.  There aren't that many for n = 4 say. (And actually I was hoping there would be >1 answer so we could compare higher values.) Does this mean you might submit an answer? That would be great if you did.

Does a length n snake have length n + 1 integer points? A snake is explained as: "2d snake formed by drawing a horizontal line of length n." Would that mean the example horizontal snake is n = 10 but would have 11 integer points (0-11)? (Even though I guess rotating at position 0 and 11 doesn't do anything useful) As an example take a snake of size n = 4 that bends 90 degrees  on every join. Is that possible or is it impossible because head and tail are the same integer points?

A snake of length n has n+1 points.

n+1 points including the endpoints. n-1 joints excluding the endpoints

Python 3 - provisional score: n=11 (n=13 with PyPy*)
Since there have been no answers in the first week, here is an example in Python to encourage competition. I've tried to make it reasonably readable so that inefficiencies can be identified easily to give ideas for other answers.
Approach

Start with the straight snake and find all the positions that can be legally reached in one move.
Find all the positions that can be legally reached from those positions, that haven't already been identified.
Repeat until no more can be found, and return the number of positions found altogether.

Code
(now with some doctests and asserts after my incorrect first attempt)
'''
Snake combinations

A snake is represented by a tuple giving the relative orientation at each joint.
A length n snake has n-1 joints.
Each relative orientation is one of the following:

0: Clockwise 90 degrees
1: Straight
2: Anticlockwise 90 degrees

So a straight snake of length 4 has 3 joints all set to 1:

(1, 1, 1)

x increases to the right
y increases upwards

'''

import turtle

def all_coords(state):
    '''Return list of coords starting from (0,0) heading right.'''
    current = (1, 0)
    heading = 0
    coords = [(0,0), (1,0)]
    for item in state:
        heading += item + 3
        heading %= 4
        offset = ((1,0), (0,1), (-1,0), (0,-1))[heading]
        current = tuple(current[i]+offset[i] for i in (0,1))
        coords.append(current)
    return coords

def line_segments(coords, pivot):
    '''Return list of line segments joining consecutive coords up to pivot-1.'''
    return [(coords[i], coords[i+1]) for i in range(pivot+1)]

def rotation_direction(coords, pivot, coords_in_final_after_pivot):
    '''Return -1 if turning clockwise, 1 if turning anticlockwise.'''
    pivot_coord = coords[pivot + 1]
    initial_coord = coords[pivot + 2]
    final_coord = coords_in_final_after_pivot[0]
    initial_direction = tuple(initial_coord[i] - pivot_coord[i] for i in (0,1))
    final_direction = tuple(final_coord[i] - pivot_coord[i] for i in (0,1))
    return (initial_direction[0] * final_direction[1] -
            initial_direction[1] * final_direction[0]
            )

def intersects(arc, line):
    '''Return True if the arc intersects the line segment.'''
    if line_segment_cuts_circle(arc, line):
        cut_points = points_cutting_circle(arc, line)
        if cut_points and cut_point_is_on_arc(arc, cut_points):
            return True

def line_segment_cuts_circle(arc, line):
    '''Return True if the line endpoints are not both inside or outside.'''
    centre, point, direction = arc
    start, finish = line
    point_distance_squared = distance_squared(centre, point)
    start_distance_squared = distance_squared(centre, start)
    finish_distance_squared = distance_squared(centre, finish)
    start_sign = start_distance_squared - point_distance_squared
    finish_sign = finish_distance_squared - point_distance_squared
    if start_sign * finish_sign <= 0:
        return True

def distance_squared(centre, point):
    '''Return the square of the distance between centre and point.'''
    return sum((point[i] - centre[i]) ** 2 for i in (0,1))

def cut_point_is_on_arc(arc, cut_points):
    '''Return True if any intersection point with circle is on arc.'''
    centre, arc_start, direction = arc
    relative_start = tuple(arc_start[i] - centre[i] for i in (0,1))
    relative_midpoint = ((relative_start[0] - direction*relative_start[1])/2,
                         (relative_start[1] + direction*relative_start[0])/2
                         )
    span_squared = distance_squared(relative_start, relative_midpoint)
    for cut_point in cut_points:
        relative_cut_point = tuple(cut_point[i] - centre[i] for i in (0,1))
        spacing_squared = distance_squared(relative_cut_point,
                                           relative_midpoint
                                           )
        if spacing_squared <= span_squared:
            return True

def points_cutting_circle(arc, line):
    '''Return list of points where line segment cuts circle.'''
    points = []
    start, finish = line
    centre, arc_start, direction = arc
    radius_squared = distance_squared(centre, arc_start)
    length_squared = distance_squared(start, finish)
    relative_start = tuple(start[i] - centre[i] for i in (0,1))
    relative_finish = tuple(finish[i] - centre[i] for i in (0,1))
    relative_midpoint = tuple((relative_start[i] +
                               relative_finish[i]
                               )*0.5 for i in (0,1))
    determinant = (relative_start[0]*relative_finish[1] -
                   relative_finish[0]*relative_start[1]
                   )
    determinant_squared = determinant ** 2
    discriminant = radius_squared * length_squared - determinant_squared
    offset = tuple(finish[i] - start[i] for i in (0,1))
    sgn = (1, -1)[offset[1] < 0]
    root_discriminant = discriminant ** 0.5
    one_over_length_squared = 1 / length_squared
    for sign in (-1, 1):
        x = (determinant * offset[1] +
             sign * sgn * offset[0] * root_discriminant
             ) * one_over_length_squared
        y = (-determinant * offset[0] +
             sign * abs(offset[1]) * root_discriminant
             ) * one_over_length_squared
        check = distance_squared(relative_midpoint, (x,y))
        if check <= length_squared * 0.25:
            points.append((centre[0] + x, centre[1] + y))
    return points

def potential_neighbours(candidate):
    '''Return list of states one turn away from candidate.'''
    states = []
    for i in range(len(candidate)):
        for orientation in range(3):
            if abs(candidate[i] - orientation) == 1:
                state = list(candidate)
                state[i] = orientation
                states.append(tuple(state))
    return states

def reachable(initial, final):
    '''
    Return True if final state can be reached in one legal move.

    >>> reachable((1,0,0), (0,0,0))
    False

    >>> reachable((0,1,0), (0,0,0))
    False

    >>> reachable((0,0,1), (0,0,0))
    False

    >>> reachable((1,2,2), (2,2,2))
    False

    >>> reachable((2,1,2), (2,2,2))
    False

    >>> reachable((2,2,1), (2,2,2))
    False

    >>> reachable((1,2,1,2,1,1,2,2,1), (1,2,1,2,1,1,2,1,1))
    False

    '''
    pivot = -1
    for i in range(len(initial)):
        if initial[i] != final[i]:
            pivot = i
            break

    assert pivot > -1, '''
        No pivot between {} and {}'''.format(initial, final)
    assert initial[pivot + 1:] == final[pivot + 1:], '''
        More than one pivot between {} and {}'''.format(initial, final)

    coords_in_initial = all_coords(initial)
    coords_in_final_after_pivot = all_coords(final)[pivot+2:]
    coords_in_initial_after_pivot = coords_in_initial[pivot+2:]
    line_segments_up_to_pivot = line_segments(coords_in_initial, pivot)

    direction = rotation_direction(coords_in_initial,
                                   pivot,
                                   coords_in_final_after_pivot
                                   )

    pivot_point = coords_in_initial[pivot + 1]

    for point in coords_in_initial_after_pivot:
        arc = (pivot_point, point, direction)
        if any(intersects(arc, line) for line in line_segments_up_to_pivot):
            return False
    return True

def display(snake):
    '''Display a line diagram of the snake.

    Accepts a snake as either a tuple:

    (1, 1, 2, 0)

    or a string:

    "1120"

    '''
    snake = tuple(int(s) for s in snake)
    coords = all_coords(snake)

    turtle.clearscreen()
    t = turtle.Turtle()
    t.hideturtle()
    s = t.screen
    s.tracer(0)

    width, height = s.window_width(), s.window_height()

    x_min = min(coord[0] for coord in coords)
    x_max = max(coord[0] for coord in coords)
    y_min = min(coord[1] for coord in coords)
    y_max = max(coord[1] for coord in coords)
    unit_length = min(width // (x_max - x_min + 1),
                      height // (y_max - y_min + 1)
                      )

    origin_x = -(x_min + x_max) * unit_length // 2
    origin_y = -(y_min + y_max) * unit_length // 2

    pen_width = max(1, unit_length // 20)
    t.pensize(pen_width)
    dot_size = max(4, pen_width * 3)

    t.penup()
    t.setpos(origin_x, origin_y)
    t.pendown()

    t.forward(unit_length)
    for joint in snake:
        t.dot(dot_size)
        t.left((joint - 1) * 90)
        t.forward(unit_length)
    s.update()

def neighbours(origin, excluded=()):
    '''Return list of states reachable in one step.'''
    states = []
    for candidate in potential_neighbours(origin):
        if candidate not in excluded and reachable(origin, candidate):
            states.append(candidate)
    return states

def mirrored_or_backwards(candidates):
    '''Return set of states that are equivalent to a state in candidates.'''
    states = set()
    for candidate in candidates:
        mirrored = tuple(2 - joint for joint in candidate)
        backwards = candidate[::-1]
        mirrored_backwards = mirrored[::-1]
        states |= set((mirrored, backwards, mirrored_backwards))
    return states

def possible_snakes(snake):
    '''
    Return the set of possible arrangements of the given snake.

    >>> possible_snakes((1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1))
    {(1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1)}

    '''
    reached = set()
    candidates = set((snake,))

    while candidates:
        candidate = candidates.pop()
        reached.add(candidate)
        new_candidates = neighbours(candidate, reached)
        reached |= mirrored_or_backwards(new_candidates)
        set_of_new_candidates = set(new_candidates)
        reached |= set_of_new_candidates
        candidates |= set_of_new_candidates

    excluded = set()
    final_answers = set()
    while reached:
        candidate = reached.pop()
        if candidate not in excluded:
            final_answers.add(candidate)
            excluded |= mirrored_or_backwards([candidate])

    return final_answers

def straight_derived_snakes(length):
    '''Return the set of possible arrangements of a snake of this length.'''
    straight_line = (1,) * max(length-1, 0)
    return possible_snakes(straight_line)

if __name__ == '__main__':
    import doctest
    doctest.testmod()
    import sys
    arguments = sys.argv[1:]
    if arguments:
        length = int(arguments[0])
    else:
        length = int(input('Enter the length of the snake:'))
    print(len(straight_derived_snakes(length)))

Results
On my machine the longest snake that can be calculated in under 1 minute is length 11 (or length 13 with PyPy*). This is obviously just a provisional score until we find out what the official score is from Lembik's machine.
For comparison, here are the results for the first few values of n:
 n | reachable orientations
-----------------------------
 0 | 1
 1 | 1
 2 | 2
 3 | 4
 4 | 9
 5 | 22
 6 | 56
 7 | 147
 8 | 388
 9 | 1047
10 | 2806
11 | 7600
12 | 20437
13 | 55313
14 | 148752
15 | 401629
16 | 1078746
17 | MemoryError (on my machine)

Please let me know if any of these turn out to be incorrect.
If you have an example of an arrangement that should not be able to be unfolded, you can use the function neighbours(snake) to find any arrangements reachable in one step, as a test of the code. snake is a tuple of joint directions (0 for clockwise, 1 for straight, 2 for anticlockwise). For example (1,1,1) is a straight snake of length 4 (with 3 joints).
Visualisation
To visualise a snake you have in mind, or any of the snakes returned by neighbours, you can use the function display(snake). This accepts a tuple like the other functions, but since it is not used by the main program and therefore does not need to be fast, it will also accept a string, for your convenience.
display((1,1,2,0)) is equivalent to display("1120")
As Lembik mentions in the comments, my results are identical to OEIS A037245 which does not take into account intersections during rotation. This is because for the first few values of n there is no difference - all shapes that do not self-intersect can be reached by folding a straight snake. The correctness of the code can be tested by calling neighbours() with a snake that cannot be unfolded without intersection. Since it has no neighbours it will contribute only to the OEIS sequence, and not to this one. The smallest example I am aware of is this length 31 snake that Lembik mentioned, thanks to David K:
(1,1,1,1,2,1,2,1,1,1,1,1,1,2,1,1,1,2,1,1,2,2,1,0,1,0,1,1,1,1)
display('111121211111121112112210101111') gives the following output:

Tip: If you resize the display window and then call display again, the snake will be fitted to the new window size.

I'd love to hear from anyone who has a shorter example with no neighbours. I suspect that the shortest such example will mark the smallest n for which the two sequences differ.

*Note that each increment of n takes very roughly 3 times as long, so increasing from n=11 to n=13 requires almost 10 times the time. This is why PyPy only allows increasing n by 2, even though it runs considerably faster than the standard Python interpreter.

If this comment gets 5 upvotes I'll look at adding an option to include visualisation of the possible arrangements, in case that helps with analysis.

This turns out to be incorrect :P

@Geobits I think I've got it right this time...

It now seems to be https://oeis.org/A037245 from http://www.americanscientist.org/issues/pub/how-to-avoid-yourself !

@trichoplax Except I still don't believe it :) They don't take into account collisions caused during rotations as far as I can see.  However, it is possible this doesn't make any difference until values of n higher than you have calculated.

My smallest result with collisions caused during rotation is a 22-long snake. If we prove a lower bound you can skip rotation check at all until that length. :P

@randomra I can think of a (much) shorter one.

@Jakube how long? maybe could code the snake in [left|none|right]* format

@randomra The shortest one is a snake of length 8: left, right,left,left,none,left,right or (2, 0, 2, 2, 1, 2, 0) in trichoplax's notation.

@trichoplax Exactly this case is also wrong in your program. Your program thinks, that this sequence is allowed, but it clearly isn't. I haven't debugged your program, but there must be a bug somewhere.

@Jakube This is openable in many ways e.g. in order joint #1 #3 #2 #4 #5 #6.

@randomra What do you mean? If you start at one end, you can only unfold 1 move, on the other end no moves at all.
Here's some quick visualization: http://fs1.directupload.net/images/150206/jsmf6qb8.png

@randomra Oh, I see your point. Are we allowed to rotate in the middle?

@Jakube I'm quite sure, yes.

@Lembik What's your opinion?

The rotations can be in any order any number of times (you can fold a joint to allow another joint to fold and then open it again later).

@Jakube the comments on the question clarify this:  Can you fold at a point more than once (back and forth)? If you can that makes it pretty complex. –  randomra Jan 28 at 16:57 @randomra You can indeed as long as you never go further than ninety degrees from straight on. –  Lembik Jan 28 at 17:09

checking validity of one given folding is anything but trivial. I did not fully reverse engineer your collision detection method, but I don't see how it could work in the general case without computing the hull of the area swept by the moving part.

@kuroineko This is a basic example solution intended to encourage competition. It sweeps out a quarter arc for every point after the pivot, and checks each of these arcs against every line segment up to the one before the pivot. I'm sure there are lots of more efficient ways - for example a line segment longer than 1 could be checked in one step rather than being treated as a sequence of length 1 line segments.

C++11 - nearly working :)
After reading this article, I collected bits of wisdom from that guy who apparently worked for 25 years on the less complicated problem of counting self-avoiding paths on a square lattice.
#include <cassert>
#include <ctime>
#include <sstream>
#include <vector>
#include <algorithm> // sort

using namespace std;

// theroretical max snake lenght (the code would need a few decades to process that value)
#define MAX_LENGTH ((int)(1+8*sizeof(unsigned)))

#ifndef _MSC_VER
#ifndef QT_DEBUG // using Qt IDE for g++ builds
#define NDEBUG
#endif
#endif

#ifdef NDEBUG
inline void tprintf(const char *, ...){}
#else
#define tprintf printf
#endif

void panic(const char * msg)
{
    printf("PANIC: %s\n", msg);
    exit(-1);
}

// ============================================================================
// fast bit reversal
// ============================================================================
unsigned bit_reverse(register unsigned x, unsigned len)
{
    x = (((x & 0xaaaaaaaa) >> 1) | ((x & 0x55555555) << 1));
    x = (((x & 0xcccccccc) >> 2) | ((x & 0x33333333) << 2));
    x = (((x & 0xf0f0f0f0) >> 4) | ((x & 0x0f0f0f0f) << 4));
    x = (((x & 0xff00ff00) >> 8) | ((x & 0x00ff00ff) << 8));
    return((x >> 16) | (x << 16)) >> (32-len);
}

// ============================================================================
// 2D geometry (restricted to integer coordinates and right angle rotations)
// ============================================================================

// points using integer- or float-valued coordinates
template<typename T>struct tTypedPoint;

typedef int    tCoord;
typedef double tFloatCoord;

typedef tTypedPoint<tCoord> tPoint;
typedef tTypedPoint<tFloatCoord>  tFloatPoint;

template <typename T>
struct tTypedPoint {
    T x, y;

    template<typename U> tTypedPoint(const tTypedPoint<U>& from) : x((T)from.x), y((T)from.y) {} // conversion constructor

    tTypedPoint() {}
    tTypedPoint(T x, T y) : x(x), y(y) {}
    tTypedPoint(const tTypedPoint& p) { *this = p; }
    tTypedPoint operator+ (const tTypedPoint & p) const { return{ x + p.x, y + p.y }; }
    tTypedPoint operator- (const tTypedPoint & p) const { return{ x - p.x, y - p.y }; }
    tTypedPoint operator* (T scalar) const { return{ x * scalar, y * scalar }; }
    tTypedPoint operator/ (T scalar) const { return{ x / scalar, y / scalar }; }
    bool operator== (const tTypedPoint & p) const { return x == p.x && y == p.y; }
    bool operator!= (const tTypedPoint & p) const { return !operator==(p); }
    T dot(const tTypedPoint &p) const { return x*p.x + y * p.y; } // dot product
    int cross(const tTypedPoint &p) const { return x*p.y - y * p.x; } // z component of cross product
    T norm2(void) const { return dot(*this); }

    // works only with direction = 1 (90° right) or -1 (90° left)
    tTypedPoint rotate(int direction) const { return{ direction * y, -direction * x }; }
    tTypedPoint rotate(int direction, const tTypedPoint & center) const { return (*this - center).rotate(direction) + center; }

    // used to compute length of a ragdoll snake segment
    unsigned manhattan_distance(const tPoint & p) const { return abs(x-p.x) + abs(y-p.y); }
};

struct tArc {
    tPoint c;                        // circle center
    tFloatPoint middle_vector;       // vector splitting the arc in half
    tCoord      middle_vector_norm2; // precomputed for speed
    tFloatCoord dp_limit;

    tArc() {}
    tArc(tPoint c, tPoint p, int direction) : c(c)
    {
        tPoint r = p - c;
        tPoint end = r.rotate(direction);
        middle_vector = ((tFloatPoint)(r+end)) / sqrt(2); // works only for +-90° rotations. The vector should be normalized to circle radius in the general case
        middle_vector_norm2 = r.norm2();
        dp_limit = ((tFloatPoint)r).dot(middle_vector);
        assert (middle_vector == tPoint(0, 0) || dp_limit != 0);
    }

    bool contains(tFloatPoint p) // p must be a point on the circle
    {
        if ((p-c).dot(middle_vector) >= dp_limit)
        {
            return true;
        }
        else return false;
    }
};

// returns the point of line (p1 p2) that is closest to c
// handles degenerate case p1 = p2
tPoint line_closest_point(tPoint p1, tPoint p2, tPoint c)
{
    if (p1 == p2) return{ p1.x, p1.y };
    tPoint p1p2 = p2 - p1;
    tPoint p1c =  c  - p1;
    tPoint disp = (p1p2 * p1c.dot(p1p2)) / p1p2.norm2();
    return p1 + disp;
}

// variant of closest point computation that checks if the projection falls within the segment
bool closest_point_within(tPoint p1, tPoint p2, tPoint c, tPoint & res)
{
    tPoint p1p2 = p2 - p1;
    tPoint p1c = c - p1;
    tCoord nk = p1c.dot(p1p2);
    if (nk <= 0) return false;
    tCoord n = p1p2.norm2();
    if (nk >= n) return false;
    res = p1 + p1p2 * (nk / n);
    return true;
}

// tests intersection of line (p1 p2) with an arc
bool inter_seg_arc(tPoint p1, tPoint p2, tArc arc)
{
    tPoint m = line_closest_point(p1, p2, arc.c);
    tCoord r2 = arc.middle_vector_norm2;
    tPoint cm = m - arc.c;
    tCoord h2 = cm.norm2();
    if (r2 < h2) return false; // no circle intersection

    tPoint p1p2 = p2 - p1;
    tCoord n2p1p2 = p1p2.norm2();

    // works because by construction p is on (p1 p2)
    auto in_segment = [&](const tFloatPoint & p) -> bool
    {
        tFloatCoord nk = p1p2.dot(p - p1);
        return nk >= 0 && nk <= n2p1p2;
    };

    if (r2 == h2) return arc.contains(m) && in_segment(m); // tangent intersection

    //if (p1 == p2) return false; // degenerate segment located inside circle
    assert(p1 != p2);

    tFloatPoint u = (tFloatPoint)p1p2 * sqrt((r2-h2)/n2p1p2); // displacement on (p1 p2) from m to one intersection point

    tFloatPoint i1 = m + u;
    if    (arc.contains(i1) && in_segment(i1)) return true;
    tFloatPoint i2 = m - u;
    return arc.contains(i2) && in_segment(i2);
}

// ============================================================================
// compact storage of a configuration (64 bits)
// ============================================================================
struct sConfiguration {
    unsigned partition;
    unsigned folding;

    explicit sConfiguration() {}
    sConfiguration(unsigned partition, unsigned folding) : partition(partition), folding(folding) {}

    // add a bend
    sConfiguration bend(unsigned joint, int rotation) const
    {
        sConfiguration res;
        unsigned joint_mask = 1 << joint;
        res.partition = partition | joint_mask;
        res.folding = folding;
        if (rotation == -1) res.folding |= joint_mask;
        return res;
    }

    // textual representation
    string text(unsigned length) const
    {
        ostringstream res;

        unsigned f = folding;
        unsigned p = partition;

        int segment_len = 1;
        int direction = 1;
        for (size_t i = 1; i != length; i++)
        {
            if (p & 1)
            {
                res << segment_len * direction << ',';
                direction = (f & 1) ? -1 : 1;
                segment_len = 1;
            }
            else segment_len++;

            p >>= 1;
            f >>= 1;
        }
        res << segment_len * direction;
        return res.str();
    }

    // for final sorting
    bool operator< (const sConfiguration& c) const
    {
        return (partition == c.partition) ? folding < c.folding : partition < c.partition;
    }
};

// ============================================================================
// static snake geometry checking grid
// ============================================================================
typedef unsigned tConfId;

class tGrid {
    vector<tConfId>point;
    tConfId current;
    size_t snake_len;
    int min_x, max_x, min_y, max_y;
    size_t x_size, y_size;

    size_t raw_index(const tPoint& p) { bound_check(p);  return (p.x - min_x) + (p.y - min_y) * x_size; }
    void bound_check(const tPoint& p) const { assert(p.x >= min_x && p.x <= max_x && p.y >= min_y && p.y <= max_y); }

    void set(const tPoint& p)
    {
        point[raw_index(p)] = current;
    }
    bool check(const tPoint& p)
    {
        if (point[raw_index(p)] == current) return false;
        set(p);
        return true;
    }

public:
    tGrid(int len) : current(-1), snake_len(len)
    {
        min_x = -max(len - 3, 0);
        max_x = max(len - 0, 0);
        min_y = -max(len - 1, 0);
        max_y = max(len - 4, 0);
        x_size = max_x - min_x + 1;
        y_size = max_y - min_y + 1;
        point.assign(x_size * y_size, current);
    }

    bool check(sConfiguration c)
    {
        current++;
        tPoint d(1, 0);
        tPoint p(0, 0);
        set(p);
        for (size_t i = 1; i != snake_len; i++)
        {
            p = p + d;
            if (!check(p)) return false;
            if (c.partition & 1) d = d.rotate((c.folding & 1) ? -1 : 1);
            c.folding >>= 1;
            c.partition >>= 1;
        }
        return check(p + d);
    }

};

// ============================================================================
// snake ragdoll
// ============================================================================
class tSnakeDoll {
    vector<tPoint>point; // snake geometry. Head at (0,0) pointing right

    // allows to check for collision with the area swept by a rotating segment
    struct rotatedSegment {
        struct segment { tPoint a, b; };
        tPoint  org;
        segment end;
        tArc    arc[3];
        bool extra_arc; // see if third arc is needed

        // empty constructor to avoid wasting time in vector initializations
        rotatedSegment(){}
        // copy constructor is mandatory for vectors *but* shall never be used, since we carefully pre-allocate vector memory
        rotatedSegment(const rotatedSegment &){ assert(!"rotatedSegment should never have been copy-constructed"); }

        // rotate a segment
        rotatedSegment(tPoint pivot, int rotation, tPoint o1, tPoint o2)
        {
            arc[0] = tArc(pivot, o1, rotation);
            arc[1] = tArc(pivot, o2, rotation);
            tPoint middle;
            extra_arc = closest_point_within(o1, o2, pivot, middle);
            if (extra_arc) arc[2] = tArc(pivot, middle, rotation);
            org = o1;
            end = { o1.rotate(rotation, pivot), o2.rotate(rotation, pivot) };
        }

        // check if a segment intersects the area swept during rotation
        bool intersects(tPoint p1, tPoint p2) const
        {
            auto print_arc = [&](int a) { tprintf("(%d,%d)(%d,%d) -> %d (%d,%d)[%f,%f]", p1.x, p1.y, p2.x, p2.y, a, arc[a].c.x, arc[a].c.y, arc[a].middle_vector.x, arc[a].middle_vector.y); };

            if (p1 == org) return false; // pivot is the only point allowed to intersect
            if (inter_seg_arc(p1, p2, arc[0]))
            {
                print_arc(0);
                return true;
            }
            if (inter_seg_arc(p1, p2, arc[1]))
            {
                print_arc(1);
                return true;
            }
            if (extra_arc && inter_seg_arc(p1, p2, arc[2]))
            {
                print_arc(2);
                return true;
            }
            return false;
        }
    };

public:
    sConfiguration configuration;
    bool valid;

    // holds results of a folding attempt
    class snakeFolding {
        friend class tSnakeDoll;
        vector<rotatedSegment>segment; // rotated segments
        unsigned joint;
        int direction;
        size_t i_rotate;

        // pre-allocate rotated segments
        void reserve(size_t length)
        {
            segment.clear(); // this supposedly does not release vector storage memory
            segment.reserve(length);
        }

        // handle one segment rotation
        void rotate(tPoint pivot, int rotation, tPoint o1, tPoint o2)
        {
            segment.emplace_back(pivot, rotation, o1, o2);
        }
    public:
        // nothing done during construction
        snakeFolding(unsigned size)
        {
            segment.reserve (size);
        }
    };

    // empty default constructor to avoid wasting time in array/vector inits
    tSnakeDoll() {}

    // constructs ragdoll from compressed configuration
    tSnakeDoll(unsigned size, unsigned generator, unsigned folding) : point(size), configuration(generator,folding)
    {
        tPoint direction(1, 0);
        tPoint current = { 0, 0 };
        size_t p = 0;
        point[p++] = current;
        for (size_t i = 1; i != size; i++)
        {
            current = current + direction;
            if (generator & 1)
            {
                direction.rotate((folding & 1) ? -1 : 1);
                point[p++] = current;
            }
            folding >>= 1;
            generator >>= 1;
        }
        point[p++] = current;
        point.resize(p);
    }

    // constructs the initial flat snake
    tSnakeDoll(int size) : point(2), configuration(0,0), valid(true)
    {
        point[0] = { 0, 0 };
        point[1] = { size, 0 };
    }

    // constructs a new folding with one added rotation
    tSnakeDoll(const tSnakeDoll & parent, unsigned joint, int rotation, tGrid& grid)
    {
        // update configuration
        configuration = parent.configuration.bend(joint, rotation);

        // locate folding point
        unsigned p_joint = joint+1;
        tPoint pivot;
        size_t i_rotate = 0;
        for (size_t i = 1; i != parent.point.size(); i++)
        {
            unsigned len = parent.point[i].manhattan_distance(parent.point[i - 1]);
            if (len > p_joint)
            {
                pivot = parent.point[i - 1] + ((parent.point[i] - parent.point[i - 1]) / len) * p_joint;
                i_rotate = i;
                break;
            }
            else p_joint -= len;
        }

        // rotate around joint
        snakeFolding fold (parent.point.size() - i_rotate);
        fold.rotate(pivot, rotation, pivot, parent.point[i_rotate]);
        for (size_t i = i_rotate + 1; i != parent.point.size(); i++) fold.rotate(pivot, rotation, parent.point[i - 1], parent.point[i]);

        // copy unmoved points
        point.resize(parent.point.size()+1);
        size_t i;
        for (i = 0; i != i_rotate; i++) point[i] = parent.point[i];

        // copy rotated points
        for (; i != parent.point.size(); i++) point[i] = fold.segment[i - i_rotate].end.a;
        point[i] = fold.segment[i - 1 - i_rotate].end.b;

        // static configuration check
        valid = grid.check (configuration);

        // check collisions with swept arcs
        if (valid && parent.valid) // ;!; parent.valid test is temporary
        {
            for (const rotatedSegment & s : fold.segment)
            for (size_t i = 0; i != i_rotate; i++)
            {
                if (s.intersects(point[i+1], point[i]))
                {
                    //printf("! %s => %s\n", parent.trace().c_str(), trace().c_str());//;!;
                    valid = false;
                    break;
                }
            }
        }
    }

    // trace
    string trace(void) const
    {
        size_t len = 0;
        for (size_t i = 1; i != point.size(); i++) len += point[i - 1].manhattan_distance(point[i]);
        return configuration.text(len);
    }
};

// ============================================================================
// snake twisting engine
// ============================================================================
class cSnakeFolder {
    int length;
    unsigned num_joints;
    tGrid grid;

    // filter redundant configurations
    bool is_unique (sConfiguration c)
    {
        unsigned reverse_p = bit_reverse(c.partition, num_joints);
        if (reverse_p < c.partition)
        {
            tprintf("P cut %s\n", c.text(length).c_str());
            return false;
        }
        else if (reverse_p == c.partition) // filter redundant foldings
        {
            unsigned first_joint_mask = c.partition & (-c.partition); // insulates leftmost bit
            unsigned reverse_f = bit_reverse(c.folding, num_joints);
            if (reverse_f & first_joint_mask) reverse_f = ~reverse_f & c.partition;

            if (reverse_f > c.folding)
            {
                tprintf("F cut %s\n", c.text(length).c_str());
                return false;
            }
        }
        return true;
    }

    // recursive folding
    void fold(tSnakeDoll snake, unsigned first_joint)
    {
        // count unique configurations
        if (snake.valid && is_unique(snake.configuration)) num_configurations++;

        // try to bend remaining joints
        for (size_t joint = first_joint; joint != num_joints; joint++)
        {
            // right bend
            tprintf("%s -> %s\n", snake.configuration.text(length).c_str(), snake.configuration.bend(joint,1).text(length).c_str());
            fold(tSnakeDoll(snake, joint, 1, grid), joint + 1);

            // left bend, except for the first joint
            if (snake.configuration.partition != 0)
            {
                tprintf("%s -> %s\n", snake.configuration.text(length).c_str(), snake.configuration.bend(joint, -1).text(length).c_str());
                fold(tSnakeDoll(snake, joint, -1, grid), joint + 1);
            }
        }
    }

public:
    // count of found configurations
    unsigned num_configurations;

    // constructor does all the work :)
    cSnakeFolder(int n) : length(n), grid(n), num_configurations(0)
    {
        num_joints = length - 1;

        // launch recursive folding
        fold(tSnakeDoll(length), 0);
    }
};

// ============================================================================
// here we go
// ============================================================================
int main(int argc, char * argv[])
{
#ifdef NDEBUG
    if (argc != 2) panic("give me a snake length or else");
    int length = atoi(argv[1]);
#else
    (void)argc; (void)argv;
    int length = 12;
#endif // NDEBUG

    if (length <= 0 || length >= MAX_LENGTH) panic("a snake of that length is hardly foldable");

    time_t start = time(NULL);
    cSnakeFolder snakes(length);
    time_t duration = time(NULL) - start;

    printf ("Found %d configuration%c of length %d in %lds\n", snakes.num_configurations, (snakes.num_configurations == 1) ? '\0' : 's', length, duration);
    return 0;
}

Building the executable
Compile with g++ -O3 -std=c++11
I use MinGW under Win7 with g++4.8 for "linux" builds, so portability is not 100% guaranteed.
It also works (sort of) with a standard MSVC2013 project
By undefining NDEBUG, you get traces of algorithm execution and a summary of found configurations.
Performances
with or without hash tables, Microsoft compiler performs miserably: g++ build is 3 times faster.
The algorithm uses practically no memory.
Since collision check is roughly in O(n), computation time should be in O(nkn), with k slightly lower than 3.
On my i3-2100@3.1GHz, n=17 takes about 1:30 (about 2 million snakes/minute).
I am not done optimizing, but I would not expect more than a x3 gain, so basically I can hope to reach maybe n=20 under an hour, or n=24 under a day.
Reaching the first known unbendable shape (n=31) would take between a few years and a decade, assuming no power outages.
Counting shapes
A N size snake has N-1 joints.
Each joint can be left straight or bent to the left or right (3 possibilities).
The number of possible foldings is thus 3N-1.
Collisions will reduce that number somewhat, so the actual number is close to 2.7N-1
However, many such foldings lead to identical shapes.
two shapes are identical if there is either a rotation or a symetry that can transform one into the other.
Let's define a segment as any straight part of the folded body.
For instance a size 5 snake folded at 2nd joint would have 2 segments (one 2 units long and the second 3 units long).
The first segment will be named head, and the last tail.
By convention we orient the snakes's head horizontally with the body pointing right (like in the OP first figure).
We designate a given figure with a list of signed segment lengths, with positive lengths indicating a right folding and negative ones a left folding.
Initial lenght is positive by convention.
Separating segments and bends
If we consider only the different ways a snake of length N can be split into segments, we end up with a repartition identical to the compositions of N.
Using the same algorithm as shown in the wiki page, it is easy to generate all the 2N-1 possible partitions of the snake.
Each partition will in turn generate all possible foldings by applying either left or right bends to all of its joints. One such folding will be called a configuration.
All possible partitions can be represented by an integer of N-1 bits, where each bit represents the presence of a joint. We will call this integer a generator.
Pruning partitions
By noticing that bending a given partition from the head down is equivalent to bending the symetrical partition from the tail up, we can find all couples of symetrical partitions and eliminate one out of two.
The generator of a symetrical partition is the partition's generator written in reverse bit order, which is trivially easy and cheap to detect.
This will eliminate almost half of the possible partitions, the exceptions being the partitions with "palindromic" generators that are left unchanged by bit reversal (for instance 00100100).
Taking care of horizontal symetries
With our conventions (a snake starts pointing to the right), the very first bend applied to the right will produce a family of foldings that will be horizontal symetrics from the ones that differ only by the first bend.
If we decide that the first bend will always be to the right, we eliminate all horizontal symetrics in one big swoop.
Mopping up the palindromes
These two cuts are efficient, but not enough to take care of these pesky palindromes.
The most thorough check in the general case is as follows:
consider a configuration C with a palindromic partition.

if we invert every bend in C, we end up with a horizontal symetric of C.
if we reverse C (applying bends from the tail up), we get the same figure rotated right
if we both reverse and invert C, we get the same figure rotated left.

We could check every new configuration against the 3 others. However, since we already generate only configurations starting with a right turn, we only have one possible symetry to check:

the inverted C will start with a left turn, which is by construction impossible to duplicate
out of the reversed and inverted-reversed configurations, only one will start with a right turn.
That is the only one configuration we can possibly duplicate.

Eliminating duplicates without any storage
My initial approach was to store all configurations in a huge hash table, to eliminate duplicates by checking the presence of a previously computed symetric configuration.
Thanks to the aforementioned article, it became clear that, since partitions and foldings are stored as bitfields, they can be compared like any numerical value.
So to eliminate one member of a symetric pair, you can simply compare both elements and systematically keep the smallest one (or the greatest one, as you like).
Thus, testing a configuration for duplication amounts to computing the symetric partition, and if both are identical, the folding. No memory is needed at all.
Order of generation
Clearly collision check will be the most time-consuming part, so reducing these computations is a major time-saver.
A possible solution is to have a "ragdoll snake" that will start in a flat configuration and be gradually bent, to avoid recomputing the whole snake geometry for each possible configuration.
By choosing the order in which configurations are tested, so that at most a ragdoll is stored for each total number of joints, we can limit the number of instances to N-1.
I use a recursive scan of the sake from the tail down, adding a single joint at each level. Thus a new ragdoll instance is built on top of the parent configuration, with a single aditional bend.
This means bends are applied in a sequential order, which seems to be enough to avoid self-collisions in almost all cases.
When self-collision is detected, the bends that lead to the offending move are applied in all possible orders until legit folding is found or all combinations are exhausted.
Static check
Before even thinking about moving parts, I found it more efficient to test the static final shape of a snake for self-intersections.
This is done by drawing the snake on a grid. Each possible point is plotted from the head down. If there is a self-intersection, at least a pair of points will fall on the same location.
This requires exactly N plots for any snake configuration, for a constant O(N) time.
The main advantage of this approach is that the static test alone will simply select valid self-avoiding paths on a square lattice, which allows to test the whole algorithm by inhibiting dynamic collision detection and making sure we find the correct count of such paths.
Dynamic check
When a snake folds around one joint, each rotated segment will sweep an area whose shape is anything but trivial.
Clearly you can check collisions by testing inclusion within all such swept areas individually. A global check would be more efficient, but given the areas complexity I can't think of any (except maybe using a GPU to draw all areas and perform a global hit check).
Since the static test takes care of the starting and ending positions of each segment, we just need to check intersections with the arcs swept by each rotating segments.
After an interesting discussion with trichoplax and a bit of JavaScript to get my bearings, I came up with this method:
To try to put it in a few words, if you call

C the center of rotation,
S a rotating segment of arbitrary lenght and direction that does not contain C,
L the line prolongating S
H the line orthogonal to L passing through C,
I the intersection of L and H,

(source: free.fr)
For any segment that does not contain I, the swept area is bound by 2 arcs (and 2 segments already taken care of by the static check).
If I falls within the segment, the arc swept by I must also be taken into account.
This means we can check each unmoving segment against each rotating segment with 2 or 3 segment-with-arc intersections
I used vector geometry to avoid trigonometric functions altogether.
Vector operations produce compact and (relatively) readable code.
Segment-to-arc intersection requires a floating point vector, but the logic should be immune to rounding errors.
I found this elegant and efficient solution in an obscure forum post. I wonder why it is not more widely publicized.
Does it work?
Inhibiting dynamic collision detection produces the correct self-avoiding paths count up to n=19, so I'm pretty confident the global layout works.
Dynamic collision detection produces consistent results, though the check of bends in different order is missing (for now).
As a consequence, the program counts snakes that can be bent from the head down (i.e. with joints folded in order of increasing distance from the head).


text:
Maximally extend integer intervals
Suppose you are given a set of non-intersecting intervals of integers [a1,b1],[a2,b2],[a3,b3],...,[aN,bN]. (Where [a,b] is the set of integers greater than or equal to a and less than or equal to b.)
The interval at index X covers bX - aX + 1 values. We'll call this number cX.
Given that each interval can either be...

unchanged (stays as [aX,bX]),
extended to the right towards the + side of number the line by cX (becoming [aX,bX + cX]),
or extended to the left towards the - side of number the line by cX (becoming [aX - cX,bX]),

what is the maximum number of values that can be covered by the union of all the updated intervals, given that they are still all non-intersecting?
Write a function or program that takes a string of the form [a1,b1],[a2,b2],[a3,b3],...,[aN,bN] and computes this maximum. If writing a function, return the value. If writing a full program, use stdin for input and print the value to stdout (or use closest alternatives).
You may assume all values are well within normal signed 32-bit integer limits and that aX is less than or equal to bX for all indices X. The intervals may be in any order, they are not necessarily always increasing. They must be given as a string in the format above. The string may be empty, in which case the answer will be 0.
The shortest submission in bytes wins.
Example
If the input were [-3,0],[1,2],[4,9] the output would be 22. The middle interval has no room to expand either way so it must remain unchanged. The left and right intervals can both be extended to [-7,0] and [4,15] respectively. The union of [-7,0] and [1,2] and [4,15] contains all the values from -7 to 15, except 3. That's 22 values.

Can we use our language's arrays' native string representation for input, or does it have to be exactly this format?

@MartinBüttner No. You need to use this exact format. (I know thats kind of a double edged sword but thats the way it goes.)

Can you expand a given interval on both sides? For example, can [5,6] become [3,8] (for an answer of 6), or can it be just [5,8] or [3,6] (for an answer of 4)?

@MtnViewMark No. They can only be extended from one side (or not at all)

Haskell, 145 bytes
import Data.List
x=maximum.map length.filter(nub>>=(==)).map concat.sequence.map(\[a,b]->[[2*a-b-1..b],[a..b],[a..2*b-a+1]]).read.('[':).(++"]")

Sample runs:
λ: x ""
0

λ: x "[5,6]"
4

λ: x "[-3,0],[1,2],[4,9]"
22

R, 282 278 269 247
This got big really quickly dealing with the string input.  I suspect I can golf this better, but have run out of time at the moment.
f=function(s){i=matrix(strtoi(strsplit(gsub('[^0-9,-]','',s),',')[[1]]),nrow=2);l=0;if((a<-length(b<-order(i[1,])))>0){if(a>1)i=i[,b];l=diff(i[,1:a])+1;x=c(t(i));for(n in 1:a)if(n==1|n==a|x[n]-l[n]>x[n+a-1]|x[n+a]+l[n]<x[n+1])l[n]=l[n]*2;};sum(l)}

Essentially the idea is

Take in the string and turn it into a 2 row matrix
Make sure it is in the right order
Work out the differences for each column
Double the first and last differences
Double the middle differences if they have a gap to the previous or
next that is large enough
Return the sum of the differences

Edit: realized I miscounted the chars originally, then rearranged a few things to shave a few.

source: Stack Exchange

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

sort: votes


text:
Build a Mining Robot
Your program will control a mining robot searching underground for valuable
minerals. Your robot will tell the controller where you want to move and dig,
and the controller will provide feedback on your robot status.
Initially your robot will be given an image map of the mine with some mining
shafts already present, and a data file specifying the value and hardness of the
minerals in the mine. Your robot will then move through the shafts looking for valuable
minerals to mine. Your robot can dig through the earth, but is slowed down by
hard rock.

The robot that returns with the most valuable cargo after a 24 hour shift
will be the winner. It may seem to be a complicated challenge but it is simple to make a basic mining robot (see the Sample Mining Robot answer below).
Operation
Your program will be started by the controller with the mine image, mineral data, and equipment filenames. Robots can use the mine image and minerals data to find valuable ore and avoid hard rock. The robot may also want to buy equipment from the equipment list.
eg: python driller.py mineimage.png minerals.txt equipmentlist.txt
After a 2 second initialisation period, the controller communicates with the robot program through stdin and stdout. Robots must respond with an action within 0.1 seconds after receiving a status message.
Each turn, the controller sends the robot a status line:
timeleft cargo battery cutter x y direction
eg: 1087 4505 34.65 88.04 261 355 right
The integer timeleft is the game seconds left before the end of shift.  The
cargo is the integer value of the minerals you have mined so far less what you
have paid for equipment. The battery level is an integer percentage of your
remaining battery charge. The cutter integer level is the current sharpness of the
cutter as a percentage of the standard value. The x and y values are positive
integers with the robot position referenced from the top left corner at (0, 0).
The direction is the current direction the robot is facing (left, right, up,
down).
When your robot receives the 'endshift' or 'failed' input, your program will
soon be terminated. You might want your robot to write debugging/performance
data to a file first.
There are 4 possible commands the controller will accept. direction
left|right|up|down will point your robot in that direction, and require 15
game-seconds. move <integer> will instruct your robot to move or dig that many
units forward which takes time depending on the hardness of minerals cut and
sharpness of your cutter (see below). buy <equipment> will install specified
equipment and deduct the cost from your cargo value, but only if the robot is at
the surface (y value <= starting y value). Equipment installation takes 300
game-seconds.  The special command snapshot writes the current mine image to
disk and takes no game time. You can use snapshots to debug your robot or create
animations.
Your robot will start with 100 battery and 100 cutter sharpness. Moving and
turning use a small amount of battery power. Digging uses much more and is a
function of the hardness of the minerals and current sharpness of the cutter. As
your robot digs into minerals, the cutter will lose its sharpness, depending on
the time taken and hardness of the minerals. If your robot has enough cargo
value, it may return to the surface to buy a new battery or cutter. Note that
high quality equipment has an initial effectiveness of over 100%. Batteries have the string "battery" in the name and (surprise) cutters have "cutter" in the name.
The following relationships define moving and cutting:
timecutting = sum(hardness of pixels cut) * 100 / cutter
cutterwear = 0.01 for each second cutting
cutters will not wear below 0.1 sharpness
timemoving = 1 + timecutting
batterydrain = 0.0178 for each second moving
changing direction takes 15 seconds and drains 0.2 from the battery
installing new equipment takes 300 seconds

Note that moving 1 unit without cutting any minerals takes 1 game second and uses 0.0178 of the battery. So the robot can drive 5600 units in 93 game minutes on a standard 100 charge, if it is not cutting minerals or turning.
NEW: The robot is 11 pixels wide so will cut up to 11 pixels with each pixel of movement. If there are less than 11 pixels to cut, the robot will take less time to move, and cause less wear on the cutter. If a pixel color is not specified in the mineral data file, it is free space of zero hardness and zero value.
The run is terminated when time runs out, the robot battery is exhausted, a part
of the robot exceeds the image boundary, an illegal command is sent, or robot
communication times out.
Your score is the final value of the robot cargo.  The controller will output
your score and the final map image. The stderr output of your program is logged in the robot.log file. If your robot dies, the fatal error may be in the log.
The Mine Data
equipment.txt:
Equipment_Name      Cost    Initial_Value
std_cutter          200     100
carbide_cutter      600     160
diamond_cutter      2000    250
forcehammer_cutter  7200    460
std_battery         200     100
advanced_battery    500     180
megapower_battery   1600    320
nuclear_battery     5200    570

mineraldata.txt:
Mineral_Name        Color           Value   Hardness
sandstone           (157,91,46)     0       3
conglomerate        (180,104,102)   0       12
igneous             (108,1,17)      0       42
hard_rock           (219,219,219)   0       15
tough_rock          (146,146,146)   0       50
super_rock          (73,73,73)      0       140
gem_ore1            (0,255,0)       10      8
gem_ore2            (0,0,255)       30      14
gem_ore3            (255,0,255)     100     6
gem_ore4            (255,0,0)       500     21

mine image:

The mine image may have an alpha channel, but this is not used.
The Controller
The controller should work with Python 2.7 and requires the PIL library. I have been informed that the Python Pillow is a Windows friendly download to get the PIL image module.
Start the controller with the robot program, cfg.py, image and data files in the
current directory. The suggested command line is:
python controller.py [<interpreter>] {<switches>} <robotprogram>
E.g.: python controller.py java underminer.class
The controller will write a robot.log file and a finalmine.png file at the end
of the run.
#!/usr/bin/env python
# controller.py
# Control Program for the Robot Miner on PPCG.
# Tested on Python 2.7 on Ubuntu Linux. May need edits for other platforms.
# V1.0 First release.
# V1.1 Better error catching

import sys, subprocess, time
# Suggest installing Pillow here if you don't have PIL already
from PIL import Image, ImageDraw

from cfg import *

program = sys.argv[1:]
calltext = program + [MINEIMAGE, MINERALFILE, EQUIPMENTFILE]
errorlog = open(ERRORFILE, 'wb')
process = subprocess.Popen(calltext,
            stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=errorlog)

image = Image.open(MINEIMAGE)
draw = ImageDraw.Draw(image)
BLACK, ORANGE, WHITE = (0,0,0), (255,160,160), (255,255,255)
W,H = image.size
dirmap = dict(right=(1,0), left=(-1,0), up=(0,-1), down=(0,1))

# read in mineral file (Name, Color, Value, Hardness):
data = [v.split() for v in open(MINERALFILE)][1:]
mineralvalue = dict((eval(color), int(value)) for
    name, color, value, hard in data)
hardness = dict((eval(color), int(hard)) for
    name, color, value, hard in data)

# read in the equipment list:
data = [v.split() for v in open(EQUIPMENTFILE)][1:]
equipment = dict((name, (int(cost), float(init))) for
    name, cost, init in data)

# Set up simulation variables:
status = 'OK'
rx, ry, direction = START_X, START_Y, START_DIR    # center of robot
cargo, battery, cutter = 0, 100.0, 100.0
clock = ENDSHIFT
size = ROBOTSIZE / 2
msgfmt = '%u %u %u %u %u %u %s'
snapnum = 1

def mkcutlist(x, y, direc, size):
    dx, dy = dirmap[direc]
    cx, cy = x+dx*(size+1), y+dy*(size+1)
    output = [(cx, cy)]
    for s in range(1, size+1):
        output += [ (cx+dy*s, cy+dx*s), (cx-dy*s, cy-dx*s)]
    return output

def send(msg):
    process.stdin.write((msg+'\n').encode('utf-8'))
    process.stdin.flush()

def read():
    return process.stdout.readline().decode('utf-8')

time.sleep(INITTIME)
while clock > 0:
    try:
        start = time.time()
        send(msgfmt % (clock, cargo, battery, cutter, rx, ry, direction))
        inline = read()
        if time.time() - start > TIMELIMIT:
            status = 'Move timeout'
            break
    except:
        status = 'Robot comslink failed'
        break

    # Process command:
    movecount = 0
    try:
        arg = inline.split()
        cmd = arg.pop(0)
        if cmd == 'buy':
            if ry <= START_Y and arg and arg[0] in equipment:
                cost, initperc = equipment[arg[0]]
                if cost <= cargo:
                    cargo -= cost
                    if 'battery' in arg[0]:
                        battery = initperc
                    elif 'cutter' in arg[0]:
                        cutter = initperc
                    clock -= 300
        elif cmd == 'direction':
            if arg and arg[0] in dirmap:
                direction = arg[0]
                clock -= 15
                battery -= 0.2
        elif cmd == 'move':
            if arg and arg[0].isdigit():
                movecount = abs(int(arg[0]))
        elif cmd == 'snapshot':
            image.save('snap%04u.png' % snapnum)
            snapnum += 1
    except:
        status = 'Robot command malfunction'
        break

    for move in range(movecount):
        # check image boundaries
        dx, dy = dirmap[direction]
        rx2, ry2 = rx + dx, ry + dy
        print rx2, ry2
        if rx2-size < 0 or rx2+size >= W or ry2-size < 0 or ry2+size >= H:
            status = 'Bounds exceeded'
            break
        # compute time to move/cut through 1 pixel
        try:
            cutlist = mkcutlist(rx2, ry2, direction, size)
            colors = [image.getpixel(pos)[:3] for pos in cutlist]
        except IndexError:
            status = 'Mining outside of bounds'
            break
        work = sum(hardness.get(c, 0) for c in colors)
        timetaken = work * 100 / cutter
        cutter = max(0.1, cutter - timetaken / 100)
        clock -= 1 + int(timetaken + 0.5)
        battery -= (1 + timetaken) / 56
        if battery <= 0:
            status = 'Battery exhausted'
            break
        cargo += sum(mineralvalue.get(c, 0) for c in colors)
        draw.rectangle([rx-size, ry-size, rx+size+1, ry+size+1], BLACK, BLACK)
        rx, ry = rx2, ry2
        draw.rectangle([rx-size, ry-size, rx+size+1, ry+size+1], ORANGE, WHITE)
        if clock <= 0:
            break

    if status != 'OK':
        break

del draw
image.save('finalmine.png')
if status in ('Battery exhausted', 'OK'):
    print 'Score = %s' % cargo
    send('endshift')
else:
    print 'Error: %s at clock %s' % (status, clock)
    send('failed')

time.sleep(0.3)
process.terminate()

The linked config file (not to be changed):
# This is cfg.py

# Scenario files:
MINEIMAGE = 'testmine.png'
MINERALFILE = 'mineraldata.txt'
EQUIPMENTFILE = 'equipment.txt'

# Mining Robot parameters:
START_X = 270
START_Y = 28
START_DIR = 'down'
ROBOTSIZE = 11      # should be an odd number

ENDSHIFT = 24 * 60 * 60   # seconds in an 24 hour shift

INITTIME = 2.0
TIMELIMIT = 0.1

ERRORFILE = 'robot.log'

Answer Format
The answers should have a title including programming language, robot name, and
final score (such as Python 3, Tunnel Terror, 1352). The answer body should have
your code and the final mine map image. Other images or animations are welcome
too. The winner will be the robot with the best score.
Other Rules

The common loopholes are prohibited.
If you use a random number generator, you must hardcode a seed in your
program, so that your program run is reproducable. Someone else must be able
to run your program and get the same final mine image and score.
Your program must be programmed for any mine image. You must not code your
program for these data files or this image size, mineral layout, tunnel
layout, etc. If I suspect a robot is breaking this rule, I reserve the right
to change the mine image and/or data files.

Edits

Explained 0.1 second response rule.
Expanded on robot starting command line options and files.
Added new controller version with better error catching.
Added robot.log note.
Explained default mineral hardness and value.
Explained battery vs cutter equipment.
Made robot size 11 explicit.
Added calculations for time, cutter wear, and battery.

A few questions:

Does your robot "see" the entire map, or only what is near them, or nothing at all? Are robots allowed to use PIL? (I presume not but I wanted to check)
Is there a limit on running time?

@TApicella 1. Robots get the image filename as an argument, and can read and process it as they like. The controllers image will be changing as the robot moves and the robot will not be able to see that. Robots may use PIL or other OSS third party libraries. 2. Robots have 2 seconds to initialize and then 0.1 second per command response.

So the limited initialization time prevents the very silly solutions involving full analysis of the image I presume?

Let's say it gives the "explorer" solutions more of a chance against the "perfect path planning" solutions.

You should document the 0.1 second per command response in the question.

Can we hardcode the minerals and equipment data?

@PeterTaylor Added the 0.1 second response time to question text.

@KeithRandall No. You must read in the image and 2 data files from the filenames given on the command line. They may be changed.

Right now, my initialization is timing out before I even import all of the equipment and mineral data (I'm using Python since that's my most comfortable language and just direct copying the controller's import code)
Is our robot not supposed to know how valuable minerals are?
EDIT: I also might be too much of a noob to know how to initialize only once and it may be trying to initialize again every step

@TApicella I have added another answer with a Python framework that might help.

Are the 2 pixels in the upper left corner supposed to be missing?

It's a feature. Use it to your advantage if you can :)

We really need to have equations for how hardness affects sharpness and battery, to make decent options.  Could you post summaries of those?

I have added a section to the question with the calculations for time taken, cutter wear, and battery drain.

Just a minor remark about equipment definition file. Since there is no explicit type field (battery or cutter), is the type to be deduced from the names themselves (i.e. a cutter name will always contain "cutter")?

@kuroineko, yes, the equipment name will always contain the equipment type string "cutter" or "battery".

Python 2, Sample Miner, 350
This is an example of the minimum code for a mining robot. It just digs straight down until its battery gives out (all robots start pointing down). It only earns a score of 350. Remember to flush stdout or else the controller will hang.
import sys
# Robots are started with 3 arguments:
mineimage, mineralfile, equipmentfile = sys.argv[1:4]
raw_input()           # ignore first status report
print 'move 1000'     # dig down until battery dies
sys.stdout.flush()    # remember to flush stdout
raw_input()           # wait for end message

Python 2, Robot Miner Python Template, 410
This is a mining robot template to show how a robot operates and provide a framework for building your own robots. There is a section for analyzing the mineral data, and a section for responding with actions. The placeholder algorithms do not do well. The robot finds some valuable minerals, but not enough to buy enough replacement batteries and cutters. It halts with a dead battery on its way to the surface to a second time.
A better plan is to use the existing tunnels to get close to valuable minerals and minimise the digging.
Note that this robot writes a log file of each status message it receives so you can check it's decisions after a run.
import sys
from PIL import Image

MINEIMAGE, MINERALFILE, EQUIPMENTFILE = sys.argv[1:4]
image = Image.open(MINEIMAGE)
W,H = image.size
robotwidth = 11
halfwidth = robotwidth / 2

# read in mineral file (Name, Color, Value, Hardness):
data = [v.split() for v in open(MINERALFILE)][1:]
mineralvalue = dict((eval(color), int(value)) for
    name, color, value, hard in data)
hardness = dict((eval(color), int(hard)) for
    name, color, value, hard in data)

# read in the equipment list:
data = [v.split() for v in open(EQUIPMENTFILE)][1:]
equipment = [(name, int(cost), float(init)) for
    name, cost, init in data]
# Find the cheapest battery and cutter for later purchase:
minbatcost, minbatname = min([(c,n) for
    n,c,v in equipment if n.endswith('battery')])
mincutcost, mincutname = min([(c,n) for
    n,c,v in equipment if n.endswith('cutter')])

# process the mine image to find good places to mine:
goodspots = [0] * W
for ix in range(W):
    for iy in range(H):
        color = image.getpixel((ix, iy))[:3]   # keep RGB, lose Alpha
        value = mineralvalue.get(color, 0)
        hard = hardness.get(color, 0)
        #
        # -------------------------------------------------------------
        # make a map or list of good areas to mine here
        if iy < H/4:
            goodspots[ix] += value - hard/10.0
        # (you will need a better idea than this)
goodshafts = [sum(goodspots[i-halfwidth : i+halfwidth+1]) for i in range(W)]
goodshafts[:halfwidth] = [-1000]*halfwidth   # stop robot going outside bounds
goodshafts[-halfwidth:] = [-1000]*halfwidth
bestspot = goodshafts.index(max(goodshafts))
# -----------------------------------------------------------------
#

dirmap = dict(right=(1,0), left=(-1,0), up=(0,-1), down=(0,1))
logging = open('mylog.txt', 'wt')
logfmt = '%7s %7s %7s %7s %7s %7s %7s\n'
logging.write(logfmt % tuple('Seconds Cargo Battery Cutter x y Direc'.split()))
surface = None
plan = []

while True:
    status = raw_input().split()
    if status[0] in ('endshift', 'failed'):
        # robot will be terminated soon
        logging.close()
        continue
    logging.write(logfmt % tuple(status))
    direction = status.pop(-1)
    clock, cargo, battery, cutter, rx, ry = map(int, status)
    if surface == None:
        surface = ry    # return to this level to buy equipment
    #
    # -----------------------------------------------------------------
    # Decide here to choose direction, move, buy, or snapshot
    if not plan and rx != bestspot:
        plan.append('direction right' if bestspot > rx else 'direction left')
        plan.append('move %u' % abs(bestspot - rx))
        plan.append('direction down')

    if plan:
        action = plan.pop(0)
    elif battery < 20 and cargo > minbatcost + mincutcost:
        action = 'direction up'
        move = 'move %u' % (ry - surface)
        buybat = 'buy %s' % minbatname
        buycut = 'buy %s' % mincutname
        plan = [move, buybat, buycut, 'direction down', move]
    else:
        action = 'move 1'
    # -----------------------------------------------------------------
    #
    print action
    sys.stdout.flush()

Thank you so much, exposing the loop that drives the interaction between controller and robot program is really helpful.

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


text:
Predict the Landslide
Landslides
In this challenge, your job is to predict the extent of damage caused by a massive landslide.
We use the following simplified two-dimensional model for it, parameterized by an initial height h >= 0 and a critical coefficient c > 0.
You start with a cliff of height h, and it is assumed that the terrain is completely flat infinitely to the left and to the right of it.
For h = 6, the situation looks like this:
##########
##########
##########
##########
##########
##########
-----------------------

The - are immovable bedrock, and the # are unstable soil.
If the height difference between two neighboring columns is more than c, a landslide occurs: the top c units of soil from the left column fall down to the next c columns on the right, one to each.
The rightmost non-empty column in the figure is unstable for c = 2, so a landslide is triggered:
#########
#########
##########
##########
##########
############
-----------------------

The column is still unstable, which causes a second landslide:
#########
#########
#########
#########
############
############
-----------------------

Now, the column on its left has become unstable, so a new landslide is triggered there:
########
########
#########
###########
############
############
-----------------------

After this, the cliff is stable again.
The nice thing about this model is that the order in which the landslides are processed does not matter: the end result is the same.
The Task
Your program is given the integer parameters h and c as inputs (the order does not matter, but you must specify it on your answer), and it should output the total number of columns that the landslide affects.
This means the number of columns in the resulting stable cliff whose height is strictly between 0 and h.
In the above example, the correct output is 4.
You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
Test Cases
These are given in the format h c -> output.
0  2  -> 0
2  3  -> 0
6  2  -> 4
6  6  -> 0
10 1  -> 10
15 1  -> 14
15 2  -> 11
15 3  -> 6
40 5  -> 16
80 5  -> 28
80 10 -> 17

CJam, 62 57 bytes
As far as I can see, this is completely different approach to implement the solution from aditsu's answer.
q~:C;:HaH)*H){(:I\_@>2<:-C>{I0a*C~)+C1a*+]z1fb_,}I?}h-H-,

Input goes in the form of h c
Example:
80 5

Output:
28

How it works
The logic is pretty straight forward here with a few tricks used to reduce code size.

Get h + 1 (+ 1 for h = 0 case) length array with each element being h to represent the cliff
Start iterating from the right most index of this array

If the two elements from current index have different more than c

Remove c from the current index element
Add 1 to next c elements of the array from the current index
Make the current index equal to the length of this new array
This makes sure that we stabilize the stones to the right of the current index first

else, reduce the current index

When we hit the left most index, we are making sure that all adjacent indexes have less than or equal to c difference
Remove any 0 or h value from the array and get length.

Code expansion
q~:C;:HaH)*H){(:I\_@>2<:-C>{I0a*C~)+C1a*+]z1fb_,}I?}h-H-,
q~:C;:HaH)*H)
q~:C;:H                  "Read the input, evaluate it, store height in H and coeff. in C";
       aH)*              "Wrap the height number in an array and repeat it H + 1 times";
           H)            "Put H+1 on stack, representing the current index of iteration";
{(:I\_@>2<:-C>{I0a*C~)+C1a*+]z1fb_,}I?}h
(:I\_@>2<:-C>
(:I                      "Decrement the current index and store it in I";
   \_                    "Swap to put array on top and make 1 copy";
     @>2<                "Get the two elements starting from Ith index";
         :-              "Get the difference. The best part of this approach is that";
                         "For the right most index, where there is only element, it";
                         "returns the element itself, which is the expected difference";
           C>            "Check if difference is greater than C";
{I0a*C~)+C1a*+]z1fb_,}   "This block will be executed when the difference is more than C";
 I0a*                    "Get an array of I length and all elements 0";
     C~)+                "Get -C value and append it to the above array";
         C1a*+           "Get C length array of 1s and concat with the above array";
              ]          "Wrap the two arrays, the cliff and the above one in an array";
               z1fb      "Transpose to get number pairs and add those pairs. For example";
                         "If we are at the right most index with H = 80 and C = 5,";
                         "The right section of the cliff looks like:";
                         "[ ... 80 80 80 80 80] and the array created in above step";
                         "looks like [ ... 0 0 0 0 -5 1 1 1 1 1]. After z, we have:";
                         "[ ... [80 0] [80 0] [80 0] [80 0] [80 -5] [1] [1] [1] [1] [1]]";
                         "After 1fb we get [ ... 80 80 80 80 75 1 1 1 1 1]";
                   _,    "Take a copy of the above resultant array and take its length";
I?                       "If difference was not greater than C, put I on stack";
                         "Now we either have the decremented index or new array length";
                         "on stack."
{ ... }h                 "This is a do while loop which makes sure that we iterate to";
                         "the left of the array. This loops runs till the top stack";
                         "element is 0 while not popping the top element";
        -H-,             "After the loop, we have the final cliff array and 0 on stack";
                         "Remove any 0 elements from the array, then remove any H";
                         "elements from the array and then take length to get the";
                         "number of columns which were modified";

Try it online here

Foiled again :p Well done :)

@aditsu again ?

It's not the first time someone beats me at CJam. And not the first time you're doing it either, although not sure if you ever did it in direct competition before.

Heh :) Its all about the algorithm :)

CJam - 70
q~:C;:H0]H*$W%{[__W<\1>]z{~-}%{C>}#):I{I(_2$=C-tC,{I+_2$=)t}/}0?}h-H-,

Try it at http://cjam.aditsu.net/
Explanation:
q~                    read and evaluate the input
:C;                   store the 2nd number in C and remove
:H                    store the first number in H
0]H*                  make an array [H 0] and repeat it H times
$W%                   sort and reverse, obtaining [(H H's) (H 0's)] (initial cliff)
{                     loop...
    [__W<\1>]         make an array with the cliff without the first column
                      and the cliff without the last column
    z{~-}%            subtract the 2 arrays to get the height differences
    {C>}#             find the index of the first height diff. greater than C
    ):I               increment and store in I
    {                 if the value is non-zero (i.e. landslide occurring)
        I(_2$=C-t     subtract C from the corresponding column height
        C,            make an array [0 1 ... C-1]
        {             for each of those numbers
            I+        add I, obtaining a column index where some soil falls
            _2$=)t    increment the column height
        }/            end loop
    }0?               else break outer loop; end if
}h                    ...while the condition is true
-H-                   remove all 0 and H from the final stable cliff
,                     count the remaining columns

The h operator checks the last value on the stack without removing it. If a landslide occurred, the value is the cliff array, which evaluates to true because it's not empty. If not, the last value is 0 (false).
So in case of landslide, the loop continues with the array on the stack, otherwise it ends with a 0 pushed after the array. That 0 is then removed from the array by the next - operator.

Python, 200 190 174
h,c=input();q=[h]*h+[0]*h
try:
 while 1:
    d=[b-a for a,b in zip(q[1:],q)];g=max(d);a=d.index(g)
    for i in range(c):q[a+1+i]+=1/(g>c);q[a]-=1
except:print sum(h>i>0for i in q)

Expanded version:
h, c = input()
# Initialize the heights
q = [h]*h + [0]*h
try:
    while 1:
        # Difference between the heights
        d = [b-a for a,b in zip(q[1:],q)]
        # It may error here, when h == 0, but thats okay
        g = max(d)
        a = d.index(g)
        for i in range(c):
            # This is the termination condition, when g <= c
            q[a+1+i] += 1 / (g>c)
            # Save the newline; also move this line to after termination
            q[a] -= 1
except:
    # Count all heights that have changed
    print sum(h > i > 0 for i in q)

Edit: After some optimizing, I eliminated the awkward loop termination via break (saves 1 byte). Also changed the slide from slice based to loop based.

Nice! You can drop the square brackets inside sum for 2 bytes. Also, it is usually better to define a full program in Python, taking input with h,c=input() and printing the result in the end.

I didn't notice this solution and posted my slightly worse one D: Oh well, competition is nice. Maybe I'll see if I can shave some bytes from mine. By the way, flipping your comparisons in your sum can save you one: sum(h>i>0for i in q).

@undergroundmonorail I tried hard, but I fear your approach is simply superior :(. c=0 saves a byte (I can't comment on your answer).

Python 2 - 194 158 bytes
h,c=input()
b=l=[h]*h+[0]*h
while b:
 b=0
 for i in range(len(l)-1):
  if l[i]-l[i+1]>c:
    for j in range(c):l[i-~j]+=1
    l[i]-=c;b=1
print sum(h>e>0for e in l)

(Note that SE's markdown interpreter converts literal tabs to 4 spaces. Lines 7 and 8 of this program have only a single tab [i.e. one byte] of indentation each.)
Takes input on stdin, h first. For example:
$ ./landslide.py <<< '6, 2'
4

This program has been through a lot of improvements. I had been editing this answer to explain some of the more major edits, but it was getting kind of long. You can check the edit history if you're curious.
Explanation
First, hand c are read from stdin. In Python 2, input() is equivalent to eval(raw_input()), which is why I ask for a comma separating the numbers. input() gives returns a tuple of ints, no conversion required.
Next, a list of integers is made. It is 2*h long. The first half are h and the second half are 0. I don't have any reasoning to show that this is enough to simulate infinite hs to the left and 0s to the right. I just sort of stumbled into it and it works for all the test cases, so if someone can find input it doesn't work for I'll gladly change it. Anyway, this list is called l, but another copy of it is called b.
b's value doesn't actually matter, all that matters is that it's truthy. A non-empty list is truthy and the only way b can be empty here is if h is 0, in which case the correct answer is still printed. In any other case, b has to be truthy to ensure we enter the while b: loop. However, the first thing that happens in the loop is setting b to 0, a falsey value. During each repetition of the loop b must be specifically set back to a truthy one or the loop will end.
The rest of the loop is the actual simulation. It's very naive, essentially just being a code translation of the problem description. If any element of l is more than c greater than the one following it, it is subtracted by c and the next c elements have 1 added to them. (The bitwise magic used here is just a shorter way of writing i+1+j, by the way.) While making these transformations, b is set to 1. The first time no transformations are made, b will stay 0 and the loop terminates.
Any true expression evaluates to True, and when you try to do math on True it evaluates to 1. The same is true of False and 0. The last line of the program uses every element of l as e in the expression h>e>0 and sums the result. This gets the number of columns greater than 0 but lower than the original cliff height, which is the value the question asks for. It's printed and the program exits.

Isn't c-=c equivalent to c=0?

...wow. thanks for watching my back, i should have caught that, haha

i+1+j can be written as i-~j

@Sp3000 I totally forgot about bitwise magic! Thanks :D

Haskell, 163 156 151 Bytes
h#c=sum[1|e<-(until=<<((==)=<<))s$r h++r 0,e`mod`h/=0]where r=replicate$h+1;s w@(x:y:z)|x==0=w|x>c+y=x-c:map(+1)(take c(y:z))++drop c(y:z)|1<2=x:s(y:z)

Usage: h#c, e.g. 6#2 which outputs 4.
How it works: the helper function s does a single landslide. Repeatedly apply s until the output does not change anymore. Count the affected elements.
Found the "apply until output doesn't change" function (i.e. until=<<((==)=<<)) at Stackoverflow.

You can save a couple of bytes by defining f as infix (h#c=...) and moving the where clause to the same line. Also, there are still some parentheses to shed using $, although I'm not sure how many...

@Zgarb: thanks for the hints. Replacing () with $ is trail and error for me.

Mathematica, 108 104 100 97 95
f=Max@#-Min@#&[0Range@#2//.{x___,k:##..&[a_,{#}],a_,y___}:>Sort@{x,##&@@({k}-1),a+#,y}/.{}->0]&

Usage:
f[c, h]

Example:
f[5, 80]

28

C# 303 295
It works!
But it is a ....
int q(int n,int c){var s=Enumerable.Repeat(n,n).ToList();s.Add(0);var d=new HashSet<int>();var g=true;while(g){g=false;for(int i=s.Count-1;i>0;i--){int z=i;int y=i-1;if((s[y]-s[z])>c){s[y]-=c;d.Add(y);g=true;for(int j=1;j<=c;j++){s[y+j]++;d.Add(y+j);if(s[s.Count-1]>0)s.Add(0);}break;}}}return d.Count;}

I must find new language ;)
I'll check this CJam thing ...
Improved:
int q(int n,int c){var s=Enumerable.Repeat(n,n).ToList();s.Add(0);var d=new HashSet<int>();var g=1>0;while(g){g=1<0;for(int i=s.Count-1;i>0;i--){int z=i,y=i-1;if((s[y]-s[z])>c){s[y]-=c;d.Add(y);g=1>0;for(int j=1;j<=c;j++){s[y+j]++;d.Add(y+j);if(s[s.Count-1]>0)s.Add(0);}break;}}}return d.Count;}

You can still optimise this a bit. int z=i;int y=i-1; could be int z=i,y=i-1;. The for loops don't do complicated things with their indices, so e.g. for(int i=s.Count-1;i>0;i--) could be for(int i=s.Count;--i>0;). 1<0 is a shorter way of writing false. I suspect that if(s[s.Count-1]>0)s.Add(0); could lose the condition without affecting correctness, just speed.

@Peter Taylor. Thanks!


text:
Anagramming Stack Exchange question titles into programs
Stack Exchange currently has 134 question and answer sites. This includes all beta sites (such as PPCG) but not Area 51 proposals nor any meta sites, except for the "mother meta".
To answer this question, choose one of those sites and write a program where every line of code is an anagram of the title of a different question on that site. Any questions from that site may be used as long as they have not been deleted, and were asked before this question.
The title of a question includes all characters that appear in the Title textbox when the edit link is clicked below a question, be they whitespace, mathjax formatting, crazy Unicode characters, whatever. (You can use the Stack Exchange API if you want to query a bunch of question titles at a time.)
The program you write must output the string that reliably appears at the top of every Stack Exchange page:
Questions Tags Users Badges Unanswered Ask Question

This exact text, plus an optional trailing newline, is the only thing your program should output. There is no input. The output should go to stdout or, if that's not possible, a similar alternative.
Since doing this with only anagrams of question titles may be kind of tricky, you may optionally add one character of your choice to each line in your program, in any column. Not all lines need to have an extra character and it does not have to be the same character across lines. The character may be anything except for a line terminator. The characters in the line minus this one new character should still be a perfect anagram of a question title.
Scoring
Your score is (number of lines with no added character) + 2 * (number of lines with an added character). The lowest score wins. In case of ties the earlier answer wins.
Details

You must provide links to all the questions you have used the titles from.

You may choose the same Stack Exchange site as someone else though you are encouraged to choose unused sites, just for some variety.

If a question you used gets deleted before the winner is chosen, your submission will be invalid, so it's best to choose well established questions.

If titles are edited on some of your questions then your submission is still valid as long as the edit history shows that your titles were correct when you posted your answer.

Comments in your program are fine.

Editing question titles to suit your needs is very bad form.

Quotes are hard to find ...

Let's do this.

Python 2, score = 2
print '''               &''(()),..===>>?''HHIMMMMPPaaaaabccdddeeeeeeeeeegggimmmmnnnnnoooooprrrrsstwyy''' and 'questions tags users \
badges unanswered ask question'.title() or '             $.?IIWaaabbccccccceeefghhhhhhiijjkklllllmmnnnoooprrrstttttttuxyyz'

I couldn't quite get it in one line, so here's a fairly straightforward solution in two.
I found the questions on Stack Overflow by regexing through the 50,000 longest titles:

How do I get PHP to ignore unescaped ampersands in query string (e.g. ?name=M&M's doesn't become array('name' => 'M', 'M\'s' => ''))
I'm using jquery backstretch and horizontal scrolling. Why does it jump back to the left when I call $.backstretch('next')?

Here's my best attempt at a one-liner for anyone who's going for it (feel free to use it):
print "questions tags users badges unanswered ask question".title() or AHHRUaacccceeeeeeeeeffghikkllmnnnooooooorrrrrrrtwwwy

How to guarantee uniqueness of a referrer who clicks on a link in a remote webpage("Request.UserHostAddress" not working correctly)?

Golfscript, 3 lines with no added characters
"Questions Tags Users Badge"'exception SLSATE[HY000][1049]eymfny incnue while pn chma afte intallin FOSBundl'or
"s Unanswered Ask "'Reoccurring error The current idetity(NT THORITY\NETWORK SERVICE)oe ot have it cc toC:\WINDOWS\Microsoft.NET\Framewor\v2.0.50727\Tempary ASP.NET Files'or
"Question""D he 'S'  SL stand f standard or strctured?"or

I hit StackOverflow, since it probably had the most (useful) posts. A lot of Qs could be found in jQuery and SQL.
Bibliography:

exception "SQLSTATE[HY000] [1049] Base 'symfony' inconnue" while updating schema after installing FOSUserBundle
Reoccurring error "The current identity (NT AUTHORITY\NETWORK SERVICE) does not have write access to 'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files'"
Does the 'S' in SQL stand for "standard" or "structured"?

Uses two strings each line, and takes the first one with or. I don't know any proper Golfscript, but I tested it here.
It's possible to get the necessary quotes in two lines, but you'll need a language that lets you dump chars.

Removed one line (or use :o\"s Unanswered Ask "o).

Pyth, 2, 1 line with 1 extra character.
r"questions tags users badges unanswered ask question"tyhgkk)            (.?AHHRUaacccceeeeeeeeeeffiiilllmnnnnooooooooprrrrrrrrtttwww

Uses grc's How to guarantee uniqueness of a referrer who clicks on a link in a remote webpage("Request.UserHostAddress" not working correctly)?, which unfortunately requires an extra s to work.