text:
Un-Merge a List
Introduction
Most of you are familiar with the merge sort algorithm for sorting a list of numbers.
As part of the algorithm, one writes a helper function called merge that combines two sorted lists into one sorted list.
In Python-like pseudocode, the function usually looks something like this:
function merge(A, B):
  C = []
  while A is not empty or B is not empty:
    if A is empty:
      C.append(B.pop())
    else if B is empty or A[0] ≤ B[0]:
      C.append(A.pop())
    else:
      C.append(B.pop())
  return C

The idea is to keep popping the smaller of the first elements of A and B until both lists are empty, and collect the results into C.
If A and B are both sorted, then so is C.
Conversely, if C is a sorted list, and we split it into any two subsequences A and B, then A and B are also sorted and merge(A, B) == C.
Interestingly, this does not necessarily hold if C is not sorted, which brings us to this challenge.
Input
Your input is a permutation of the first 2*n nonnegative integers [0, 1, 2, ..., 2*n-1] for some n > 0, given as a list C.
Output
Your output shall be a truthy value if there exist two lists A and B of length n such that C == merge(A, B), and a falsy value otherwise.
Since the input contains no duplicates, you don't have to worry about how ties are broken in the merge function.
Rules and Bonuses
You can write either a function or a full program.
The lowest byte count wins, and standard loopholes are disallowed.
Note that you are not required to compute the lists A and B in the "yes" instances.
However, if you actually output the lists, you receive a bonus of -20%.
To claim this bonus, you must output only one pair of lists, not all possibilities.
To make this bonus easier to claim in strongly typed languages, it is allowed to output a pair of empty lists in the "no" instances.
Brute forcing is not forbidden, but there is a bonus of -10% for computing all of the last four test cases in under 1 second total.
Test Cases
Only one possible output is given in the "yes" instances.
[1,0] -> False
[0,1] -> [0] [1]
[3,2,1,0] -> False
[0,3,2,1] -> False
[0,1,2,3] -> [0,1] [2,3]
[1,4,0,3,2,5] -> False
[4,2,0,5,1,3] -> [4,2,0] [5,1,3]
[3,4,1,2,5,0] -> [4,1,2] [3,5,0]
[6,2,9,3,0,7,5,1,8,4] -> False
[5,7,2,9,6,8,3,4,1,0] -> False
[5,6,0,7,8,1,3,9,2,4] -> [6,0,8,1,3] [5,7,9,2,4]
[5,3,7,0,2,9,1,6,4,8] -> [5,3,7,0,2] [9,1,6,4,8]
[0,6,4,8,7,5,2,3,9,1] -> [8,7,5,2,3] [0,6,4,9,1]
[9,6,10,15,12,13,1,3,8,19,0,16,5,7,17,2,4,11,18,14] -> False
[14,8,12,0,5,4,16,9,17,7,11,1,2,10,18,19,13,15,6,3] -> False
[4,11,5,6,9,14,17,1,3,15,10,12,7,8,0,18,19,2,13,16] -> [4,17,1,3,15,10,12,7,8,0] [11,5,6,9,14,18,19,2,13,16]
[9,4,2,14,7,13,1,16,12,11,3,8,6,15,17,19,0,10,18,5] -> [9,4,2,16,12,11,3,8,6,15] [14,7,13,1,17,19,0,10,18,5]

Pyth, 39 * 0.9 * 0.8 = 28.08
#aY->QxQeS-QsY&YsY)KfqylTlQmsdty_Y%tlKK

This program clams all two bonuses. It prints a pair of lists, if un-merging is possible, else an empty list, which is a falsy value in Pyth (and Python).
Input:  [5,3,7,0,2,9,1,6,4,8]
Output: ([9, 1, 6, 4, 8], [5, 3, 7, 0, 2])
Input:  [5,7,2,9,6,8,3,4,1,0]
Output: [] (falsy value)

You can test it online, but it may be a bit slower than the offline version. The offline version solves each of the test cases in <0.15 seconds on my laptop.
Probably (one of) the first time, a Pyth solution uses actively Exceptions (it saved at least 1 char). It uses the same idea as Peter Taylor's solution.
                         preinitialisations: Q = input(), Y = []
#                 )     while 1: (infinite loop)
        eS-QsY             finds the biggest, not previous used, number
      xQ                   finds the index
    >Q                     all elements from ... to end
   -          &YsY         but remove all used elements
 aY                        append the resulting list to Y

When all numbers are used, finding the biggest number fails,
throws an exception and the while loop ends.
This converts [5,3,7,0,2,9,1,6,4,8] to [[9, 1, 6, 4, 8], [7, 0, 2], [5, 3]]

        msdty_Y  combine the lists each for every possible subset of Y (except the empty subset)
 fqylTlQ         and filter them for lists T with 2*len(T) == len(Q)
K                and store them in K

%tlKK        print K[::len(K)-1] (prints first and last if K, else empty list)

Pyth, 30 * 0.9 = 27.0
I haven't really tried solving it without printing the resulting lists. But here's a quick solution based on the code above.
#aY->QxQeS-QsY&YsY)fqylsTlQtyY

I basically only removed the print statement. The output is quite ugly though.
Input:  [0,1,2,3]
Output: [[[3], [2]], [[3], [1]], [[2], [1]], [[3], [0]], [[2], [0]], [[1], [0]]] (truthy value)
Input:  [5,7,2,9,6,8,3,4,1,0]
Output: [] (falsy value)

Try it online.

You may find that rather than printing (K[0], Q-K[0]) you can print (K[0], K[-1]). I don't know whether that would give a saving, though.

@PeterTaylor thanks, saved 2 chars.

@PeterTaylor and even 2 more chars, if I print K[::len(K)-1].

GolfScript (35 * 0.9 = 31.5)
{.$-1>/~,)\.}do;]1,\{{1$+}+%}/)2/&,

The online demo is quite slow: on my computer, it runs all of the tests in under 0.04 seconds, so I claim the 10% reduction.
Explanation

 The suffix of C which starts with the largest number in C must come from the same list. Then this reasoning can be applied to (C - suffix), so that the problem reduces to subset sum.

APL, 62 50 44 * 90% = 39.6
{(l÷2)⌷↑(⊢∨⌽)/(2-/(1,⍨⍵≥⌈\⍵)/⍳l+1),⊂l=⍳l←⍴⍵}

Try it here.

JavaScript (Node.js), 103 bytes * 0.9 * 0.8
f=(x,u,a=[],b=[],y=[...x],c=y.pop())=>b[0]<a[0]?0:1/c?f(y,~-u,[c,...a],b)||f(y,~u,[c,...b],a):u?0:[a,b]

Try it online!

JavaScript (Node.js), 105 bytes * 0.9 * 0.8
f=(x,u=0,a=[],b=[],y=[...x],c=y.pop())=>b[0]<a[0]?0:1/c?f(y,u-1,[c,...a],b)||f(y,~u,[c,...b],a):u?0:[a,b]

Try it online!
JavaScript (Node.js), 115 bytes * 0.9 * 0.8
f=(x,u=0,a=[],b=[],y=[...x],c=y.pop())=>1/c?!(b[0]<c)&&f(y,u-1,[c,...a],b)||!(a[0]<c)&&f(y,~u,[c,...b],a):u?0:[a,b]

Try it online!

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


text:
Is there a shorter way to assign one of two variables in Python?
This is a tips question for golfing in python.
In multiple golfs I've done in Python, a fixed value is assigned to one of two variables chosen by a Boolean. The chosen variable is overwritten by the given value, and the other is unchanged.
17 chars:
if b:y=z
else:x=z

Assigning a conditional value is easy, but assigning to a conditional variable seems clunky. I'm wondering if there's a shorter way I'm missing.
This would be easy if x,y were instead a list L, but assume the context requires referring to the variables enough that writing L[0] and L[1] is prohibitive. Converting takes too long:
20 chars:
L=[x,y];L[b]=z;x,y=L

The fastest way I know is with a Python 2 exec, which is bizarre:
16 chars, Python 2:
exec"xy"[b]+"=z"

Tuple-choosing seems to be longer:
18, 19, 18, 18 chars:
x,y=b*(x,z)or(z,y)
x,y=[z,x,y,z][b::2]
y,x=[y,z,x][b:b+2]
y,x,*_=[y,z,x][b:]   # Python 3

Is there some shorter method or character-saving optimization? You can assume b is 0 or 1, not just Falsey or Truthy, and also make assumptions about the data types and values if it helps.

I don't know of anything better.  If you need to do this a lot, you can do x,y=C(x,y,z,b) (14 chars) and push any of these implementations into the body of C.

Why isn't this in Stack Overflow?

@BobTheAwesome I'm not asking for good ways to do this, just short ones.

12 chars/assignment + 9 chars of overhead
V=vars()     # do once at the start of the program
V["xy"[b]]=z

Note that this only works at global scope, it does not work inside a function.

Wow, I did not know about this. And it's cool that V updates automatically, with no need to call the function again. So this breaks even with exec in two uses. Also, just doing vars()["xy"[b]]=z is 17 chars, which is the best we have so far for Python 3, without the control flow of if/else which can cause problems.

It's actually 9 chars of overhead because a newline or semicolon must follow the assignment.

If you only need to do it once, can you do: vars()["xy"[b]]=z?

@acbabis: yes, as xnor pointed out.

14 chars, Python 2
exec"xy=z"[b:]

The two variables are y and xy. If b=0, this sets xy=z. If b=1, this sets y=z. This will be worth it if xy is used no more than once elsewhere in the code.

Very clever! I suspect you usually need to use xy at least twice though, for its initial assignment, and to read it out afterwards.

15 chars, Python 2
exec`b`[0]+"=z"

Requires that the variables be called F and T rather than x and y, and that b is False or b is True, rather than being the equal numbers 0 or 1.
This saves a char from "xy"[b] by instead taking the first letter of the string representation of b, which is T or F.

Note that the variables can also be called a and r, l and u or s and e, with appropriate indices.

source: Stack Exchange

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

sort: votes


text:
Area of a Self-Intersecting Polygon
Consider a potentially self-intersecting polygon, defined by a list of vertices in 2D space. E.g.
{{0, 0}, {5, 0}, {5, 4}, {1, 4}, {1, 2}, {3, 2}, {3, 3}, {2, 3}, {2, 1}, {4, 1}, {4, 5}, {0, 5}}

There are several ways to define the area of such a polygon, but the most interesting one is the even-odd rule. Taking any point in the plane, draw a line from the point out to infinity (in any direction). If that line crosses the polygon an odd number of times, the point is part of the polygon's area, if it crosses the polygon an even number of times, the point is not part of the polygon. For the above example polygon, here are both its outline as well as its even-odd area:

The polygon will not in general be orthogonal. I've only chosen such a simple example to make it easier to count the area.
The area of this example is 17 (not 24 or 33 as other definitions or area might yield).
Note that under this definition the area of the polygon is independent of its winding order.
The Challenge
Given a list of vertices with integer coordinates defining a polygon, determine its area under the even-odd rule.
You may write a function or program, taking input via STDIN or closest alternative, command-line argument or function argument and either return the result or print it to STDOUT or closest alternative.
You may take input in any convenient list or string format, as long as it's not preprocessed.
The result should either be floating point number, accurate to 6 significant (decimal) digits, or a rational result whose floating point representation is accurate to 6 significant digits. (If you produce rational results they are likely going to be exact, but I can't require this, as I don't have exact results for reference.)
You must be able to solve each of the test cases below within 10 seconds on a reasonable desktop machine. (There is some leeway in this rule, so use your best judgement. If it takes 20 seconds on my laptop I'll give you the benefit of the doubt, if it takes a minute, I won't.) I think this limit should be very generous but it is supposed to rule out approaches where you just discretise the polygon on a sufficiently fine grid and count, or use probabilistic approaches like Monte Carlo. Be a good sportsman and don't try to optimise of these approaches such that you can meet the time limit anyway. ;)
You must not use any existing functions related directly to polygons.
This is code golf, so the shortest submission (in bytes) wins.
Assumptions

All coordinates are integers in the range 0 ≤ x ≤ 100, 0 ≤ y ≤ 100.
There will be at least 3 and at most 50 vertices.
There won't be any repeated vertices. Neither will any vertices lie on another edge. (There may be collinear points in the list, though.)

Test Cases
{{0, 0}, {5, 0}, {5, 4}, {1, 4}, {1, 2}, {3, 2}, {3, 3}, {2, 3}, {2, 1}, {4, 1}, {4, 5}, {0, 5}}
17.0000

{{22, 87}, {6, 3}, {98, 77}, {20, 56}, {96, 52}, {79, 34}, {46, 78}, {52, 73}, {81, 85}, {90, 43}}
2788.39

{{90, 43}, {81, 85}, {52, 73}, {46, 78}, {79, 34}, {96, 52}, {20, 56}, {98, 77}, {6, 3}, {22, 87}}
2788.39

{{70, 33}, {53, 89}, {76, 35}, {14, 56}, {14, 47}, {59, 49}, {12, 32}, {22, 66}, {85, 2}, {2, 81},
 {61, 39}, {1, 49}, {91, 62}, {67, 7}, {19, 55}, {47, 44}, {8, 24}, {46, 18}, {63, 64}, {23, 30}}
2037.98

{{42, 65}, {14, 59}, {97, 10}, {13, 1}, {2, 8}, {88, 80}, {24, 36}, {95, 94}, {18, 9}, {66, 64},
 {91, 5}, {99, 25}, {6, 66}, {48, 55}, {83, 54}, {15, 65}, {10, 60}, {35, 86}, {44, 19}, {48, 43},
 {47, 86}, {29, 5}, {15, 45}, {75, 41}, {9, 9}, {23, 100}, {22, 82}, {34, 21}, {7, 34}, {54, 83}}
3382.46

{{68, 35}, {43, 63}, {66, 98}, {60, 56}, {57, 44}, {90, 52}, {36, 26}, {23, 55}, {66, 1}, {25, 6},
 {84, 65}, {38, 16}, {47, 31}, {44, 90}, {2, 30}, {87, 40}, {19, 51}, {75, 5}, {31, 94}, {85, 56},
 {95, 81}, {79, 80}, {82, 45}, {95, 10}, {27, 15}, {18, 70}, {24, 6}, {12, 73}, {10, 31}, {4, 29},
 {79, 93}, {45, 85}, {12, 10}, {89, 70}, {46, 5}, {56, 67}, {58, 59}, {92, 19}, {83, 49}, {22,77}}
3337.62

{{15, 22}, {71, 65}, {12, 35}, {30, 92}, {12, 92}, {97, 31}, {4, 32}, {39, 43}, {11, 40},
 {20, 15}, {71, 100}, {84, 76}, {51, 98}, {35, 94}, {46, 54}, {89, 49}, {28, 35}, {65, 42},
 {31, 41}, {48, 34}, {57, 46}, {14, 20}, {45, 28}, {82, 65}, {88, 78}, {55, 30}, {30, 27},
 {26, 47}, {51, 93}, {9, 95}, {56, 82}, {86, 56}, {46, 28}, {62, 70}, {98, 10}, {3, 39},
 {11, 34}, {17, 64}, {36, 42}, {52, 100}, {38, 11}, {83, 14}, {5, 17}, {72, 70}, {3, 97},
 {8, 94}, {64, 60}, {47, 25}, {99, 26}, {99, 69}}
3514.46

Can we reformat the input to suit our needs, by replacing the delimiters and such?

Specifically, I would like to replace the delimiters in a way that makes the list a valid PostScript User Path, so I can parse the whole thing with one upath operator. (It is actually an extremely simple 1:1 conversion between the seperators. }, { just becomes lineto, and the comma between the x and y is removed, and the opening and closing braces are replaced with a static header and footer...)

@AJMansfield I usually don't mind using convenient, native list representations, but using upath and lineto sounds like you're actually preprocessing the input. I.e. you're not taking a list of coordinates but an actual polygon.

Can we assume that the polygons are generic enough that there are no triple (or higher) intersections?

Do you have a reference about the consistency of the even-odd rule? Drawing the line in different directions will result in different number of crossing times.

@MattNoonan Oh, that's a good point. Yes you may assume that.

@Ray While the direction may affect the number of crossings, it will only ever increase or decrease by 2, preserving the parity. I'll try to find a reference. For a start, SVG uses the same definition.

By the way, the even-odd rule works because of the following: starting outside the polygon and moving from left to right, top to bottom, perform rasterization as follows: every time you cross a boundary line of the polygon switch from "drawing" to "not drawing" (or vice versa) until having exited the polygon.  Any given horizontal print will cross the boundary line exactly an even number of times (the shape is closed, so this statement is mathematically true). Ergo, any odd number of crossings is inside the polygon.

I don't want to bump this unnecessarily, but technically you are drawing a ray, since lines are bi-infinite but rays are semi-infinite.

Mathematica 12.0 has a new built-in function for this: CrossingPolygon.

@alephalpha The Mathematica input Area[CrossingPolygon[{{...},{...}}]] gives Area=24 for the first test case. All other results are as specified in the test case description.

@HugoPfoertner That's interesting. I don't know if this is a bug of Mathematica.

@alephalpha That may be. The graphics Mma creates with Graphics [CrossingPolygon [..]] for the first polygon is exactly the same as the one shown in the challenge description and has area 17 of the black part. I don't know the Mathematica world well enough to know how to report a suspected bug.

Mathematica, 247 225 222
p=Partition[#,2,1,1]&;{a_,b_}~r~{c_,d_}=Det/@{{a-c,c-d},{a,c}-b}/Det@{a-b,c-d};f=Abs@Tr@MapIndexed[Det@#(-1)^Tr@#2&,p[Join@@MapThread[{1-#,#}&/@#.#2&,{Sort/@Cases[{s_,t_}/;0<=s<=1&&0<=t<=1:>s]/@Outer[r,#,#,1],#}]&@p@#]]/2&

First add the points of intersection to the polygon, then reverse some of the edges, then its area can be calculated just like a simple polygon.

Example:
In[2]:= f[{{15, 22}, {71, 65}, {12, 35}, {30, 92}, {12, 92}, {97, 31}, {4, 32}, {39, 43}, {11, 40},
 {20, 15}, {71, 100}, {84, 76}, {51, 98}, {35, 94}, {46, 54}, {89, 49}, {28, 35}, {65, 42},
 {31, 41}, {48, 34}, {57, 46}, {14, 20}, {45, 28}, {82, 65}, {88, 78}, {55, 30}, {30, 27},
 {26, 47}, {51, 93}, {9, 95}, {56, 82}, {86, 56}, {46, 28}, {62, 70}, {98, 10}, {3, 39},
 {11, 34}, {17, 64}, {36, 42}, {52, 100}, {38, 11}, {83, 14}, {5, 17}, {72, 70}, {3, 97},
 {8, 94}, {64, 60}, {47, 25}, {99, 26}, {99, 69}}]

Out[2]= 3387239559852305316061173112486233884246606945138074528363622677708164\
 6419838924305735780894917246019722157041758816629529815853144003636562\
 9161985438389053702901286180223793349646170997160308182712593965484705\
 3835036745220226127640955614326918918917441670126958689133216326862597\
 0109115619/\
 9638019709367685232385259132839493819254557312303005906194701440047547\
 1858644412915045826470099500628074171987058850811809594585138874868123\
 9385516082170539979030155851141050766098510400285425157652696115518756\
 3100504682294718279622934291498595327654955812053471272558217892957057\
 556160

In[3]:= N[%] (*The numerical value of the last output*)

Out[3]= 3514.46

Unfortunately I'm not sure this logic will work for all situations.  Can you try {1,2},{4,4},{4,2},{2,4},{2,1},{5,3}?  You should come out with 3.433333333333309.  I looked at using a similar logic.

@MickyT Yes, it works. It returned 103/30, and the numerical value is 3.43333.

Sorry about that.  Good solution

Python 2, 323 319 bytes
exec u"def I(s,a,b=1j):c,d=s;d-=c;c-=a;e=(d*bX;return e*(0<=(b*cX*e<=e*e)and[a+(d*cX*b/e]or[]\nE=lambda p:zip(p,p[1:]+p);S=sorted;P=E(input());print sum((t-b)*(r-l)/2Fl,r@E(S(i.realFa,b@PFe@PFi@I(e,a,b-a)))[:-1]Fb,t@E(S(((i+j)XFe@PFi@I(e,l)Fj@I(e,r)))[::2])".translate({70:u" for ",64:u" in ",88:u".conjugate()).imag"})

Takes a list of vertices through STDIN as complex numbers, in the following form
[  X + Yj,  X + Yj,  ...  ]

, and writes the result to STDOUT.
Same code after string replacement and some spacing:
def I(s, a, b = 1j):
    c, d = s; d -= c; c -= a;
    e = (d*b.conjugate()).imag;
    return e * (0 <= (b*c.conjugate()).imag * e <= e*e) and \
           [a + (d*c.conjugate()).imag * b/e] or []

E = lambda p: zip(p, p[1:] + p);
S = sorted;

P = E(input());

print sum(
    (t - b) * (r - l) / 2

    for l, r in E(S(
        i.real for a, b in P for e in P for i in I(e, a, b - a)
    ))[:-1]

    for b, t in E(S(
        ((i + j).conjugate()).imag for e in P for i in I(e, l) for j in I(e, r)
    ))[::2]
)

Explanation
For each point of intersection of two sides of the input polygon (including the vertices), pass a vertical line though that point.

(In fact, due to golfing, the program passes a few more lines; it doesn't really matter, as long as we pass at least these lines.)
The body of the polygon between any two consecutive lines is comprised of vertical trapezoids (and triangles, and line segments, as special cases of those).
It has to be the case, since if any of these shapes had an additional vertex between the two bases, there would be another vertical line through that point, between the two lines in question.
The sum of the areas of all such trapezoids is the area of the polygon.
Here's how we find these trapezoids:
For each pair of consecutive vertical lines, we find the segments of each side of the polygon that (properly) lie between these two lines (which might not exist for some of the sides).
In the above illustration, these are the six red segments, when considering the two red vertical lines.
Note that these segments don't properly intersect each other (i.e., they may only meet at their end points, completely coincide or not intersect at all, since, once again, if they properly intersected there would be another vertical line in between;) and so it makes sense to talk about ordering them top-to-bottom, which we do.
According to the even-odd rule, once we cross the first segment, we're inside the polygon; once we cross the second one, we're out; the third one, in again; the fourth, out; and so on...
In other words, if we group the segments into consecutive pairs, each pair is the legs of one of the trapezoids.
Overall, this is an O(n3 log n) algorithm.

This is brilliant! I knew I could count on you for this one. ;) (You might want to answer this question over on Stack Overflow.)

@MartinBüttner Keep 'em coming :)

Great work and a great explanation

WHile I can imagine that there might be some pathological cases that this technique would fail on (most of them calculus-related, and obviously with more than 50 points), this is some pretty neat code. I might just steal the technique for my answer.

This is an impressive answer. Did you develop the algorithm yourself or is there existing work on this problem? If there is existing work, I would appreciate a pointer to where I can find it. I had no idea on how to tackle this.

Not relevant to the golfing part but if you keep track of the ordering of the line-segments you don't need to sort at every step. Instead do one step of bubble sorting and insert/remove newly appearing/disappearing lines for a total cost of O(n^3). (n^2 * n for the bubble sorts and n * n for adding/removing lines)

@CarpetPython I developed it myself, but I'd be very surprised if it hasn't been done before.

@MartinBüttner Thanks for the bounty :)

Haskell, 549
It doesn't look like I can golf this one down far enough, but the concept was different than the other two answers so I figured I'd share it anyway. It performs O(N^2) rational operations to compute the area.
import Data.List
_%0=2;x%y=x/y
h=sort
z f w@(x:y)=zipWith f(y++[x])w
a=(%2).sum.z(#);(a,b)#(c,d)=b*c-a*d
(r,p)?(s,q)=[(0,p)|p==q]++[(t,v t p r)|u t,u$f r]where f x=(d q p#x)%(r#s);t=f s;u x=x^2<x
v t(x,y)(a,b)=(x+t*a,y+t*b);d=v(-1)
s x=zip(z d x)x
i y=h.(=<<y).(?)=<<y
[]!x=[x];x!_=x
e n(a@(x,p):y)|x>0=(n!y,a):(e(n!y)$tail$dropWhile((/=p).snd)y)|0<1=(n,a):e n y
c[p]k=w x[]where((_,q):x)=e[]p;w((n,y):z)b|q==y=(k,map snd(q:b)):c n(-k)|0<1=w z(y:b);c[]_=[]
b(s,p)=s*a p
u(_,x)(_,y)=h x==h y
f p=abs$sum$map b$nubBy u$take(length p^2)$c[cycle$i$s p]1

Example:
λ> f test''
33872395598523053160611731124862338842466069451380745283636226777081646419838924305735780894917246019722157041758816629529815853144003636562916198543838905370290128618022379334964617099716030818271259396548470538350367452202261276409556143269189189174416701269586891332163268625970109115619 % 9638019709367685232385259132839493819254557312303005906194701440047547185864441291504582647009950062807417198705885081180959458513887486812393855160821705399790301558511410507660985104002854251576526961155187563100504682294718279622934291498595327654955812053471272558217892957057556160
λ> fromRational (f test'')
3514.4559380388832

The idea is to rewire the polygon at every crossing, resulting in a union of polygons with no intersecting edges.  We can then compute the (signed) area of each of the polygons using Gauss' shoelace formula (http://en.wikipedia.org/wiki/Shoelace_formula).  The even-odd rule demands that when a crossing is converted, the area of the new polygon is counted negatively relative to the old polygon.
For example, consider the polygon in the original question. The crossing in the upper-left is converted to two paths which only meet at a point; the two paths are both oriented clockwise, so the areas of each would be positive unless we declared that the inner path is weighted by -1 relative to the outer path.  This is equivalent to alphaalpha's path reversal.

As another example, consider the polygon from MickyT's comment:

Here, some of the polygons are oriented clockwise and some counterclockwise. The sign-flip-on-crossing rule ensures that the clockwise-oriented regions pick up an extra factor of -1, causing them to contribute a positive amount to the area.
Here's how the program works:
import Data.List  -- for sort and nubBy

-- Rational division, with the unusual convention that x/0 = 2
_%0=2;x%y=x/y

-- Golf
h=sort

-- Define a "cyclic zipWith" operation. Given a list [a,b,c,...z] and a binary
-- operation (@), z (@) [a,b,c,..z] computes the list [b@a, c@b, ..., z@y, a@z]
z f w@(x:y)=zipWith f(y++[x])w

-- The shoelace formula for the signed area of a polygon
a=(%2).sum.z(#)

-- The "cross-product" of two 2d vectors, resulting in a scalar.
(a,b)#(c,d)=b*c-a*d

-- Determine if the line segment from p to p+r intersects the segment from
-- q to q+s.  Evaluates to the singleton list [(t,x)] where p + tr = x is the
-- point of intersection, or the empty list if there is no intersection.
(r,p)?(s,q)=[(0,p)|p==q]++[(t,v t p r)|u t,u$f r]where f x=(d q p#x)%(r#s);t=f s;u x=x^2<x

-- v computes an affine combination of two vectors; d computes the difference
-- of two vectors.
v t(x,y)(a,b)=(x+t*a,y+t*b);d=v(-1)

-- If x is a list of points describing a polygon, s x will be the list of
-- (displacement, point) pairs describing the edges.
s x=zip(z d x)x

-- Given a list of (displacement, point) pairs describing a polygon's edges,
-- create a new polygon which also has a vertex at every point of intersection.
-- Mercilessly golfed.
i y=h.(=<<y).(?)=<<y

-- Extract a simple polygon; when an intersection point is reached, fast-forward
-- through the polygon until we return to the same point, then continue.  This
-- implements the edge rewiring operation. Also keep track of the first
-- intersection point we saw, so that we can process that polygon next and with
-- opposite sign.
[]!x=[x];x!_=x
e n(a@(x,p):y)|x>0=(n!y,a):(e(n!y)$tail$dropWhile((/=p).snd)y)|0<1=(n,a):e n y

-- Traverse the polygon from some arbitrary starting point, using e to extract
-- simple polygons marked with +/-1 weights.
c[p]k=w x[]where((_,q):x)=e[]p;w((n,y):z)b|q==y=(k,map snd(q:b)):c n(-k)|0<1=w z(y:b);c[]_=[]

-- If the original polygon had N vertices, there could (very conservatively)
-- be up to N^2 points of intersection.  So extract N^2 polygons using c,
-- throwing away duplicates, and add up the weighted areas of each polygon.
b(s,p)=s*a p
u(_,x)(_,y)=h x==h y
f p=abs$sum$map b$nubBy u$take(length p^2)$c[cycle$i$s p]1

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


text:
Randomised list, formatted nicely
Challenge
Task
Given a number N, output 2 NxN squares; each line of each square is a random permutation of [0, N); the squares are separated by a newline
Rules

Produce a randomised list of length N, separated by space
Repeat this N*2 times
Separate each output with a newline, with 2 newlines at the midpoint
The value of n must be "obvious", you can get it via stdin; argument; whatever, but there must be a distinct value somewhere, so the value of n can't just be scattered across your program.

Example
Given n = 4, the output could be:
1 2 0 3
2 3 1 0
2 0 3 1
2 0 3 1

0 3 2 1
3 1 0 2
0 1 3 2
0 2 1 3

Lowest number of bytes wins

Do columns need to be aligned? - it matters for n>9

nah, i wouldn't worry

Is it not a code-golf question (I mean code-golf tagged) ?

Does the function need to be able to output all random permutation?

I should think so, otherwise you could just hardcode it to output "1 2 3 4" and call it random ( http://xkcd.com/221/ )

J, 9 7 bytes
Thanks to @randomra for shaving off two characters:
?~2&,]

Previously I had:
?~($~2&,)

These are functions, you can apply them to an argument directly or store them in a variable and then use them:
   (?~2&,$]) 5
1 0 4 2 3
2 4 0 3 1
2 3 1 0 4
2 3 0 1 4
3 0 1 4 2

1 4 0 2 3
2 1 4 3 0
2 3 1 0 4
2 3 1 4 0
0 1 2 3 4

   f=.?~2&,$]
   f 5
4 2 3 0 1
3 4 1 0 2
3 4 0 2 1
1 2 4 3 0
2 0 4 1 3

2 1 3 0 4
1 3 4 2 0
2 4 1 3 0
3 2 1 0 4
3 0 4 2 1

?~2&,$] saves 2 bytes.

Pyth, 13
V2VQjdoOQUQ)k

Pretty simple program, I believe it follows the spec.
Try it online here
Explanation:
                   : Q = eval(input)
V2                 : Do the next part twice
  VQ       )       : Do the stuff before the ) Q times
    jd             : Join the resulting list on spaces
      oOQUQ        : order range(Q) by random_int( from 0 to Q )
            k      : print nothing (pyth auto-pads each print with a newline)

R, 73 71 66 62 54
I feel there should be a better way, but at the moment
n=5;for(i in 1:(n*2))cat(sample(n)-1,rep('\n',1+!i-n))

Edit: Replace rank(runif(1:n))-1 with sample(1:n)-1. Used rep instead of if. Thanks to Alex A for a few more.
Test run
> n=5;for(i in 1:(n*2))cat(sample(n)-1,rep('\n',1+!i-n))
0 3 1 2 4
0 1 4 2 3
2 3 4 0 1
4 1 0 2 3
1 0 3 4 2

4 3 1 0 2
3 0 1 2 4
4 2 3 1 0
4 2 1 0 3
3 1 0 2 4

You can save a byte by doing n=scan();for(i in 1:(2*n)) rather than assigning n inside for().

You can save another 2 bytes by doing sample(n) rather than sample(1:n) since they're equivalent.

And what is 1+!i-n doing?

@AlexA. It was the shortest way I could think of doing 1 except when i == n, so it is equivalent to 1+(i==n) .  I also got rid of the vector constructor in the cat

Ah, okay. Clever. Right now you're hard-coding n but doesn't it still need to come from input? Or does simply defining it like that constitute "obvious" per the OP's rules? (It is obvious...)

@AlexA.  I wondered about that, but I noticed a number of others were doing it, including the OP

CJam, 22 bytes
l~{_{_,mrS*N@}*N\}2*;;

Input via STDIN. I feel like there must be a much way to do this.
Test it here.

Bash+coreutils, 61
Input as a command-line arg.
seq -f"((%g))&&echo \`seq 0 $[$1-1]|shuf\`||echo" -$1 $1|bash

CJam, 20 19 bytes
ri_a*0+2*{,mrS*}%N*

Try it here (for Firefox).
Other solutions:
{T,mrS*N}_ri:T*N](T*
"T,mrS*N"ri:T*:F~NF~
LN]"T,mrS*N"ri:T*f{~}

Is a trailing newline ok? You can put N in the block

@aditsu Then there will be two trailing newlines.

Oh, right.. it's not obvious in the online interpreter.

Java, 190 187 bytes
void f(int n){int k=0,i,t,x,o[]=new int[n];for(;k<n;o[k]=k++);for(k=0;k++<n*2;)for(i=n;i>0;t=o[x*=Math.random()],o[x]=o[i],o[i]=t,System.out.print(o[i]+(i>0?" ":k==n?"\n\n":"\n")))x=i--;}

Clunky, but it does the job (that's Java's motto, right?). Pretty simplistic: it fills an array, then repeatedly uses my earlier Fisher-Yates to shuffle and print. I tried using Collections.shuffle() instead, but it was a touch longer once you add in the import.
Ah well, such is life.
With line breaks:
void f(int n){
    int k=0,i,t,x,o[]=new int[n];
    for(;k<n;o[k]=k++);
    for(k=0;k++<n*2;)
        for(i=n;
            i>0;
            t=o[x*=Math.random()],
            o[x]=o[i],
            o[i]=t,
            System.out.print(o[i]+(i>0?" ":k==n?"\n\n":"\n"))
        )
            x=i--;
}

You can save a byte by removing the +" ", and using i>0?" ":k==n?" \n\n":" \n" instead.

@Ypnypn Saved three with it, since I don't need trailing spaces with newlines. Thanks :)

Clip, 29
[zjm[ Jm[ jkwRRzwS}Rz}R2:2N]n

Takes input from STDIN.
[z                         ]n  .- z is the numeric value of the input -.
  j                     :2N    .- join with two newlines              -.
   m[                }R2       .- do twice                            -.
      J                        .- join with a newline                 -.
       m[         }Rz          .- do z times                          -.
          j     wS             .- join with spaces                    -.
           kw                  .- wrap each number                    -.
             R                 .- shuffle                             -.
              Rz               .- list of the first z numbers         -.

Example run:
> java -jar clip4.jar random.clip
4
2 1 0 3
3 1 2 0
1 0 2 3
3 1 0 2

3 0 1 2
0 1 2 3
3 2 0 1
0 1 3 2

Python 3, 90 bytes
from random import*
def f(n):S="*L,=range(n);shuffle(L);print(*L);"*n;exec(S+"print();"+S)

I'm sure there's a better method for handling the newline break in between, but I'm having trouble coming up with a way.

Python - 139 138 bytes
import random as r
n=4
s=range
t=s(0,4)
print('\n\n'.join('\n'.join(' '.join('%d'%i for i in r.sample(t,n)) for j in t) for k in s(0,2)))

EDIT: Knocked off a byte

import static java.lang.System.out;public class A{public static void main(String[]a){int n=Integer.decode(a[0]);for(int x=0;x<2;x++){for(int i=0;i<n;i++){java.util.stream.IntStream.range(0,n).parallel().forEach(k->out.print(k+" "));out.println();}out.println();}}}

As short as I could manage in Java - 265 bytes.
It takes an ordered stream of n integers and concurrently prints them separated by a space, so the output order is non-deterministic and it does this per line.
EDIT:
If done as only a function:
void g(int n){for(int x=0,i=0;x<2;x++){for(;i<n;i++){java.util.stream.IntStream.range(0,10).parallel().forEach(k->out.print(k+" "));System.out.println();}System.out.println();}}}}}

This is 179 bytes; the ordering may not seem very random - but as far as I'm aware it is quite non-deterministic.

You could use a function instead.

This has got to be the worst RNG ever. I like it for sheer cheek, but the "randomness" is terrible :)

Plus, you could declare x and i together with n and scrape off a few characters.

I agree that it's non-deterministic, but our standard definition of "random" can be found here for future reference: http://meta.codegolf.stackexchange.com/a/1325/14215

PHP, 109
$n=4;$p=range(0,$n-1);for($k=0;$k<2;$k++){for($i=0;$i<$n;$i++){shuffle($p);echo join(' ',$p)."\n";}echo"\n";}

New implemented solution uses 1 more bytes. But now fulfill OP requirement.
Old solution which do not randomize permutation of line.
PHP, 108
$n=4;for($k=0;$k<2;$k++){for($i=0;$i<$n;$i++){for($j=0;$j<$n;$j++)echo rand(0,$n-1)." ";echo"\n";}echo"\n";}

This solution is wrong. "each line of each square is a random permutation of [0, N)"

Rule 3, quoting: "the value of n can't just be scattered across your program". The first 5 characters are $n=4;. There is nothing reading anything from STDIN, argument, POST, GET, COOKIE, SESSION.... Nothing.

@IsmaelMiguel, Many of other answers also uses the variable assignment instead of parameter/STDIN. And they also get more upvotes. So I am confusing if using assignment will broke rule. I think what OP wants not to use constant 4 or any other integer in program to same these 5 bytes. See but there must be a distinct value somewhere

@abc667, I did not understood how each line is not randomized when individual element is random.

Lines aren't suppose to be random but be random permutation of [0,n). Line 1 1 1 1 is wrong. There must be every number from (1,2,3,4) and every number must appear exactly once.

@abc667 Yes you are right, I added new solution using 2 more bytes but do what it is required to. Unfortunately solution is much similar to Ismael's solution.

Your solution (the one that works) is almost exactly like mine, but yours has 3 more bytes.

Rebol - 76 75
N: 4 do b:[loop N[print random collect[repeat i N[keep i - 1]]]]print""do b

Ungolfed:
N: 4

do b: [
    loop N [
        print random collect [
            repeat i N [keep i - 1]
        ]
    ]
]

print ""
do b

PHP (106 bytes):
This one was quite unexpectedly hard.
But here is a somewhat large solution:
<?for(;3>$j++;$o='',$z=range(0,($i=$n=$_GET[n])-1)){for(;$i--;shuffle($z))$o.=join(' ',$z)."
";echo"$o
";}

This can be rewritten to Javascript quite 'easily'.
For this to work, you must access the file over an http server, with ?n=<number> appended to the name.

Ruby - 69
r=->(n){[0,0].map{(1..n).map{(0..n-1).to_a.shuffle*" "}*"\n"}*"\n\n"}

Sample output:
puts r[5]

yields:
3 0 2 1 4
0 4 1 3 2
2 1 0 4 3
0 4 2 1 3
4 1 2 3 0

4 0 3 2 1
3 1 0 2 4
3 4 0 2 1
0 2 3 4 1
3 2 4 0 1

and
puts r[7]

yields
5 4 0 6 1 3 2
6 3 1 2 4 0 5
5 2 1 0 6 4 3
4 0 5 2 3 1 6
0 6 3 1 4 5 2
6 3 0 2 5 1 4
2 4 1 0 6 5 3

0 1 4 3 6 5 2
3 5 4 2 6 1 0
2 3 5 1 4 6 0
3 0 5 2 1 4 6
4 6 5 0 2 3 1
6 5 3 2 0 4 1
3 4 6 1 0 5 2

I think I can shave some bytes by making a helper function, give me a minute.

It was too complicated to create a helped function :(

Your lines appear to be random numbers in [0, N-1], whereas they should be random permutations of [0, N-1].

@Théophile fixed; interestingly it's the same length as before

Scala, 105 98 95 84 bytes
(n:Int)=>{def s=0.until(n).permutations take n map(_ mkString " ") mkString "\n";s+"\n\n"+s}

Ungolfed
def squares(n: Int): String = {
  def square(n: Int): String = 0.until(n).permutations.take(n).map(_.mkString(" ")).mkString("\n")
  square(n)+"\n\n"+square(n)
}

C++ 201
void f(int n)
{
std::vector<int> v;int N=n;
while(n--)v.push_back(n);
for(int i=0;i<2*N+1;i++)
{
random_shuffle(v.begin(),v.end());
if(!(i==N))for(int j=0;j<N;j++)printf("%d ",v.at(j));
else puts("");
puts("");
}
}

05AB1E, 13 bytes
2FFL<.rðý,}¶?

Try it online.
Or alternatively:
·FIL<.r})»2ä»

Try it online.
Explanation:
2F          # Loop 2 times:
  F         #  Inner loop the (implicit) input amount of times:
   L<       #   Push a list in the range [0, (implicit) input-1]
     .r     #   Randomly shuffle it
       ðý   #   Join it by spaces
         ,  #   Pop and output it with trailing newline
  }¶?       #  After the inner-loop is done: print a newline

·           # Double the (implicit) input
 F          # Loop that many times:
  IL<       #  Push a list in the range [0, input-1]
     .r     #  Randomly shuffle it
 })         # After the loop: wrap everything on the stack into a list
   »        # Join each inner list by spaces, and then each string by newlines
    2ä      # Split it into a list of two equal-sized strings
      »     # And join those by newlines as well (which is output implicitly as result)

If a leading instead of trailing newline is allowed, the first version could be 2F¶?FL<.rðý, instead, to save a byte on the }: Try it online.


text:
Print number triangle
Given a number N, output a NxN right angled triangle, where each row i is filled with numbers up to i.
Example
n = 0
(no output)
n = 4
1
1 2
1 2 3
1 2 3 4

n = 10
1
1 2
1 2 3
.
.
.
1 2 3 4 5 6 7 8 9 10

(no alignment needed)
n = N
1
1 2
1 2 3
.
.
.
1 2 3 4 .... N

There is no trailing space at the end of each line.
Least number of bytes wins, and standard loopholes are not allowed.

Can the output be a nested list of numbers?

What should be the behavior for n=0, and for n>9?

@Sieg Sure, as long as the output is correct.

@freekvd for 0 there is no output, for n>9 no special formatting required

Ah darn, you broke my submission.  Fixing ASAP

Can you include an example larger than 10 we can see how two double-digit numbers should look together?

Joe, 5 3 bytes (+2 or +3 for -t flag)
Well, apparently I didn't utilize the full potential of Joe. This was possible back when I first posted this.
\AR

Here, R gives the range from 0 to n, exclusive. Then \A takes successive prefixes of it (A is the identity function). Examples:
With -t flag (note: this is now the standard output even without the flag):
   (\AR)5
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
   \AR5
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
   \AR2
0
0 1
   \AR1
0
   \AR0

Without it:
   \AR5
[[0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4]]
   (\AR)5
[[0], [0, 1], [0, 1, 2], [0, 1, 2, 3], [0, 1, 2, 3, 4]]
   \AR2
[[0], [0, 1]]
   \AR1
[[0]]
   \AR0
[]

The rules got changed a bit. My old code didn't behave correctly with N =0. Also, now output could be just a nested list, so -t can be dropped.
1R1+R

Now, Rn gives a range from 0 to n, exclusive. If given 0, it returns an empty list.  1+ adds 1 to every element of that range. 1R maps the values to ranges from 1 to x. Empty liats, when mapped, return empty lists.
Example output:
   1R1+R0
[]
   1R1+R5
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]

Update: I just noticed something. The function automatically maps to rank 0 elements. The following example is run with -t flag.
   1R1+R3 5 8
1
1 2
1 2 3

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8

Old: 5 bytes (with the -t flag)
1R1R

This is an anonymous function which takes in a number, creates a list from 1 to N (1Rn) and maps those values to the preceding range, giving a range from 1 to x for each item of range 1 to N.
The -t flag gives output as a J-like table.
   1R1R5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Note : the language is very new and not complete, but the latest version was released before this challenge.

So J was not enough for having an advantage on array based challenges ? :D

@Optimizer Optimizing is important.

Suddenly, my most voted answer is the one I spent the least time on. The injustice.

I guess Joe is not your average Joe...

Python 3, 48 45 bytes
f=lambda n:n and[f(n-1),print(*range(1,n+1))]

Hooray for side effects.

Nested nothingness. Now that's twisted.

That's a nifty trick: putting the function before the print to execute the prints in reverse order.

APL, 5
⍪⍳¨⍳⎕

creates a vector 1..n and for each element another such vector.
Then ⍪ makes a column out of all vectors. This avoids the problem with trailing blanks.
Try it on tryapl.org

Older solution:
{⎕←⍳⍵}¨⍳⎕

Creates a vector 1..n
{⎕←⍳⍵} is a function that outputs for each (¨) element a vector 1..n on a separate line
This one can't be tried on tryapl.org unfortunately, because ⎕← doesn't work there.

There should be no trailing spaces in any line.

ah thank you, i missed that one. Will correct soon

I knew APL would be a solution

Oh God, what are my eyes seeing

J, 27 bytes
J is not good with non-array numeric output. This function creates a properly formatted string from the numbers.
   ;@(<@,&LF@":@:>:@:i.@>:@i.)

   (;@(<@,&LF@":@:>:@:i.@>:@i.)) 4
1
1 2
1 2 3
1 2 3 4

Try it online here.

You could also use ]\@i. to get ;@(<@,&LF@":@:>:@:]\@i.)

PHP, 53 Bytes
Edit 2: Ismael Miguel suggested reading from input instead of defining a function, so the score is now 53 bytes for PHP:
for($a=1;@$i++<$n=$argv[1];$a.=" ".($i+print"$a\n"));

And once again, it can be improved if PHP is configured to ignore errors (52 bytes):
for($a=1;$i++<$n=$argv[1];$a.=" ".($i+print"$a\n"));
for($a=1;$i++<$n=$_GET[n];$a.=" ".($i+print"$a\n"));

Edit: Austin suggested a 60 bytes version in the comments:
function f($n){for($a=1;@$i++<$n;$a.=" ".($i+print"$a\n"));}

Which can be improved if we doesn't display PHP errors (59 bytes):
function f($n){for($a=1;$i++<$n;$a.=" ".($i+print"$a\n"));}

$a stores the next line that will be printed, and each time it's printed a space and the next number (print always returns 1) are concatened to it.

Recursive functions (65 bytes):
function f($n){$n>1&&f($n-1);echo implode(' ',range(1,$n))."\n";}
function f($n){$n>1&&f($n-1);for(;@$i++<$n;)echo$i,' ';echo"\n";}   // Using @ to hide notices.

Shorter recursive function, with error reporting disabled (64 bytes):
function f($n){$n>1&&f($n-1);for(;$i++<$n;)echo$i,' ';echo"\n";}

Even shorter recursive function, with error reporting disabled and an empty line before real output (62 bytes):
function f($n){$n&&f($n-1);for(;$i++<$n;)echo$i,' ';echo"\n";}

Just for fun, non-recursive fucntions:
function f($n){for($i=0;$i<$n;print implode(' ',range(1,++$i))."\n");}    // 70 bytes
function f($n){for(;@$i<$n;print implode(' ',range(1,@++$i))."\n");}      // 68 bytes, hiding notices.
function f($n){for(;$i<$n;print implode(' ',range(1,++$i))."\n");}        // 66 bytes, error reporting disabled.

45 bytes: for($a=1;@$i<$n;$a.=" ".(@++$i+print"$a\n"));

@Austin: I've read in a comment that the code must be either a full program reading from input, or a function.
Very nice trick, it can be improved by a bit / byte: for($a=1;@$i++<$n;$a.=" ".($i+print"$a\n")); (44 bytes)

Ah ok, then I suppose you would do function f($n){for($a=1;@$i++<$n;$a.=" ".($i+print"$a\n"));}, which is 60 bytes.

Indeed. Are you OK if I edit my answer to add your solution?

Sure, go for it.

for($a=1;$i++<$n=$_GET[n];$a.=" ".($i+print"$a\n")); --> try this (full code, using url parameter n with the number)

@IsmaelMiguel: I've edited the answer with your idea. Using $argv[1] is better for the no-error version. Too bad we can't use $argc directly.

I have a shorter one for you, but only for PHP 4: for($a=1;@$i++<$n=$N;$a.=" ".($i+print"$a\n"));, pass the URL parameter N=x. This works only on PHP<4.2 because of the directive register_globals (http://php.net/manual/en/ini.core.php#ini.register-globals) which automatically registers the variables in $_POST, $_GET and so on to the current code automatically. $_GET['Z'] will be registed as the variable $Z. This value defaults to on on those old versions. To work for PHP<5.3, you have to create a php.ini file with register_globals=on

@BenoitEsnard You have to do $argv[1]*1 or $argv[1]+0, otherwise it will print 1 if you give it 0 when it is supposed to print nothing.  At least, that's what happens in PHP 5.5.

You can save 3 bytes removing unnecessary $n= in loop condition.

@Austin this can be done by changing @$i++= to @++$i<= so only one character must be added.

CJam, 13 12 bytes
ri{),:)S*N}/

How it works:
ri{       }/     "Run the block input number of times with iteration index from 0 to N-1";
   )             "Increment the iteration index (making it 1 to N)";
    ,            "Get an array of 0 to iteration index";
     :)          "Increment each of the above array members by 1";
       S*        "Join all above array numbers with space";
         N       "Add a new line. After all iterations, things are automatically printed";

Try it online here

JavaScript (ES6) 49 52
Such a simple task, I wonder if this can be made shorter in JS (Update: yes, using recursion)
Recursive 49
f=n=>alert((r=w=>n-i++?w+'\n'+r(w+' '+i):w)(i=1))

Iteraive 52
f=n=>{for(o=r=i=1;i++<n;o+='\n'+r)r+=' '+i;alert(o)}

Where can I test this? I cant seem to find any ES6 playgrounds that accepts this

@KristofferSall-Storgaard Firefox supports ES6 be default. So Firefox Console.

Pyth, 9 bytes
VQjdr1hhN

Really thought that this can be done shorter, but it doesn't seem so.
Try it online.
            Q = input()
VQ          For N in [0, 1, ..., Q-1]:
    r1hhN       create list [1, ..., N+1+1-1]
  jd            print joined with spaces

An alternative 9: VQaYhNjdY. If only a returned the list, then something like VQjdaYhN would be 8.

a briefly used to return the appended list.

I'm not familiar with Pyth, so could you elaborate why N+1+1-1?

@Sieg r is the Python-range function, therefore the -1 (r1N creates the list [1, 2, ..., N-1]). But in the Nth iteration of the loop, I want the list [1, 2, ..., N+1], therefore I need to add 2 to N. r1hhN translates directly to range(1, N+1+1). Another possibility would be r1+N2 (range(1, N+2)).

Or even mhdhN, but that's a complete different approach.

Java, 85 84 bytes
This is surprisingly short in Java.
void a(int a){String b="";for(int c=0;c++<a;System.out.println(b+=(c>1?" ":"")+c));}

Indented:
void a(int a){
    String b="";
    for(int c=0;
        c++<a;
        System.out.println(
                b+=(c>1?" ":"")+c
        ));
}

1 byte thanks to Bigtoes/Geobits

You can save one by moving the b+=... into println(b+=...).

><> (Fish), 40 37 + 3 = 40 bytes
&1>:&:&)?;1\
(?v:n" "o1+>}:{:@
ao\~1+

Once again, ><> does decently well at another number printing exercise. Run with the -v flag for input, e.g.
py -3 fish.py -v 4

Explanation
&               Put n in register
1               Push 1 (call this "i")

[outer loop]

:&:&)?          If i > n...
;                 Halt
1                 Else push 1 (call this "j")

[inner loop]

}:{:@(?         If j > i...
~1+ao             Pop j, print newline, increment i and go to start of outer loop
:n" "o1+          Else print j, print a space, increment j and go to start of inner loop

Prolog - 119
h(N):-setof(X,(between(1,N,K),setof(Y,between(1,K,Y),X)),[L]),k(L),nl,fail.
k([A|B]):-write(A),(B=[];write(" "),k(B)).

Python 2 - 62 54 65 bytes
def f(n):
 for x in range(n):print' '.join(map(str,range(1,x+2)))

The number n should be given as input to the program, not initialized in a variable.

Thanks for the hint. Was not sure about that.

Sorry, I should have been clearer. What I meant is that you must actually define N by doing N=input() or something similar, so that your program can be run as such. Here is a Meta discussion on the topic.

So this would be right, right?

Looks good now!

J, 9 characters
As a tacit, monadic verb.
[:":\1+i.

i. y – the numbers from 0 to y - 1.
1 + i. y – the numbers from 1 to  y.
": y – the vector y represented as a string.
":\ y – each prefix of y represented as a string.
":\ 1 + i. y – each prefix of the numbers from 1 to y represented as a matrix of characters.

Now that's quite smart. +1

This is more J-esque but doesn't it violate the rule about there being no trailing spaces on each line?

@miles Indeed it does! Anything else would be very complicated.

Python 2 - 72
>>> def p(N):print'\n'.join(' '.join(map(str,range(1,i+2)))for i in range(N))
...
>>> p(5)
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

For answers on this site, you should write a complete program or function. And you should print the result to stdout, or return them from a function. N should be read from input or taken as a function parameter, not predefined as a variable.

@user23013 OK,fixed!

The function definition needs to be included in the byte count, so I don't think this is 61. It's probably in your best interest to call the function something short, like p. On another note, you can remove two spaces - one between print and '\n' and the other between ))) and for.

@Sp3000 OK,thanks for attention! fixed!;)

72: def p(N):print'\n'.join(' '.join(map(str,range(1,i+2)))for i in range(N))

You forgot the other two changes.

@Sieg Yes! nice, as im new here i don't attention to this tiny stuffs ;)

C (with no loops, yeah!) - 72 bytes
b(n,c){if(n){b(n-1,32);printf("%d%c",n,c);}}r(n){if(n){r(n-1);b(n,10);}}

This creates a function r(n) that can be used this way:
main(){ r(5); }

See it in action, here on tutorialspoint.com
It requires a very few tricks easily explained.
I think it can be greatly improved.

Actually it's 75 bytes, not 74. However, you can cut it down to 72 bytes by replacing ' ' with 32 and '\n' with 10: b(n,c){if(n){b(n-1,32);printf("%d%c",n,c);}}r(n){if(n){r(n-1);b(n,10);}}

Pretty nice trick, thanks!

Thanks! I did my best to one up you in the C category, but I couldn't make anything shorter! So I decided to shorten yours instead.

64 bytes b(n,c){n&&b(n-1,32)^printf("%d%c",n,c);}r(n){n&&r(n-1)^b(n,10);} Wandbox

Perl, 28
Reads the parameter from stdin.
@x=1..$_,print"@x
"for 1..<>

From the command line:
perl -E'$,=$";say 1..$_ for 1..<>'

but I don't now how to count that (probably between 25 and 29).

Thunno 2 N, 5 bytes
RRıðj

Attempt This Online!
Explanation
RRıðj  # Implicit input    ->  4
R      # Range [1..n]      ->  [1,2,3,4]
 R     # Range of each     ->  [[1],[1,2],[1,2,3],[1,2,3,4]]
  ı    # To each list:
   ðj  #  Join by spaces   ->  ["1","1 2","1 2 3","1 2 3 4"]
       # Join by newlines  ->  "1\n1 2\n1 2 3\n1 2 3 4"
       # Implicit output

Julia 1.0, 34 bytes
~n=1:n.|>x->println(join(1:x,' '))

Try it online!

Python
import string
N,s=int(input()),list(string.digits)
for i in range(1,N+1):
    print(' '.join(s[1:i+1]))

Doesn't this fail if N >= 10?

@Sieg Yes you're right. I just learning Python, was looking for way to convert list of int to list of strings.

63 bytes: for i in range(int(input())):print(' '.join("123456789"[:i+1])) - Note that strings are treated as lists.

Go, 93 81 78 93 90 bytes
func r(n int)(s string){s=string(n+48);if n!=1{s=r(n-1)+" "+s};println(s);return}

Current ungolfed
func r(n int) (s string) {
    // Convert n to a string, we do not have to initialize s since
    // we hijacked the return value.
    // Numbers in the ascii table starts at 48
    s = string(n | 48)
    // Unless we are on our last iteration, we need previous iterations,
    // a space and our current iteration
    if n != 1 {
        // Collect the result of previous iteration for output
        s = r(n-1) + " " + s
    }
    println(s)
    // We can use a naked return since we specified the
    // name of our return value in the function signature
    return
}

If we need to handle N > 9 we can use the following at 78 bytes, however it requires importing the fmt package.
func r(n int)(s string){s=Sprint(n);if n!=1{s=r(n-1)+" "+s};Println(s);return}

If we include the import statement I'm now back at my initial 93 92 90 bytes
import."fmt";func r(n int)(s string){s=Sprint(n);if n>1{s=r(n-1)+" "+s};Println(s);return}

Test it online here: http://play.golang.org/p/BWLQ9R6ilw
The version with fmt is here: http://play.golang.org/p/hQEkLvpiqt

I'm not sure how I feel about the string cast, but any attempts to turn it into a byte array just makes it longer

The main problem I see is that it doesn't work for n>9. You can save a byte by changing != to >, though.

@Bigtoes, fixed now, I dont know if I'm supposed to count the import statement though

I know they're counted for the languages I'm more familiar with, so most likely yes. Sucks, I know :)

Golfscript 14
,{2+,1>' '*n}/

Expects the input number to be present on the stack.
Online example: link

Perl: 34 characters
print"@$_\n"for map[1..$_],1..$_;

This code gets the input number supplied through the special variable $_.

Most brackets are redundant here: print"@$_\n"for map[1..$_],1..$_ also works.

I adjusted the code.

C, 89 characters
// 90 characters
f(int n){int a=1,b;for(;n--;++a){for(b=0;b<a;++b)printf("%c%d",(!!b)*' ',b+1);puts("");}}

To eliminate confusion about puts("");. This simply prints a newline character (as seen here):

Notice that puts not only differs from fputs in that it uses stdout as destination, but it also appends a newline character at the end automatically (which fputs does not).

I got it slightly shorter with @TheBestOne's java algorithm:
// 89 characters
f(int a){char b[999]="",*p=b+1;int c=0;for(;a--&&(sprintf(b,"%s %d",b,++c)&&puts(p)););}

puts(""); does nothing. You can use char b[999]="" instead of char b[999]={0} to save 1 character.

puts(""); prints a newline character.

Clip, 16
Jm[ijkw,1iwS},1n

Explanation
J                   .- join with newlines                           -.
 m[i        },1n    .- map numbers from 1 to numeric value of input -.
    jkw   wS        .- join with spaces                             -.
       ,1i          .- numbers from 1 to index                      -.

Bash+coreutils, 26 bytes
seq $1|sed "x;G;s/\n/ /;h"

seq simply generates the numbers 1 to n
sed saves the entire output for a given line in the hold space, and then appends the next line to it.

ZX / Sinclair BASIC - 39 bytes
ZX Basic uses 1 byte per keyword (all the uppercase words), so helps to keep the byte size down a bit...
1 INPUT n:FOR i=1 TO n:FOR j=1 TO i:PRINT j;" ";:NEXT j:PRINT:NEXT i

Using n = 8

Nice. But ZX basic uses 6 more hidden bytes for each numeric literal (a common trick was VAL("1") (6 bytes as VAL is 1) insted of 1 (7 bytes))

R, 28
for(i in 1:scan())print(1:i)

The output is incorrect for an input value of 0. Also, it's unclear whether the leading [1] on each line is in violation of the spec.

@AlexA. if you look closely at the question you'll see my comment asking what behavior should be for n=0. But thanks for pointing me in the right direction!

I saw the comment. The thing is that this doesn't print nothing for 0, it prints 1; 1 0. (Pretend ; is a line break.)

You might want to also consider using cat(1:i,"\n"). Even though it's slightly longer than print(1:i), it doesn't include a leading [1] on each line.

TI-Basic, 28 bytes
Input N
For(I,1,N
randIntNoRep(1,N->L1
SortA(L1
Disp L1
End

This does not output as the format indicates; rather, the array is displayed, brackets and all, on the homescreen.

Haskell, 62 57 bytes
e=enumFromTo 1
f=putStr.unlines.map(unwords.map show.e).e

Point-free style. Usage example:
Prelude> f 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Doing e=enumFromTo 1 saves 7 bytes.

@Zgarb: Thanks, but if I swap out enumFromTo 1, I have to give the main function a name, too, so it's 5 bytes. Without the name it would be a let construct: let e=enumFromTo 1 in (putStr.unlines.map(unwords.map show.e).e) 5

C++, 130 bytes
To provide N, provide that many arguments on the command-line (the arguments don't matter, just the count of arguments).
#include <stdio.h>
#define printf P
int main(int c, char**){if(int x=c-1){main(x--,0);P("1");for(;x;--x){P(" %d",c-x);}P("\n");}}

C# - 94 bytes
Written as an anonymous function that returns a string, which doesn't seem to be disallowed by the spec.
n=>String.Join("\n\n",Enumerable.Range(1,n).Select(l=>String.Join(" ",Enumerable.Range(1,l))))

Here's an ungolfed version (comments are read in BDCA order):
n =>
    String.Join("\n\n",                    //...then join it together with newlines.
        Enumerable.Range(1, n).Select(l => //For each l from 1 to n, ...
                String.Join(" ",              //...and join it with spaces, ...
                    Enumerable.Range(1, l)    //...get the range from 1 to l, ...

Scala, 73 65 62 bytes
(n:Int)=>print(1 to n map(1 to _ mkString " ") mkString "\n")

Ungolfed
def printNumberTriangle(n: Int): Unit = {
  def rowString(m: Int): String = 1.to(m).mkString(" ")
  print(1.to(n).map(rowString).mkString("\n"))
}

Mathematica, 32
Print@Row[Range@i," "]~Do~{i,#}&

How about TableForm[Range/@Range@#]&?

Shorter: Grid[Range/@Range@#]&

And it even looks better. :) (I keep forgetting about Grid.)

But I'm not sure if there is no trailing space at the end of each line.

Oh good point. :(

JavaScript, 73
n=5;for(i=1,s='';i<=n;i++)for(j=1;j<=i;j++)s+=j+(j==i?"\n":' ');alert(s);

Excel VBA, 97 bytes
n = InputBox("n")
For i = n To 1 Step -1
For j = n To 1 Step -1
Cells(i, j) = j
Next j
n = n - 1
Next i

When executed you are prompted for n and the resulting triangles are displayed on the spread sheet:

Optimized version to taking autoformatting into account, 74 Bytes Sub f(n)
For i=n To 1 Step -1
For j=1To n
Cells(i, j)=j
Next j
n=n-1
Next i
End Sub

    JavaScript, 92 bytes
var x=function(o){for(var r=1;o>=r;r++){for(var a="",f=1;r>=f;f++)a+=f+" ";console.log(a)}};

usage: x(5)

Welcome to PPCG! I think you accidentally put a stray \`` in there. Also, [unnamed functions are generally allowed](http://meta.codegolf.stackexchange.com/questions/1501/should-function-literals-be-allowed-when-a-function-is-asked-for/1503#1503), so you can omit the var x. Even if not, you could shorten it to function x(o).... If you'd use the ES6 standard, you could shorten it even further by using [arrow notation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions). You can also leave out all the var`s ... we don't care about good style here. ;)

@MartinBüttner Thank you for the good pointers :)

awk, 27 bytes
{for(n=$0;n>=$i=++i;)print}

Got it working with some tweaks.
Example usage and output

me@home:~$ echo 0 | awk '{for(n=$0;n>=$i=++i;)print}'
me@home:~$ echo 1 | awk '{for(n=$0;n>=$i=++i;)print}'
1
me@home:~$ echo 2 | awk '{for(n=$0;n>=$i=++i;)print}'
1
1 2
me@home:~$ echo 12 | awk '{for(n=$0;n>=$i=++i;)print}'
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10 11
1 2 3 4 5 6 7 8 9 10 11 12

C,88 bytes
f(n,i,j,t){i=j=1;for(;i<=n;){t=j;printf("%d%c",t,j==i?(++i&&(j=1))*'\n':(++j||1)*' ');}}

Usage:
f(10);

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10

tcl, 76
time {set p "";set j 1;while \$j<=[incr i] {set p $p\ $j;incr j};puts $p} $n

Testable on http://rextester.com/FPJXC1708
Is the first line accountable? It is not part of the algorithm, only serves for acquiring input.

Perl 6, 24 bytes
{say ~$_ for [\,] 1..$_}

Jelly, 3 bytes
RRG

How it works:
RRG
R     Inclusive Range, 3 -> [1, 2, 3]
 R    Inclusive Range for all elements, [1, 2, 3] -> [[1], [1, 2], [1, 2, 3]]
  G   Attempt to format as grid

Try it online!

Pushy, 4 bytes
:Lh_

Try it online!
This works by building the stack up to the final line, step-by-step, and printing the stages:
:    \ Input times do (this consumes input):
Lh   \  Push stack length + 1
_    \  Print stack items, space separated.

J, 14 bytes
":@>@<@:>:\@i.

Usage:
   f =. ":@>@<@:>:\@i.
   f 5
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Explanation:
   i.4                      N.B.  i.n = list of numbers up to n
0 1 2 3

   >:@i.4                   N.B.  >:n = increment n
1 2 3 4

   >:\@i.4                  N.B.  >:\n = increment prefixes of n
1 0 0 0
1 2 0 0
1 2 3 0
1 2 3 4

   <@:>:\@i.4               N.B.   < = Box, <@:>:\ = Box the incremented prefixes of n
+-+---+-----+-------+
|1|1 2|1 2 3|1 2 3 4|
+-+---+-----+-------+

   ":@>@<@:>:\@i.4          N.B.   ":@> = String format each opened box (ensures no zeros or spaces appear at the end of each line).
1
1 2
1 2 3
1 2 3 4

Noether, 39 bytes
I~A{A0>}{A(i1+~i(j1+~jP" "P£)"
"P0~ji)}

Try it here!
Explanation:
I~A   - Push User Input onto the stack and store in variable A
{A0>} - If A>0
{     - Then do
A(    - loop until top of stack equals A
i1+~i - Increment i
(     - loop until top of stack equals i
j1+~j - Increment j
P     - Print top of stack (j)
" "   - Push the string " " onto stack
P     - Print top of stack (" ")
£     - Pop top of stack
)     - End loop
"\n"  - Push the string "\n" onto stack
P     - Print top of stack
0~j   - Set variable j to zero
i     - Push i onto stack
)     - End loop

Forth (gforth), 40 bytes
: f 1+ 1 do i 1+ 1 do i . loop cr loop ;

Try it online!

Vyxal j, 4 bytes
ɾɾvṄ

Try it Online!
Explained
ɾɾvṄ
rr   # range over range over input
  v  # vectorise
   Ṅ # join list by spaces

j flag joins by newlines

Arturo, 30 bytes
$=>[loop map&=>[@1..&]=>print]

Try it!

C++
int main()
{
   cout << "Enter N:";
   int N;
   cin >> N;

    for(int i=1; i <= N; i++)
    {
         for(int j=1; j<=i; j++)
            {
              cout << j;
            }
       cout << endl;
    }

  return 0;
}

Btw, this is code-golf (writing a program in the least amount of characters). Therefore something like cout << "Enter N:"; is not necessary. Also you can save a lot of chars, if you remove the whitespace, remove return 0;, ...

Python 2 - 60 61 53 bytes
k='1'
for i in range(2,input()+2):print k;k+=' '+`i`

With thanks to Sp3000

Had the indents in my code, lost them when I copied it to the post. And thanks for the suggestion!

Also one more thing: by default, code golf implies full program or function, so you can't assume N is already defined (maybe i<=input()?). On a side note though, you can save a few bytes by replacing str(i) with <backtick>i<backtick> :)

@Sp3000 \\i\\`seems to work:`i``.

@user23013 \i``. Ah thanks, so it does.

Javascript, 83
Not to happpy about this one
n=9;r='';for(i=1;i<n+2;i++){for(a=1;a<i;a++){r+=a+' '}r=r.slice(0,-1)+'\n'}alert(r)

Pretty straight forwards
r=''; so javascript doesn't add the value as numbers
r.slice(0,-1)+'\n'remove last space and add a line end
Edit: info
First I was trying to use A030512(int seq) but that failed n>10

k, 8
1+!:'1+!

I need to add 27 characters so I'm just going to type some nonsense here.
k)!5
0 1 2 3 4

k)1+!5
1 2 3 4 5

k)!:'1+!5
,0
0 1
0 1 2
0 1 2 3
0 1 2 3 4

k)1+!:'1+!5
,1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Wouldn't a brief explanation be a lot more fun than some nonsense?

Ruby - 51
r=->(n){(1..n).each{|i|puts (1..i).to_a.join(" ")}}

Sample output:
r[5] # 1
     # 1 2
     # 1 2 3
     # 1 2 3 4
     # 1 2 3 4 5

r[7] # 1
     # 1 2
     # 1 2 3
     # 1 2 3 4
     # 1 2 3 4 5
     # 1 2 3 4 5 6
     # 1 2 3 4 5 6 7

If you aren't pedantic enough to care, trim 3 bytes by changing puts to p - but this surrounds every line in the output with "

VBA, 116 bytes
Function n(m As Integer)
If m > 0 Then
For a = 1 To m
n = n & " " & a
Next
Debug.Print n(m - 1)
End If
End Function

Doesn't this generate a leading new line and a leading space?

oh leading space isn't allowed?  I thought only trailing space is not allowed

And the loser is... Pascal! 178 148 bytes
Sidenote: this isn't golfed at all, besides newlines and spaces. I haven't coded in Pascal for more than 10 years, so I used it just for the memories.
Golfed:
program p;procedure p(n:integer);var i,j:integer;begin for i:=1 to n do begin for j:=1 to i do begin write(j); end; writeln; end end;begin p(5);end.

Ungolfed:
program p;
procedure p(n:integer);
var i,j:integer;
begin
    for i:=1 to n do begin
        for j:=1 to i do begin
            write(j);
        end;
        writeln;
    end
end;
begin
    p(5);
end.

It doesn't seem to output the spaces. Also there is no need for semicolons before end.

Right... the spaces. I didn't remember that semicolons before end were optional, two extra bytes could be golfed there

Python 2 - 57 61 bytes
Had another idea.
Only bad thing is the leading space.

def f(n):
 s=''
 for x in range(n):s+=' %s'%(x+1);print s[1:]

example output:

>>> def f(n):
...  s=''
...  for x in range(n):s+=' %s'%(x+1);print s[1:]
...
>>> f(8)
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8

Change print s to print s[1:]. This gets rid of the first char in the string

Golfscript - 41 chars
"#{STDIN.gets}"~.0={}{)}if,{,{)}%" "*}%n*

How it works:
"#{STDIN.gets}" -> Read a string from input
"~" -> Evaluate the input
".0=" -> Create a clone of the input and check if it's zero
"{}{)}if" -> If it's zero, do nothing, else add one to the number
",{,{)}%" "*}%" -> Create a list from 0 to N, loop through it and create new lists and do other stuff that I don't have time to explain.
"n*" -> Display it nicely

ARM assembly 485 bytes
.global main
main:
    mov r0, #10
    mov r1, #1
    bl triangle

    mov r0, #10
    bl putchar

    mov r7, #1
    swi 0

triangle:
    cmp r1, r0
    movgt pc, lr
    push {r0,r1,lr}
    mov r0, r1
    mov r1, #1
    bl row
    mov r0, #10
    bl putchar
    pop {r0,r1,lr}
    add r1, r1, #1
    b triangle

row:
    cmp r1, r0
    movgt pc, lr
    push {r0,r1,lr}
    ldr r0, =numFormat
    bl printf
    pop {r0,r1,lr}
    add r1, r1, #1
    b row

numFormat:
    .asciz "%d "

called using the subroutine triangle, register r0 holds the limit and r1 holds the starting value.
tested on Raspberry Pi and Android

Java 8 - 293 chars
Golfed:
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
public class T{public static void main(String[] a){int n=10;System.out.println(IntStream.range(1,n+1).boxed().map(i->IntStream.range(1,i+1).boxed().map(j->""+j).collect(joining(" "))).collect(joining("\n")));}}

Ungolfed:
    import java.util.stream.*;
    import static java.util.stream.Collectors.joining;

    public class T {
        public static void main(String[] a){
            int n=10;

            System.out.println(
                 IntStream.range(1,n+1)
                          .boxed()
                          .map(i -> IntStream.range(1,i+1)
                                             .boxed()
                                             .map(j -> ""+j)
                                             .collect(joining(" ")))
                          .collect(joining("\n")));
        }
    }

Example output, n = 10:
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4 5 6
1 2 3 4 5 6 7
1 2 3 4 5 6 7 8
1 2 3 4 5 6 7 8 9
1 2 3 4 5 6 7 8 9 10

PHP (65 bytes):
This is pretty simple to do in php:
for(;$i++<$_GET[n];$_[]=join(' ',range(1,$i)));echo@join('
',$_);

This probably may output an empty string or the '\0' char or worst if you use 0 (there is no control on it).
This is because $_ will be nullwhen you use 0 and PHP will output null (which may output any of the said before).

There is another aproach (61 bytes):
foreach(range(1,$_GET[n])as$v)echo join(' ',range(1,$v))."
";

But it can't handle the 0 in the expected way.

Dyalog APL, 11 characters
Assumes ⎕IO←1.
(⍕↑)⍤0 1⍨⍳⎕

⍕⍵ – ⍵ represented as a string.
⍺↑⍵ – ⍺ items taken from ⍵.
⍺(⍕↑)⍵ – ⍺ items taken from ⍵, the result represented as a string.
⍺(⍕↑)⍤0 1⍵ – The previous expression, but executed for each item in ⍺ and each vector in ⍵.
(⍕↑)⍤0 1⍨⍵ – The previous expression with both arguments taken from ⍵.
(⍕↑)⍤0 1⍨⍳⍵ – The previous expression applied to the integers from 1 to ⍵.
(⍕↑)⍤0 1⍨⍳⎕ – The previous expression with input taken from the user.

K, 17 bytes
(`0:" "/$1+!)'1+!

Doing this sort of formatted output isn't very convenient in K. I used the "join" form of / from k5 to join elements of each vector with spaces. Try it with oK.
A nice thing about this solution is that it is in "tacit" form, so there's no need to create a function wrapper. Just append the argument N and suppress the result with ;:
  (`0:" "/$1+!)'1+!5;
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Powershell v2  number of Characters : 567
   function Build-Triangle
    {
         [CmdletBinding()]
         param(
            [Parameter(Mandatory=$True,ValueFromPipeline=$True)]
            [int]$n
        )

        begin {}
        process
        {
            [int]$cnt = 1
            if ( $n -gt 0 )
            {
                while ( $cnt -le $n )
                {
                    $string += $cnt.ToString() + " "
                    Write-Output -InputObject $string
                    $cnt++
                }
            }
        }
        end {}
    }

    Build-Triangle -n 10 | Measure-Object
    0 | Build-Triangle
    11 | Build-Triangle
    # just for kicks make the triangle upside down
    11 | Build-Triangle  | Sort-Object -Descending
    # find out how big the function is
    Get-Content Function:\Build-Triangle | Measure-Object -Word -Character -Line

Welcome to PPCG! This is code golf. Please show some effort to reduce the number of bytes in your code (single-letter variable names, no comments, no unnecessary whitespace would be a start).

C# - 92 bytes
void f(int n){for(int i=0;i++<n;)Console.WriteLine(string.Join(" ",Enumerable.Range(1,i)));}

Nothing fancy, just a packed function.

JavaScript, 73 chars
Not even trying to compare with the others here, just your typical first post:
for(n=prompt(),i=1;n>=i;i++){var l="";for(j=1;j<=i;j++)l+=" "+j;alert(l)}

I'm not sure this qualifies because it's alerting n times, which is not the same as outputting a 'right angle triangle' of the entire thing.

PowerShell -  42 32bytes
Edit: AdmBorkBork reports that we can save many bytes by using a complete script, and assuming a default delimiter!
 param($n)0..$n-gt0|%{"$(1..$_)"}

Never done any serious PowerShell, just felt I might learn something from this, and indeed I did. Old 42byte code:
function k($n){0..$n-gt0|%{1..$_-join" "}}

Defines a function k which takes an input $n, creates a range from 0 through to $n, filters for entires greater than 0, then creates a range from 1 to each remaining value, and joins these with a space. Example out:
PS > k 3
1
1 2
1 2 3
PS > k 0
PS >

Alternatively, you can define a filter, which will print as many triangles as you want.
filter z{0..$_-gt0|%{1..$_-join" "}}

PS > 3,0,2|z
1
1 2
1 2 3
1
1 2
PS >

Hiya! Not sure if you're still around, but you can use a full script instead of a function and use the default $OutputFieldSeparator to get down to 32 bytes with param($n)0..$n-gt0|%{"$(1..$_)"} -- Try it online!

@AdmBorkBork I do indeed still lurk around here, thanks for the tips!

Element, 20
_'[1+2:'.2:`\ ."\
`]

The main idea is that the stacks contain a string and a number. We repeatedly increment the number and append it to the string, printing the result.  Given that Element has zero support for arrays, I think this is a very decent score.
Since most people are probably unfamiliar with this language, Element is a golfing language I created in 2012.  You can see the most updated interpreter, written in Perl, here.
To make the explanation easier, I'll replace the newline with an L.
_'[1+2:'.2:`\ ."\L`]
_'                    input a number and put it onto the control stack
  [                ]  this is a FOR loop
   1+                 increment the number.  An empty stack is zero.
     2:               make a second copy of it
       '              put one copy on the control stack to save it
        .             append the other copy to the end of the string
         2:           make a second copy of the new string
           `          output one of them
            \ .       append a space to the other
               "      put the number from earlier pack onto the main stack
                \L`   output a newline, but the L should be an actual newline

Python 2, 60 bytes
One byte less than current best in Python 2, so I've decided to post it.
def f(x):
 if x:f(x-1);print" ".join(map(str,range(1,x+1)))

Usage:
f(5)

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

Three slightly different approaches
Ruby, 37 bytes
f=->n{n.times{|i|puts [*1..i+1]*" "}}

Ruby, 38 bytes
f=->n{puts (1..n).map{|i|[*1..i]*" "}}

Ruby, 40 bytes
f=->n{([*1..n+1]*" ").scan(/ /){puts$`}}

UniBasic 50 Bytes
S='';INPUT N;FOR I=1 TO N;S:=I;CRT S;S:=' ';NEXT I

Ungolfed:
S=''
INPUT N
FOR I=1 TO N
  S:=I
  CRT S
  S:=' '
NEXT I

q, 18 bytes
1+til each 1+til n

MATLAB, 63
for m=1:input('');fprintf(['1' repmat(' %d',1,m-1) 10],2:m);end

Not the best, but because of the requirements on spaces, functions like num2str and disp can't be used as they produce too many.
Run the code and enter the number when prompted (~=STDIN). It will then print the number triangle.

JavaScript, 77 Bytes
function(n){for(i=1;i<=n;i++){a='';for(j=1;j<=i;j++)a+=j+' ';console.log(a)}}

05AB1E, 3 bytes
LL»

Try it online.
Explanation:
L      # Create a list in the range [1, (implicit) input]
 L     # Map each integer `i` to a list in the range [1, `i`]
  »    # Join the list of lists by newlines,
       # which implicitly also joins the inner lists by a single space
       # (and output it implicitly)

Rockstar, 97 93 bytes
listen to N
X's 0
while N-X
build X up
O's 1
Y's 1
while X-Y
let Y be+1
let O be+" "+Y

say O

Try it (Code will need to be pasted in)
Original, 97 bytes
listen to N
X's 0
while N-X
build X up
O's 1
cut O
while X-O
rock O+1 in O

join O with " "
say O

Nibbles, 2 bytes (4 nibbles)
.,$,

.,$,        # full program
.,$,$       # with implicit arg added
.           # map over
 ,          # range from 1..
  $         # input
   ,        # getting the range from 1..
    $       # each number

Fortunately, Nibbles' default formatting for lists-of-lists is a happy match to the required output.


text:
Downhill Maze Solver
A downhill maze is given as a series of rows of space separated digits from 0 to 9 inclusive, plus one "S" and one "X", where the S denotes the start and the X denotes the finish.  In a downhill maze, you may only go to a space that is adjacent to you to the north, south, east, or west (no diagonals), and you may only go to spaces with a value less than or equal to the value you are currently on.
The program should output a path to navigate through the maze in the same format as the input, only all traversed spaces should have a "." in them, and all unvisited spaces should have a "#" in them.  The starting and ending cells should also keep their "S" and "X", respectively.  You can assume there is always a solution to the maze.
Example input:
3 3 3 3 2 1 S 8 9
3 1 1 3 3 0 6 8 7
1 2 2 4 3 2 5 9 7
1 2 1 5 4 3 4 4 6
1 1 X 6 4 4 5 5 5

Example output:
. . . . # # S . #
. # # . . # # . .
. # # # . # # # .
. # # # . # # # .
. . X # . . . . .

Can you move to and from S and X in any direction? Is the maze always solvable?

Also, can we assume that all the rows have the same length? And, just to clarify, a "digit" means a single decimal digit from 0 to 9 inclusive, right?

@Calvin Yes, you you may move to and from S and X in any direction.  The maze is assumed to be solvable.

@IImari Yes, all rows have the same length, and yes, a "digit" is a single digit from 0 to 9 inclusive.

JavaScript (ES6) 219
A function returning true or false. The solution (if found) is output on the console.
It does not try to find an optimal solution.
f=o=>(r=(m,p,w=0,v=m[p])=>
v>':'
  ?console.log(' '+m.map(v=>v<0?'#':v,m[f]='X').join(' '))
  :v<=w&&[1,-1,y,-y].some(d=>r([...m],d+p,v),m[p]='.')
)(o.match(/[^ ]/g).map((v,p)=>v>'S'?(f=p,0):v>':'?v:v<'0'?(y=y||~p,v):~v,y=0),f)

Ungolfed to death and explained more than needed
f=o=>{
  var r = ( // recursive search function
    m, // maze array (copy of)
    p, // current position
    w  // value at previous position
  )=>
  {
    var v = m[p]; // get value at current position
    if (v == 'S') // if 'S', solution found, output and return true
    {
      m[f] = 'X'; // put again 'X' at finish position
      m = m.map(v => { // scan array to obtain '#'
        if (v < 0) // a numeric value not touched during search
          return '#'
        else
          return v
      }).join(' '); // array to string again, with added blanks (maybe too many)
      console.log(' '+m) // to balance ' '
      return true; // return false will continue the search and find all possible solutions
    }
    if (v <= w) // search go on if current value <= previous (if numeric, they both are negative)
    {
      m[p]='.'; // mark current position
      return [1,-1,y,-y].some(d=>r([...m], d+p, v)) // scan in all directions
    }
    // no more paths, return false and backtrack
    return false
  }

  var f, // finish position (but it is the start of the search)
      y = 0; // offset to next/prev row
  o = o.match(/[^ ]/g) // string to char array, removing ' 's
  .map((v,p) => // array scan to find f and y, and transform numeric chars to numbers
   {
     if (v > 'S') // check if 'X'
     {
       f = p;
       return 0; // 'X' position mapped to min value
     }
     if (v > ':') // check if 'S'
       return v; // no change
     if (v < '0') // check if newline
     {
       if (!y) y = ~p; // position of first newline used to find y offset
       return v; // no change
     }
     return ~v; // map numeric v to -v-1 so have range (-1..-10)
   })

  return r(o, f, 0) // start with a fake prev value
}

Test in Firefox/FireBug console
f('3 3 3 3 2 1 S 8 9\n3 1 1 3 3 0 6 8 7\n1 2 2 4 3 2 5 9 7\n1 2 1 5 4 3 4 4 6\n1 1 X 6 4 4 5 5 5')

Output
. . . . # # S . #
. # # . . # # . .
. # # # . # # # .
. # # # . # # # .
. . X # . . . . .

true

We seem to share a mutual code unfathomability.

@Sieg why, isn't it crystal clear? I'll add an explanation tomorrow

@Sieg more fathomable?

Fathomable indeed.

C# - 463
Accepts input via STDIN, and should produce an optimal path, tested for the given test case, but not otherwise. Assumes there is always a solution.
I'm in a bit of a hurry, I have a deadline in 7 hours, but this just looked like too much fun to miss out on. I'm also out of practice. It could be very embarrassing if this goes wrong, but it's reasonably golfed.
using C=System.Console;class P{static void Main(){var S=C.In.ReadToEnd().Replace("\r","").Replace('X','+');int s=S.IndexOf('S'),e=S.IndexOf('+'),w=S.IndexOf('\n')+1,L=S.Length,i,j=L;var K=new int[L];for(K[s]=s+2;j-->0;)for(i=0;i<L;i+=2){System.Action<int>M=z=>{if((z+=i)>=0&z<L&&S[z]<=S[i]&K[z]<1&K[i]>0&(i%w==z%w|i/w==z/w))K[z]=i+1;};M(2);M(-2);M(w);M(-w);}for(w=e;w!=s+1;w=i){i=K[w]-1;K[w]=-1;}for(;++j<L;)C.Write(j%2<1?K[j]<0?j==s?'S':j==e?'X':'.':'#':S[j]);}}

Code with comments:
using C=System.Console;

class P
{
    static void Main()
    {
        var S=C.In.ReadToEnd().Replace("\r","").Replace('X','+'); // read in the map, replace X with + because + < 0
        int s=S.IndexOf('S'),e=S.IndexOf('+'),w=S.IndexOf('\n')+1,L=S.Length,i,j=L; // find start, end, width, length

        var K=new int[L]; // this stores how we got to each point as loc+1 (0 means we havn't visited it)

        for(K[s]=s+2; // can't risk this being 0
            j-->0;) // do L passes
            for(i=0;i<L;i+=2) // each pass, look at every location
            {
                // if a whole load of bouds checks, point new location (i+z) at i
                System.Action<int>M=z=>{if((z+=i)>=0&z<L&&S[z]<=S[i]&K[z]<1&K[i]>0&(i%w==z%w|i/w==z/w))K[z]=i+1;};
                // try and move in each direction
                M(2);
                M(-2);
                M(w);
                M(-w);
            }

        for(w=e;w!=s+1;w=i) // find route back
        {
            i=K[w]-1; // previous location
            K[w]=-1; // set this so we know we've visited it
        }

        for(;++j<L;) // print out result
            C.Write(j%2<1?K[j]<0?j==s?'S':j==e?'X':'.':'#':S[j]); // if K < 0, we visit it, otherwise we don't
    }
}


text:
Tracing the Hues of an Image
Load an image into this stack snippet and move your mouse over it. A black curve that follows the hue angle, starting at your cursor point, will be drawn:

Load an image: <input type='file' onchange='load(this)'>

Max length <input id='length' type='text' value='300'>

<canvas id='c' width='100' height='100'>Your browser doesn't support the HTML5 canvas tag.</canvas>

I've only tested this snippet in Google Chrome.
For example, when the cursor is above red, the curve has a 0° slope, but when it's above yellow, it has a 60° slope. The curve continues on for the specified length, continuously changing its slope to match the hue.
Load up this image and when you pan the cursor across it, the line just around the cursor should do a complete counter-clockwise turn:

This and this are other neat images to try. (You'll need to save them and then load them with the snippet. They can't be directly linked due to cross-origin constraints.)
Here is a non-minified version of the snippet:

function load(i) { //thanks http://jsfiddle.net/vacidesign/ja0tyj0f/
    if (i.files && i.files[0]) {
        var r = new FileReader()
        r.onload = setupImage
        r.readAsDataURL(i.files[0])
    }
}

function setupImage(e) {
    img = $('').attr('src', e.target.result)[0]
    function setup(c) {
        c.attr('width', img.width)
        c.attr('height', img.height)
        var ctx = c[0].getContext('2d')
        ctx.drawImage(img, 0, 0)
        return ctx
    }
    ctx = setup($('#c'))
    ctxRead = setup($('<canvas>'))
}

function findPos(obj) {
    var curleft = 0, curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return { x: curleft, y: curtop };
    }
    return undefined;
}

$('#c').mousemove(function(e) { //thanks http://stackoverflow.com/a/6736135/3823976
    if (typeof img === 'undefined') return
    var pos = findPos(this)
    var x = e.pageX - pos.x
    var y = e.pageY - pos.y
    $('#coords').html('x = ' + x.toString() + ', y = ' + y.toString())
    var maxLength = parseInt($('#length').val())
    if (isNaN(maxLength)) {
        alert('Bad max length!')
        return
    }

    function hue(x, y) {
        var rgb = ctxRead.getImageData(x, y, 1, 1).data
        var r = rgb[0] / 255, g = rgb[1] / 255, b = rgb[2] / 255
        return Math.atan2(Math.sqrt(3) * (g - b), 2 * r - g - b)
    }

    //gather points
    var xs = [x], ys = [y]
    var i = 0
    while (xs[i] >= 0 && xs[i] < this.width && ys[i] >= 0 && ys[i] < this.height && i < maxLength) {
        xs.push(xs[i] + Math.cos(hue(xs[i], ys[i])))
        ys.push(ys[i] - Math.sin(hue(xs[i], ys[i])))
        i++
    }

    //draw stuff
    ctx.clearRect(0, 0, this.width, this.height)
    ctx.drawImage(img, 0, 0)
    for (var i = 0; i < xs.length; i++)
        ctx.fillRect(Math.floor(xs[i]), Math.floor(ys[i]), 1, 1) //not using strokes because they may be anti-aliased
})
canvas {
  border:1px solid black;
}

Load an image: <input type='file' onchange='load(this)'>

Max length <input id='length' type='text' value='300'>

<canvas id='c' width='100' height='100'>Your browser doesn't support the HTML5 canvas tag.</canvas>

Challenge
Write a program that does what the snippet is doing, just not interactively. Take an image and an (x, y) coordinate in the bounds of image, and a maximum curve length. Output the same image with the added black curve that follows the hue angles starting at (x, y) and ends when it reached the maximum length or hits an image boundary.
Specifically, start the curve at (x, y) and measure the hue angle there. Go one unit (one pixel's width) in that direction, noting that your new position is most likely not an integer coordinate. Mark another point on the curve and move again, using the hue from the closest pixel (using something like floor or round, I won't be checking this precisely). Continue on like this until the curve goes out of bounds or it exceeds the maximum length. To finish, plot all the curve points as single black pixels (again, use nearest pixels) overlayed on the image, and output this new image.
The "hue angle" is just the hue:
hue = atan2(sqrt(3) * (G - B), 2 * R - G - B)

Note that for grayscale values that don't technically have a hue, this returns 0, but that's fine.
(This formula uses atan2 which most built-in math libraries have. R, G, B are from 0 to 1, not 0 to 255.)

You can use any common lossless image file format as well as any image libraries.
Take input from stdin or the command line, or write a function with arguments for the image file name, x and y, and the max length.
The max length and x and y are always nonnegative integers. You can assume x and y are in range.
Save the output image with a name of your choice or simply display it.
Your implementation does not have to exactly match the snippet. A few pixels in slightly different places due to a slightly different rounding/calculation method is fine. (In chaotic cases this could lead to curves that end up majorly different, but as long as they look correct visually, it's fine.)

Scoring
The smallest submission in bytes wins.

The snippet is completely broken in Firefox.

Snippet also doesn't work in Safari. (Cool challenge though, +1)

@Calvin's Hobbies May we chat? http://chat.stackexchange.com/rooms/22029/permission-to-conduct-a-related-challenge

MATLAB, 136
function t(g,x,y,l)
m=imread(g);imshow(m); h=2*pi*rgb2hsv(m);h=h(:,:,1);s=streamline(cos(h),-sin(h),x,y,[1,l]);set(s,'LineW',1,'Co','k');

Copied most of the setup and such from @sanchises, but  I instead use streamline to compute and draw the path. It does antialias the line though, and uses bilinear interpolation, rather than nearest-neighbor as specified.

C with SDL, 549 516 bytes
I'll start this party! For some reason, I felt like trying my hand at golf tonight. What you guys do is hard... If there's one thing I don't see any of on this site, it's SDL. I may have just found out why. This particular snippet complies with both SDL2 and SDL1.2, but is atrocious. Called like f("imagename.bmp", xcoord, ycoord, max_length);. It saves a file with the same name as given in the arguments. Output seems to be very similar to the OP's code snippet, but "fuzzier." I may try to fix this up a bit later.
#include"SDL.h"
f(char*C,x,y,m){SDL_Surface*P=SDL_LoadBMP(C);int p=P->pitch,i=P->format->BytesPerPixel,q=0;double X=x,Y=y,f=255,R,G,B,h;Uint8*Q,d=1,r,g,b,k;while(d){Q=P->pixels+y*p+i*x;SDL_GetRGB(i==4?*(Uint32*)Q:i==3?SDL_BYTEORDER==4321?*Q<<16|Q[1]<<8|Q[2]:*Q|Q[1]<<8|Q[2]<<16:i==2?*(Uint16*)Q:*Q,P->format,&r,&g,&b);R=r/f;G=g/f;B=b/f;h=atan2(sqrt(3)*(G-B),2*R-G-B);for(k=0;k<i;k++)Q[k]=0;X+=cos(h);Y-=sin(h);if((int)X-x|(int)Y-y)q++;x=X;y=Y;d=x<0|x>=P->w|y<0|y>=P->h|q>=m?0:1;}SDL_SaveBMP(P,C);SDL_FreeSurface(P);}

Here it is all unraveled:
#include"SDL.h"
f(char*C,x,y,m){
    SDL_Surface*P=SDL_LoadBMP(C);
    int p=P->pitch,i=P->format->BytesPerPixel,q=0;
    double X=x,Y=y,f=255,R,G,B,h;
    Uint8*Q,d=1,r,g,b,k;
    while(d){
        Q=P->pixels+y*p+i*x;
        SDL_GetRGB(i==4?*(Uint32*)Q:i==3?SDL_BYTEORDER==4321?*Q<<16|Q[1]<<8|Q[2]:*Q|Q[1]<<8|Q[2]<<16:i==2?*(Uint16*)Q:*Q,P->format,&r,&g,&b);
        R=r/f;
        G=g/f;
        B=b/f;
        h=atan2(sqrt(3)*(G-B),2*R-G-B);
        for(k=0;k<i;k++)Q[k]=0;
        X+=cos(h);
        Y-=sin(h);
        if((int)X-x|(int)Y-y)q++;
        x=X;y=Y;
        d=x<0|x>=P->w|y<0|y>=P->h|q>=m?0:1;
    }
    SDL_SaveBMP(P,C);
    SDL_FreeSurface(P);
}

I should note that care was taken to make it cross platform--in the interest of honesty, it didn't feel good to hardcode it for my machine, even if it cut off a substantial number of bytes. Still, I feel like a couple things are superfluous here, and I'll look at it again later.
EDIT-------
This IS Graphical Output, after all...
I'll update with images that I find interesting periodically.
f("HueTest1.bmp", 270, 40, 200);

f("HueTest2.bmp", 50, 50, 200);

f("HueTest3.bmp", 400, 400, 300);

MATLAB, 186 172
The game is on! Call as t('YourImage.ext',123,456,100'), for an image of any type MATLAB supports, starting at (x,y)=(123,456) and maximum length 100. Initial positions cannot be exactly at the right and bottom edges (that would cost me two bytes), so to start on the edge, use something like x=799.99 to start at x=800. Indexing starts at 1, not 0.
Code:
function t(g,x,y,l)
m=imread(g);[Y,X,~]=size(m);h=2*pi*rgb2hsv(m);while(x>0&x<X&y>0&y<Y&l)
p=ceil(x);q=ceil(y);m(q,p,:)=0;a=h(q,p);x=x+cos(a);y=y-sin(a);l=l-1;end
imshow(m)

Revisions:

Changed from line from previous to next pixel to just putting a dot at a pixel, since the line will never be longer than a pixel! Still using line since that is the shortest code I know to produce a pixel.
Changed the color from black to blue, using Co to expand to Color (which MATLAB does automatically)
Changed order of calculating next position and drawing a point, since I realized thanks to @grovesNL that I was actually drawing out of bounds since I was checking bounds after changing the position.
Changed from drawing lines to setting rgb matrix to 0 and displaying after.

Aren't x=0 or y=0 potentially valid positions?

Also, how is this 166 bytes?

@grovesNL Sorry, accidentally counted my test version without the function header. Spec did not require zero-based or one-based indexing, so I'm using MATLAB's one-based, so no, x=0 or y=0 is not valid in this program.

Ah, I forgot that MATLAB was one-based (it has been a while). But I guess that may make x=X and y=Y valid instead?

@grovesNL It does, but is it worth 2 bytes for the minuscule chance that floating point numbers accumulate to exactly x==X and y==Y, even though the spec says 'I won't be checking this precisely' regarding rounding? (Although of course, a 188 byte count does look prettier than 186 ;) )

I meant x==X or y==Y, so it's an entire column and row you are excluding. I'm just being pedantic, don't mind me :-)

@grovesNL I know (no offence taken), but since I use ceil, any position x between x>X-1 and x<X is rounded to the hue value in pixel x=X, so the hue values in those columns are used as much as all the others (well, eps(X) less, but let's not get too pedantic). Remember that for a 800x800 image, you would index from 0 to 799; I already did +1 by indexing from 1 to 800.

Fair point, one-based array with ceil should cover that boundary. Does this give you the same results on the sample image we used above?

@grovesNL Yes, but really, what's the fun in posting an exact duplicate of other people's pictures?

Let us continue this discussion in chat.

Hah! Beat you at your own game, my MATLAB solution is only 135 chars!

Python, 203 172
from scipy.misc import*
def f(i,x,y,l):
 a=imread(i);Y,X,_=a.shape;o=a.copy()
 while(X>x>0<y<Y<[]>l>0):r,g,b=a[y,x]/255.;o[y,x]=0;l-=1;x+=2*r-g-b;y-=3**.5*(g-b);imsave(i,o)

Sample output:

Call with f("image.jpg", 400, 400, 300)
I've wasted a lot of characters for the import, if anyone has suggestions to improve it. May not work in 3.0

From a quick glance: sqrt(3) -> 3**.5? I can't think of anything for the imports though.

Nice one! That will be useful in the future.

Processing, 323 characters
void h(String f,float x,float y,float m){PImage i=loadImage(f);PImage i2=loadImage(f);while(m>0){color c=i.get((int)x,(int)y);float r=red(c)/255;float g=green(c)/255;float b=blue(c)/255;float h=atan2(sqrt(3)*(g-b),2*r-g-b);float dx=cos(h);float dy=-sin(h);m-=1;x+=dx;y+=dy;i2.set((int)x,(int)y,color(0));}i2.save("o.png");}

With whitespace:
void h(String f, float x, float y, float m) {
  PImage i = loadImage(f);
  PImage i2 = loadImage(f);

  while (m > 0) {

    color c = i.get((int)x, (int)y);
    float r = red(c)/255;
    float g = green(c)/255;
    float b = blue(c)/255;
    float h = atan2(sqrt(3) * (g - b), 2 * r - g - b);

    float dx = cos(h);
    float dy = -sin(h);

    m-= 1;
    x += dx;
    y += dy;

    i2.set((int)x, (int)y, color(0));
  }

  i2.save("o.png");
}

I'm sure I could shorten this further, but it works for now.

JavaScript 414
function P(G,x,y,l){
I=new Image()
I.onload=function(){d=document,M=Math,C=d.createElement('canvas')
d.body.appendChild(C)
w=C.width=I.width,h=C.height=I.height,X=C.getContext('2d')
X.drawImage(I,0,0)
D=X.getImageData(0,0,w,h),d=D.data,m=255,i=0
for(;l--;i=(w*~~y+~~x)*4,r=d[i]/m,g=d[i+1]/m,b=d[i+2]/m,H=M.atan2(M.sqrt(3)*(g-b),2*r-g-b),d[i]=d[i+1]=d[i+2]=0,x+=M.cos(H),y-=M.sin(H))
X.putImageData(D,0,0)}
I.src=G}