text:
Out-of-Control Rounding Errors
Background
You have recently been hired by a small accounting firm.
The world of accounting is somewhat foreign to you, so you're not sure whether you are following all the professional guidelines.
In particular, you don't know when you should round all those numbers, and in which direction, so most of the time you just wing it and hope for the best.
Input
Your input is a single string that represents a simple calculation.
It contains some number of nonnegative integers delimited by the characters +-*/.
The string reads from left to right, and the normal precedence rules are ignored, so "23+1*3/4" means "start with 23, add 1, multiply by 3, and divide by 4", the result being 18.
The input will not contain numbers that start with 0 (except 0 itself), nor a division by zero.
Output
At each stage of the calculation, you can either round the result up or down to the nearest integer, or keep it as it is.
Finally, you round either up or down to obtain a integer result.
Your output is the list of integers that may result from such a calculation, sorted and without duplicates.
Rules
You can write either a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
Test Cases
"42" -> [42]
"2+0+4-0" -> [6]
"23+1*3/4" -> [18]
"5/2" -> [2,3]
"5/2+7/3*6-1" -> [17,18,19,23]
"23/2/2*30-170/3" -> [-7,-6,-2,-1,0,1,3,4]
"1/3*2*2*2*2*2*2" -> [0,16,20,21,22,24,32,64]
"1/3*9" -> [0,3,9]

Does the program have to work for all possible inputs (regardless of number size), a limited size input, or only the test cases?

@orlp It should work at least when all input numbers and intermediate results are below, say, 10 million in absolute value. The accounting firm is small, after all.

Take note of the test case 1/3*9, which may fail if you use floating point numbers.

@Claudiu Thanks, I added it to the challenge.

J, 84 bytes
Starting from a 1 element list the function keeps all the possible intermediate numbers in the list by evaling the next expression and adding it's up and down rounded copies.
Will golf further and add explanation tomorrow.
Can't find obvious ways to golf it more.
f=.3 :'/:~~.<.>((,>.,<.)@".@(":@],''x'',;@[))&.>/|.(>@{.;_2<\}.);:y rplc''/'';''%'''

Passes all the tests.
Usage:
   f '1/3*2*2*2*2*2*2'
0 16 20 21 22 24 32 64
   f '1/3*9'
0 3 9

Try it here.

How do you deal with them as rationals instead of floats - is that built in to J? (Complete J noob here)

@Claudiu At every eval I force extended precision numbers (in this case rationals) by appending the letter x at the end of the list.

Python 2, 220 characters
import re,sys,math as m,fractions as f
X=f.Fraction
M=map
F=['+']+re.split("(\D)",sys.argv[1])
r=[X(0)]
while F:U=[eval('f.'+`n`+F[0]+F[1])for n in r];r=M(X,U+M(m.floor,U)+M(m.ceil,U));F=F[2:]
print sorted(set(M(int,r)))

It keeps a list of all possible numbers and at each step, generates three numbers for every number in the list, even if there are duplicates. Thus the run-time complexity is exponential. However, it works instantly for these small examples. Dupes are removed at the end.
It uses fractions.Fraction to do exact division, avoiding floating point inexactitudes.
Add 5 characters (r=map(X,g) --> r=set(map(X,g))) to dramatically increase performance.

Here's an easy golf to start off with: \D is a predefined character class for matching non-digits

@orlp: Fixed now! (I think..)

@Claudiu: that should be either r"(\D)" or "(\\D)". Also, if you use Python 3, you can replace the indexing into F with starred assignment, e.g.: A,B,*F=F, use A and B instead of F[0] and F[1], and get rid of F=F[2:].

@Mac: "\D" ends up working anyway and it's shorter. It's not a valid escape sequence so Python just includes the \  and D verbatim. Good Python3 tip actually, I'll check it out, though I'll have to replace backticks with repr() and turn the map result into a list. Starred assignment is something I wish Python 2 had..

Python, 421 370 354 bytes
Sorry, please bear with me. I am really new to python (I was just looking for a language that supports fractiosn) and used all of the few tricks I knew for shortening the code but it is still a monster considering that there is a python solution of almost half the size. I learned a lot and thought I'd submit it anyway=)
New Version thanks to @kirbyfan64sos and @Zgarb
from fractions import*
from math import*
import re,operator as z
s=input()
N=re.split(r'[\*\/\-\+]',s)
O=re.split(r'[0-9]+',s)[1:-1]
d={'+':z.add,'-':z.sub,'*':z.mul,'/':z.truediv}
l=[int(N[0])]#list of inters up to now
for i in range(len(O)): #iterate over all operations
    n=set()
    for f in l:
        f=d[O[i]](f,Fraction(int(N[i+1])))
        n.update([floor(f),ceil(f),f])
    l=n
print(set(map(floor,n)))

Old Version
from fractions import Fraction as F
from math import floor,ceil
import re
s=input()
N=re.split(r'[\*\/\-\+]',s)   #Numbers
O=re.split(r'[0-9]+',s)[1:-1] #Operators
l=[int(N[0])]
for i in range(len(O)): #Iterate over all operators
    n=set()
    for f in l:           #Iterate over all possible numbers
        g=F(int(N[i+1]))
        o=O[i]
        if o=='/':
            f/=g
        elif o=='*':
            f*=g
        elif o=='-':
            f-=g
        else:
            f+=g
        n.add(floor(f))  #Add all possible numbers to a new set
        n.add(ceil(f))   # the 'set' structure prevents from having multiple copies
        n.add(f)         # which is a really nice feature
    l=n                #repeat
print(set([floor(k) for k in n])) #also remove the unrounded ones

For one thing, you could replace some of the space indents with tabs (it generally sucks, but works well in code golf: a tab == 1 character). You can also use a dict instead of several ifs (d={'+': operator.add, '-': operator.sub, ...}; d[op](a, b)). Also, [floor(k) for k in n] can be shortened to map(floor, n), and the n.add calls can become n.extend([floor(f), ceil(f), f]).

Wow thank you very much, I'm gonna try and implement them! I allready counted the indents as tabs but I had to convert them to spaces here.

You can also just use single spaces; they should work.

As far as I can see, you use F only once, so you could do from fractions import* and save some bytes. Same with math. Remove the spaces around =, they are unnecessary. Also, you should assign the input to s instead of hard-coding.

@flawr Remove every optional space. Also, you need to be able to accept any input. Use s=input() rather than s = "1/3*9", remove your comments, etc.

Oh sorry, I pasted the wrong version, now corrected it.

Mathematica, 134
Union@Flatten@{Floor@#,Ceiling@#}&@ToExpression@StringReplace[#,x:("+"|"-"|"*"|"/"~~NumberString):>"//{Floor@#,#,Ceiling@#}"~~x~~"&"]&

MATLAB, 283 chars
function[u]=w(s)
s=[' ' strsplit(regexprep(s,'\D',' $& '))];s=reshape(s,[2,size(s,2)/2]);o=s(1,:);d=cellfun(@str2num,s(2,:));a=d(1);for n=2:size(o,2)switch o{n}case'+';a=a+d(n);case'-'a=a-d(n);case'/'a=a/d(n);case'*'a=a*d(n);end;a=[ceil(a);a;floor(a)];end;u=unique(a(mod(a,1)==0))end

Ungolfed:
function [u] = WingitRound(i)
    i=[' ' strsplit(regexprep(i,'\D',' $& '))];
    i=reshape(i,[2,size(i,2)/2]);

    o=i(1,:);
    n=cellfun(@str2num,i(2,:));

    a=n(1);

    for n=2:size(o,2)
        switch o{n}
            case '+'
                a = a + n(n);
            case '-'
                a = a - n(n);
            case '/'
                a = a / n(n);
            case '*'
                a = a * n(n);
        end
        a = [ceil(a);a;floor(a)];
    end

    u=unique(a(mod(a,1)==0)));
end

While writing this, I realized that there is an even shorter way of doing this, which I will add once I finish writing it.

VBA, 347 bytes
Function OoCRE(inp As String)
ct = 0
i = 1
Do While i < Len(inp)
c = Mid(inp, i, 1)
If Not IsNumeric(c) Then
ct = ct + 1
If ct = 2 Then
inp = Round(Application.Evaluate(Left(inp, i - 1))) & Right(inp, Len(inp) - (i - 1))
i = InStr(1, inp, c)
ct = 1
End If
End If
OoCRE = Round(Application.Evaluate(inp))
i = i + 1
Loop
End Function

There is quite a lot of golfing to be done here, primarily removing superflous whitespace and choosing shorter var names


text:
Print the first character of the previous answers
The accepted winner is isaacg, with his 7-bit ASCII answer. However, the challenge isn't over yet - this bounty is awarded to the shortest answer. If, somehow, you get all the first characters of all the other answers down into 10 bytes, you will win the bounty. This includes all the characters from Round 2's GolfScript answer (plus the one added by that answer itself). This is the ONE time I will let you go out of order - if you have any objections to this, let me know in the comments.

I'd like to give credit to randomra, who helped me with my old idea and gave me this new one.

Previous Winners

Round 1: isaacg, with 7-bit ASCII
Next bytes: 30 (or 10 if you want that sweet, sweet rep)
You know, code-golfing is really cool. People take a challenge, and it slowly gets smaller! But let's do this another way. So, here is my challenge:
The code will print the first character of all the previous answers in the order they were posted (the first answer prints nothing)
The code starts at 100 bytes and decreases by 5 each time.
If two posts are going by the same answer (i.e, they both posted within a few seconds of each other), the newer one has to add the old one's character and decrease by 5 bytes (even by a few seconds).
Any language can be used.
Your code must not produce any errors.
Your code must use all the bytes required for the first step.
Your code must print to STDOUT.
Non-printable characters are OK, but:

They can not be the first character (for the sake of the purpose of this question)
You must let everyone know where they are

You may post multiple answers, but:

You must wait 2 answers before posting another (so if you posted the 100 bytes, you have to wait until 85 bytes.)

You can't:

use more than 10 bytes of comments
have variables that go unused for the entire program
fill the program with whitespace
have variable names longer than 10 bytes (but you can have multiple less-than 10-byte variables)
(EMBLEM's first answer being the exception to these rules, because it was posted before these restrictions.)

No standard loopholes. Unless you want to take all the fun out of the challenge.
When no more answers are submitted for 3 weeks, the answer that uses the fewest bytes wins. (In the event of a tie, the one printing the longer string wins.)

Example: The third answer has to be a 90 bytes long code outputting two characters (the first char of the 100-byte code then the first char of the 95-byte code). The first answer outputs nothing (no previous answers to get chars from).

"Unnecessary whitespace" is bad wording. Python's whitespace to end statements is unnecessary, because you can use semicolons.

Did you notice that this will end with only 9 to 10 answers ?

@Optimizer I think 10+ is possible - each answer reduces the available space by 5 bytes, and increases the requirement by 1, so the hard limit is probably 16 answers.

@isaacg assuming that golfing languages are still available at 10+ answer stage.

@Optimizer Languages can be repeated.

@isaacg ah. my bad in that.

Can we use non-printable ascii?

@user23013 Only if it's not the first character, so we don't ruin the whole challenge. It still counts to bytes, and you have to mark where the characters are. Other than that, it should be OK.

What's the purpose of "Your code must have one print statement/function"? Can we use GolfScript or CJam that print the stack automatically without a print statement? Alternatively, can we use two or more print statements or print the characters one by one in a loop?

@user23013 Yes. I think I messed that one up, it just has to print to STDOUT.

Perhaps, we can start at 100 bytes again, but start with ppuppPq([#fwSmdP[ as the starting string, and restarting each time the string is longer than the allowed bytecount. I can't think of a winning criterion then, though.

@sanchises What would happen after 100 answers?

@LegionMammal978 The universe will end.

@LegionMammal978 Well, this answer encodes and prints 17 letters in only 15 bytes. It can just keep going until no-one can add any more answers. But just in case someone is able to get all 18 in 10 bytes, we should have to wait 24 hours before restarting from 100.

@Scimonster I'd be impressed if anyone did that.

@ASCIIThenANSI So would i, but it might be possible. That's why i suggest giving it 24 hours to be pretty sure that no more golfing is going to be done.

@Scimonster Agreed.

@Scimonster You honestly think there is a 4-bit character set that includes all of #(PS[dfmpquw? We're running into the very limits of information density here. Unless you write a 10-byte program that processes all previous answers. Not sure if that's worth waiting for.

@sanchises We're not saying there is one. We're giving people a chance to see what they can do. If no one can, we'll restart it.

Can your answer print any printable characters that aren't part of previous answers? I think it's possible to write a 10 byte golfscript that just prints the ASCII characters 18 times.

⯋劳⽐̡㋰Ύ褞⺄祳PΏ -- can anybody decode this ?

-1 Why didn't this challenge just die with dignity after the 15-byte solution? It seems disingenuous to change it after a good, "winning" answer has been given just so you can keep playing by different rules.

Please read the comments on this answer and, if you don't mind, edit the question to address the ambiguity.

@Rainbolt I've fixed the ambiguity. This means you can't define a bunch of variables, and then print the characters without using them. In the linked question, var __ is disallowed, but renaming p would be acceptable.

@bcsb1001 Nope. GolfScript did it in 35: http://codegolf.stackexchange.com/a/48673/38891

18 chars in 10 bytes, anyone?

@mbomb007 Might be possible. 15-bytes surprised everyone.

Yeah, but that wasn't a programming language, but rather an encoding. The characters necessary now aren't possible due to data density and current encodings.

@mbomb007 Maybe you could encode some golfing language in 7-bit ASCII.

It doesn't look like it's going to happen.

7-bit ASCII, 15 bytes
Updated: I did not realize that padding should occur at the end.
Correct version, padded at end:
hexdump (xxd):
0000000: e1c3 af0e 1438 a8b6 8f37 7a7b 7250 b6    .....8...7z{rP.

Printouts (not sure which is correct):
�ï8��z{rP�

áÃ¯8¨¶7z{rP¶

Old version, incorrectly padded at the front:
pá×
T[G½=¹([

The language / format here is 7-bit ascii, where each group of 7 bits corresponds to an ASCII character. It is used in transferring SMS data. A decoder is located here.
No widely accepted ruling exists on whether answers to fixed output questions which are not written in a programming language are allowed. See this meta post for more information. (I apologize, I misread that post earlier.)

Congratulations! You are the only person I've seen to compress a string longer than the code it's included in! :D

@ASCIIThenANSI Compressing a string into a shorter program is easy. The Python program print('A'*100) prints a string of 100 A's. Compressing an effectively random string is not easy.

@Calvin'sHobbies This would be easier if we had all just started all our code with the letter 'p'. :D

-1 I should've looked at this sooner... This appears to be encoded incorrectly. It looks like you start with a bit of padding, but from what I can tell from the format (and this answer is already stretching the definition of a format, since packed 7-bit ASCII isn't actually used anywhere), the data should be padded at the end, not the start. And even with the padding, I think the rest isn't encoded correctly.

The first 6 bytes look okay now, but it seems something goes wrong after that. For instance, it seems that the seventh byte should be ('q'<<7)+'(', which is a8, not d1.

@Runer112 I figured out the bug, my generation program dropped the initial 0 bit on ). I'll have it fixed in a moment. Thanks for catching this.

So, I know this is off-topic, but does 7-bit ASCII converted to 8-bit turn 0110111 0100100 into 01101110 100100...? Is that why it looks like it's printed weird?

@ASCIIThenANSI Yes, that's how the format works. I'm just displaying it byte by byte.

It should be "áÃ¯<SO><DC4>8¨¶7z{rP¶".

Element, 80 bytes
programs do many fun things, like print the letters p`, p`, u`, and p` in a row.

This is a language I created over three years ago.  You can find an interpreter, written in Perl, here.  The ` operator prints the top thing on the stack (the letters).  The other punctuation does do stuff, like concatenation, but the results are never printed.

Very clever, sir. Very clever...

Clip, 20 bytes
[M"ppuppPq([#fwSmdP"

I think you are the last one standing. Unless somebody can compress ppuppPq([#fwSmdP[ in 15 bytes AND output it.

@sanchises If anyone does, I'd award a bounty. Because it would be just that good.

@sanchises If only there was some esoteric language which outputted the  program with all occurrences of p replaced with pp. Then a solution would be pupPq([#fwSmdP[.

@bcsb1001 Yes, I thought of something like that recently; an esoteric language where each command is a winning challenge solution on this site, and uses the output of that command as the input for the next command. It would be awesome if somebody could program anything in that.

@sanchises But would that break a standard loophole rule by going out to the internet?

Common Lisp, 65 bytes
(print(map 'string #' code-char #(112 112 117 112 #x70 80 #x71)))

The last 112 should be changed to 80 (somehow).

With this answer, an age of darkness has been ushered in.

Scratch, 45 bytes
when green flag clicked
show
say[ppuppPq([#f]

Byte count as per text representation. See meta.

Nice job. I never thought of using Scratch.

Round 2: Ruby, 75 bytes
"ppuppPq([#fwSmdP[ppnvos".chars.each do|character|;print character;end#4444

I thought I'd make it a little more challenging by starting my answer with a quote! >:D

Python 3, 95 bytes
pre='public class f{public static void main(String[] a){System.out.print("");}}'
print(pre[0])

Haskell, 35 bytes
main = putStrLn "\&ppuppPq([#fwS\&"

What does "&" do?

@Hjulle Take up two characters. (It's an escape code for the empty string.)

It has been 24 hours since the edit! Let's do this! :D
Java, Round 2, 100 bytes
public class Bytes{public static void main(String[] args){System.out.print("ppuppPq([#fwSmdP[p");}}

How about marking this "Round 2"?

Java, 100 bytes
public class f{public static void main(String[] a){System.out.print("");}}//createdbyEMBLEMasdfghjkl

Mathematica, 75 bytes
Print[StringJoin[First/@Characters/@{"publ","pre=","usin","p1 =","prog"}]];

F#, 60 bytes
[<EntryPoint>]let main arg=System.Console.Write "ppuppPq(";0

F# script, 40 bytes
System.Console.Write "\u0070puppPq([#fw"

It has its own file type (.fsx), so I'm pretty sure that it counts as a language.

You forgot the 'w' from Scratch.

I think this is also missing the 'f' from the 50 byte javascript answer.

Fixed that, too

Round 2: ///, 65 bytes
\p/CodeGolfIsAwesome!/puppPq/CodeGolfIsAwesome!([#fwSmdP[ppnvos"R

Thought I would spice it up a bit more with a backslash :)

C#, 90 bytes
using System;namespace IAmAwesome{class Program{static void Main(){Console.Write("pp");}}}

Ruby, 70 bytes
q = ["publ", "pre", "usi", "p1 ", "pro", "Pri"]
q.each{|s| print s[0]}

You'd have to rearrange it to ["publ", "pre", "usi", "p1 ", "pro", "Pri"].

C, 55 Bytes
#include<stdio.h>
int main(){return puts("ppuppPq([");}

It should be changed to "ppuppPq([".

@LegionMammal978 Thanks, fixed.

JavaScript, 50 bytes
function foo() {console.log("ppuppPq([#");}
foo();

It should be ppupPq([#

@ASCIIThenANSI I don't think so.

MATLAB, 30 bytes
disp([112 112 'uppPq([#fwSm'])

Nicely shows how loose MATLAB goes about with data types.

Mathematica, 25 bytes
Print["ppuppPq([#fwSmd"];

I had a novel 25-byte CJam solution that encoded the string in a non-straightforward way. Unfortunately, it looks like it'll never see the light of day. :-/

@Runer112 You and all your little rhymes / Still, I had this answer ~20 seconds before the 30-byte one chimed.

Round 2: Batch, 70 bytes
REM BATCHS
GOTO B
:C
ECHO ppuppPq([#fwSmdP[ppnvos"
GOTO A
:B
GOTO C
:A

Your quote was futile. D:>
Edit: it just occurred to me that I was going by file size instead of character count, not sure how bytes are to be counted :P

Edit 2: Added a comment to fill bytes. If you check byte count on a windows machine, just pretend the "REM BATCHS" is just "REM" I guess. :P

I'm counting bytes with gedit; it says your answer is 63. No worries; you're close enough to fill in the gap with comments.

Ah, alright cool, I'll just stick a comment in there.

@EMBLEM It's because the Windows newline is \r\n. There are 7 extra \rs there.

Round 2, ><>, 45 bytes
4 chars of comments.
'c(v\R"sovnpp[PdmSwf#[(qPppupp'01.uwyz
ol?!;

The string now contains both " and ', so ><> answers can't just surround it with either anymore (that's how I avoided any escapes).

Round 2, Mathematica, 40 bytes
Print@"ppuppPq([#fwSmdP[ppnvos\"R\\v(c'"

Yay second page!

Isn't the output missing a c?

@plannapus It was, fixed

Round 2, Golfscript, 35 bytes
"ppuppPq([#fwSmdP[ppnvos\"R\\v(c'P"

No waste bytes. Starts with a quote again!

7-bit ASCII won't work here, it only creates 28 bytes and includes an extra NUL

Someone cleverer than I will have to do it.. maybe there's some language encoded in 6 bits which can be run to produce the proper output..

No, 6 bits would create 24 bytes, but we need 30.

@LegionMammal978: Right, 24 bytes, then 8 six-bit instructions to print them or do whatever

Aren't we close to running into a limit here?

You're missing the apostrophe from 2 answers back

@14mRh4X0r An easy fix, though; Claudiu can just add the ' and remove the x.

Oops, guess I missed it twice. Thanks guys.

Would adding two unprintable characters count as cheating?

@Rodolvertice You can add them, but you shouldn't put them at the start of your code.

I meant as in using 7 bit ASCII and filling in the last 2 spaces with unprintables

@Rodolvertice No, then.

Python 3, 85 bytes
p1 = 'publ'
p2 = 'pre'
p3 = 'usi'
def cprint():
  print(p1[0], p2[0], p3[0])
cprint()

Round 2, C#, 95 bytes
namespace Cool{class Program{static void Main(){System.Console.Write("ppuppPq([#fwSmdP[pp");}}}

How about marking this "Round 2"?

Round 2: Javascript, 90 bytes

var p="p";alert(p+p+p+"u"+p+p+p.toUpperCase()+"q([#fwSmd"+p.toUpperCase()+"["+p+p+"n");//p

How about marking this "Round 2"?

The __, would fall under unnecessary variables.

Round 2, Javascript, 60 bytes
var _p="p";alert(_p.repeat(2)+"uppPq([#fwSmdP[ppnvos\"R\\");

I think that your __ would fall under unnecessary variables. Try changing p to a two-letter name and make the string double-quoted to add a backslash for the printed quote. That should compensate for the 3 chars you lost from removing the __,.

They didn't say not to use them. They said to use at most ten bytes of them.

It meant that you can use necessary variables of up to 10 bytes, but you can't use unnecessary variables altogether.

@Rainbolt You're interpreting it as "You can't use more than 10 bytes of (comments), (unnecessary variables), (filling the program with whitespace), or (variable names) longer than 10 bytes", but because of the second reference, I see it as "You can't use (more than 10 bytes of comments), (unnecessary variables), (filling the program with whitespace), or (variable names longer than 10 bytes)".

I've fixed the ambiguity. In the question, var __ is disallowed (not being used in the rest of the program), but renaming p would be acceptable.

Round 2, F# script, 55 bytes
(**)System.Console.Write(@"uppPq([#fwSmdP[ppnvos""R\v")

See my previous F# script anwer for why I think it is a valid language.

Round 2, R, 50 bytes
cat('ppuppPq([#fwSmdP[ppnvos\"R\\v(',file=stdout())

Round 2: Python, 85 bytes
os=['p']*8
os[4:6]=u'P'+r'q([#fwSmdP'
os[2:2]='u'
os[-2:-2]='['
print''.join(os)+'nv'

Starts with the fundamentals - the 'p's - and builds it up from there.

Prints ppuppPq([#fwSmdP[ppp, should be ppuppPq([#fwSmdP[ppnv

@EMBLEM: Oops, silly me. Thanks, fixed.

Round 2: VBS, 80 bytes
s = "ppuppPq([#fwSmdP[ppnvo" : For i=1 To 22 : WScript.Echo Mid(s ,i , 1) : Next

Left field language.

source: Stack Exchange

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

sort: votes


text:
ASCII L-system renderer
Background
An L-system (or Lindenmayer system) is a parallel rewriting system that, among other things, can be easily used to model fractals. This question concerns deterministic, context-free L-systems. These consists of an alphabet of symbols, an initial axiom string and a set of rewrite rules mapping each alphabet symbol to a new string. The rules are applied to the axiom in parallel, generating a new string. This process is then repeated.
For example, the system with the axiom "A" and the rules A=ABA;B=BBB generates the sequence of strings "ABA", "ABABBBABA", "ABABBBABABBBBBBBBBABABBBABA", etc. For conciseness, we don't explicitly mention the alphabet when defining the L-system. Furthermore, any symbol without an explicit rewrite rule is assumed to be unchanged (i.e. the default rule for a symbol A is A=A).
L-systems can be visualised using a form of turtle graphics. By convention, the turtle starts facing to the right. A string is then drawn by iterating over its symbols: an F means "draw forward one unit", a G means "move forward one unit", a + means "turn left one angle unit" and a - means "turn right one angle unit". All other symbols in the string are ignored. For the purpose of this question, the angle units are assumed to always be 90°.
Task
Given a specification of any L-system and a number of iterations, your program should output an ASCII rendering of the resulting string (as described above) using box-drawing characters.

The parameters are passed in as a space-separated string comprising the axiom, rewrite rules (as a ;-separated list of equations) and number of rewrite iterations. For example, the input "F F=FGF;G=GGG 2" generates the string "FGFGGGFGF" and hence draws four lines with appropriate gaps.
The symbols used by the L-system can be any ASCII character apart from space and semicolon. There is at most one explicit rule specified per symbol (with the default rewrite rule being the identity mapping as described above).
You can assume that the output will always contain at least one F.
The output should use the following UNICODE box-drawing characters to represent the visualization: ─ (U+2500), │ (U+2502), ┌ (U+250C), ┐ (U+2510), └ (U+2514), ┘ (U+2518), ├ (U+251C), ┤ (U+2524), ┬ (U+252C), ┴ (U+2534), ┼ (U+253C), ╴ (U+2574), ╵ (U+2575), ╶ (U+2576) and ╷ (U+2577). See below for examples.
The output should not contain empty lines above the topmost box character or below the bottommost one. It should also not contain any spaces to the left of the leftmost box characer or to the right of the rightmost one. Lines with trailing spaces that don't extend beyond the rightmost box character are allowed.

You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument. Results should be printed to STDOUT (or closest alternative), saved to a file or returned as a string.
Examples
# Cantor dust
>> "F F=FGF;G=GGG 0"
╶╴
>> "F F=FGF;G=GGG 1"
╶╴╶╴
>> "F F=FGF;G=GGG 2"
╶╴╶╴  ╶╴╶╴
>> "F F=FGF;G=GGG 3"
╶╴╶╴  ╶╴╶╴        ╶╴╶╴  ╶╴╶╴

# Koch curve
>> "F F=F+F−F−F+F 1"
 ┌┐
╶┘└╴
>> "F F=F+F-F-F+F 2"
    ┌┐
   ┌┘└┐
  ┌┘  └┐
 ┌┼┐  ┌┼┐
╶┘└┘  └┘└╴

Other examples to test your program with include:
# Dragon curve
>> "FX X=X+YF+;Y=-FX-Y n"

# Hilbert curve
>> "A A=-BF+AFA+FB-;B=+AF-BFB-FA+ n"

# Sierpinski carpet
>> "F F=F+F-F-F-G+F+F+F-F;G=GGG n"

The first two of which look as follows (produced using @edc65's answer):

You can test out any of the systems at this page.
Scoring
Shortest code (in bytes) wins. Standard rules apply.
Miscellania
This challenge was inspired by Draw a Random Walk with Slashes. In fact, it's possible to represent a random walk as an L-system if we extend the system to allow multiple rules per symbol, with the expansion chosen non-determistically during rewriting. One formulation is:
"F F=FF;F=F+F;F=F++F;F=F+++F"

Another common extension, often used when modeling plants, is to interpret the [ and ] characters as pushing and popping the current position and angle. Most plants use angles smaller than 90°, but here is one example that doesn't:
"FAX X=[-FAX][FAX][+FAX];A=AFB;B=A"

Neither of these examples need to be supported in this challenge.
This challenge is also similar to "Sorry, young man, but it's Turtles all the way down!". However, that challenge used line rendering rather than ASCII and allowed a more flexible syntax.

JavaScript (ES6), 440 bytes (410 chars)
F=p=>([a,r,n]=p.split(' '),t=>{r.split(';').map(x=>r[x[0]]=x.slice(2),r={});for(;n--;)a=[...a].map(c=>r[c]||c).join('');u=x=y=0,g=[];for(c of a)c=='+'?[t,u]=[u,-t]:c=='-'?[u,t]=[t,-u]:c<'F'|c>'G'?0:((y+=u)<0?(g=[[],...g],++y):g[y]=g[y]||[],(x+=t)<0?(g=g.map(r=>[,...r]),++x):0,c>'F'?0:g[g[f=t?0.5:2,y][x]|=(3+t-u)*f,y-u][x-t]|=(3+u-t)*f)})(1)||g.map(r=>[for(c of r)' ╶╴─╵└┘┴╷┌┐┬│├┤┼'[~~c]].join('')).join('\n')

Less golfed
F=p=>{
  [a,r,n]=p.split(' '),
  r.split(';').map(x=>r[x[0]]=x.slice(2),r={}); // set rules
  for(;n--;)a=[...a].map(c=>r[c]||c).join(''); // build string
  t=1,u=x=y=0, // start pos 0,0 start direction 1,0
  g=[[]]; // rendering in bitmap g
  for(c of a)
    c=='+'?[t,u]=[u,-t] // left turn
    :c=='-'?[u,t]=[t,-u] // right turn
    :c=='F'|c=='G'?(     // move or draw
      (y+=u)<0?(g=[[],...g],++y):g[y]=g[y]||[], // move vertical, enlarge grid if needed
      (x+=t)<0?(g=g.map(r=>[,...r]),++x):0, // move horizontal, enlarge grid if needed
      c=='F'&&( // draw: set bits
        f=t?0.5:2,
        g[y][x]|=(3+t-u)*f,
        g[y-u][x-t]|=(3+u-t)*f
      )
    ):0;
  // render bits as box characters
  return g.map(r=>[' ╶╴─╵└┘┴╷┌┐┬│├┤┼'[~~c]for(c of r)].join('')).join('\n')
}

Test Code snippet to test (in Firefox)

F=p=>([a,r,n]=p.split(' '),t=>{r.split(';').map(x=>r[x[0]]=x.slice(2),r={});for(;n--;)a=[...a].map(c=>r[c]||c).join('');u=x=y=0,g=[];for(c of a)c=='+'?[t,u]=[u,-t]:c=='-'?[u,t]=[t,-u]:c<'F'|c>'G'?0:((y+=u)<0?(g=[[],...g],++y):g[y]=g[y]||[],(x+=t)<0?(g=g.map(r=>[,...r]),++x):0,c>'F'?0:g[g[f=t?0.5:2,y][x]|=(3+t-u)*f,y-u][x-t]|=(3+u-t)*f)})(1)||g.map(r=>[for(c of r)' ╶╴─╵└┘┴╷┌┐┬│├┤┼'[~~c]].join('')).join('\n')

fs=18;(Z=d=>(Result.style.fontSize=(fs+=d)+'px',Result.style.lineHeight=fs+'px'))(0)
#Result { font-size: 10px }
#Param { width: 400px }
Param: <input type=text id=Param />
<button onclick="Result.innerHTML=F(Param.value)">Start</button>

Output <button onclick="Z(-2)">Z-</button> <button onclick="Z(2)">Z+</button>

Great (and quick!) answer. I've added screenshots of the dragon and hilbert curve outputs to the question.

Haskell, 568 bytes
import Data.List.Split
p=splitOn
l=lookup
m=maximum
n=minimum
o[h,x]=(h,x)
Just x#_=x
_#x=x
g[s,r,i]=iterate((\c->lookup[c](map(o.p"=")(p";"r))#[c])=<<)s!!read i
u v@(a,x,y,d,e)c|c=='+'=(a,x,y,-e,d)|c=='-'=(a,x,y,e,-d)|c=='G'=(a,x+d,y+e,d,e)|c=='F'=(s(x,y)(d%e)a:s(x+d,y+e)(d?e)a:a,x+d,y+e,d,e)|1<2=v
s p n a=(p,n+(l p a)#0)
1%0=2;0%1=8;-1%0=1;0%(-1)=4
1?0=1;0?1=4;-1?0=2;0?(-1)=8
f z=unlines[[" ╴╶─╷┐┌┬╵┘└┴│┤├┼"!!(l(x,y)q#0)|x<-[n a..m a]]|y<-[m b,m b-1..n b]]where a=map(fst.fst)q;b=map(snd.fst)q;(q,_,_,_,_)=foldl u([],0,0,1,0)$g$p" "z

Test run:
*Main> putStr $ f "F F=F-F+F+F-F 3"
╶┐┌┐  ┌┐┌┐        ┌┐┌┐  ┌┐┌╴
 └┼┘  └┼┼┘        └┼┼┘  └┼┘
  └┐  ┌┼┼┐        ┌┼┼┐  ┌┘
   └┐┌┼┘└┘        └┘└┼┐┌┘
    └┼┘              └┼┘
     └┐              ┌┘
      └┐┌┐        ┌┐┌┘
       └┼┘        └┼┘
        └┐        ┌┘
         └┐┌┐  ┌┐┌┘
          └┼┘  └┼┘
           └┐  ┌┘
            └┐┌┘
             └┘

How it works:

rewriting (function g): I parse the rules into an association list (letter -> replacement string) and repeatedly map it over the axiom.
creating the path (function u for a single step): I do not store the path in a matrix but in another association list with (x,y) positions as the keys and bit patterns of the 4 basic blocks (╴,╶,╷ and ╵) as values. Along the way I keep track of the current position and direction.
drawing the path (function f): first I calculate the max/min dimensions from the path list and then I iterate over [max y -> min y] and [min x -> max x] and lookup the blocks to draw.

ES7, 394 chars, 424 bytes
F=p=>([a,r,n]=p.split` `,t=>{r.split`;`.map(x=>r[x[0]]=x.slice(2),r={});for(;n--;)a=[...a].map(c=>r[c]||c).join``;u=x=y=0,g=[];for(c of a)c=='+'||c=='-'?[t,u]=[u,-t]:c<'F'|c>'G'?0:((y+=u)<0?(g=[[],...g],++y):g[y]=g[y]||[],(x+=t)<0?(g=g.map(r=>[,...r]),++x):0,c>'F'?0:g[g[f=t?0.5:2,y][x]|=(3+t-u)*f,y-u][x-t]|=(3+u-t)*f)})(1)||g.map(r=>[for(c of r)'╶╴─╵└┘┴╷┌┐┬│├┤┼'[~~c]].join``).join`
`

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


text:
Generate a pair of integers from a non-negative one
You should write a program or function which takes a non-negative integer N as input and outputs or returns two integers (negative, zero or positive) X and Y.
Integers are meant in the mathematical sense as there are infinitely many of them.
The implemented function has to be bijective. This means that for every N it has to output a different X Y pair and every X Y pair should be outputted for some input N i.e. all of the following pairs should be outputted for some N:
                 ...
    ┌─────┬─────┬────┬────┬────┐
    │-2 -2│-2 -1│-2 0│-2 1│-2 2│
    ├─────┼─────┼────┼────┼────┤
    │-1 -2│-1 -1│-1 0│-1 1│-1 2│
    ├─────┼─────┼────┼────┼────┤
... │0 -2 │0 -1 │0 0 │0 1 │0 2 │ ...
    ├─────┼─────┼────┼────┼────┤
    │1 -2 │1 -1 │1 0 │1 1 │1 2 │
    ├─────┼─────┼────┼────┼────┤
    │2 -2 │2 -1 │2 0 │2 1 │2 2 │
    └─────┴─────┴────┴────┴────┘
                 ...

Note that U V and V U are different pairs if U!=V.
Details

If your language doesn't support arbitrarily large integers that's fine but your algorithm should work with an arbitrarily large integer data-type. Your code should still support input values for at least 2^31-1.
If you choose to print or return the output as string no leading 0's or + signs are allowed. Otherwise your language's standard integer representation is fine.

Example
If the task would be to make a bijective function taking a non-negative integer N and output one integer X a solution could be the function
if (input mod 2 == 0) return N/2 else return -(N+1)/2,
implemented in some language. This function returns X = 0 -1 1 -2 2... for N = 0 1 2 3 4....

Can any of the integers in the output be repeated for different input? e. g. 10=>11 12, 9=>10 11 is this invalid because 11 is repeated?

As far as "bijective" is defined "11 12" not the same as "10 11" and therefore valid. This is because a bijective function is defined as a function "where every element of one set is paired with exactly one element of the other set, and every element of the other set is paired with exactly one element of the first set. There are no unpaired elements."(http://en.wikipedia.org/wiki/Bijection). If you were to inverse your function "11 12" should output 10 and "10 11" should output 9.

@BrainSteel Your example is valid. Only the (ordered) pairs can't be repeated. GiantTree is correct. Added some more explanation to the question.

Does it have to be a bijection within the integer range of the given language or should it work for all integers?

@flawr You can't do a bijection in a fixed range as the two sets will be of different size. Your algorithm should work for all integers using it on a proper datatype (see the first point of the Details section).

@LegionMammal had a good mathematical description of the task:  "You need to define a bijective function $f:N+→Z^2$. –  LegionMammal978."  that I think would be beneficial somewhere in the statement

@BrianJ It was more like $f:\mathbb{N}^+\rightarrow\mathbb{Z}^2$ = $f:\mathbb{N}^+\rightarrow\mathbb{Z}^2$.

@LegionMammal978 thanks! I couldn't see the markdown to copy directly.

Pyth, 15
u,-HyeGhGjQ2,ZZ

Try it online.
u             reduce
                lambda G,H:    [implicit]
  ,-HyeGhG         (H-2*G[-1],G[0])
  jQ2           base(input(),2)
  ,ZZ           (0,0)
              print result     [implicit]

A Python translation:
g=lambda Z,n:(n-2*Z[1],Z[0])
print reduce(g,binlist(input()),(0,0))

or iteratively:
(x,y)=(0,0)
for b in binlist(input()):
    (x,y)=(b-2*y,x)
print (x,y)

where binlist converts a number to a list of digits like binlist(4) = [1,0,0].
So, how does this work? It interprets the binary digits of the number \$n\$ as two interleaved numbers in base negative two like in my Python solution.
The binary number $$n=\dots b_5 b_4 b_3 b_2 b_1 b_0 $$ corresponds to the pair $$ (x,y) = (b_0 - 2 b_2 + 4 b_4 - 8 b_6 + \cdots, b_1 - 2 b_3 + 4 b_5 - 8 b_7 + \cdots).$$
If we hadn't yet processed the last digit \$b_0\$ of \$n\$, we'd have all indices higher by $1$, $$n'=\dots b_5 b_4 b_3 b_2 b_1 $$ corresponding to the pair $$ (x',y') = (b_1 - 2 b_3 + 4 b_5 - 8 b_7 + \cdots, b_2 - 2 b_4 + 4 b_6 - 8 b_8 + \cdots).$$
We can then express the new values once \$b_0\$ is read in terms of the old values
$$(x,y) = (b_0 - 2y', x').$$
So, by repeatedly performing the transformation \$(x,y) \to (b - 2y, x)\$ on each successive bit \$b\$ of \$n\$, we build the point \$(x,y)\$ that comes from extracting its digits.

CJam, 24 22 21 bytes
My brain has trouble understanding the math other solutions are using. But my brain definitely understands binary, so here's a soultion based on bit manipulation!
li4b2fmd2/z{)(\2b^}%p

Try it online.
Explanation
This approach treats the input as two interleaved binary values, one for each output number. All but the least significant bit of each encode a magnitude, and the least significant bit signals whether or not to take the bitwise complement of this magnitude. In this implementation, the odd-positioned bits correspond to the first output number (and the even-positioned bits correspond to the second) and an LSB of 0 signals to take the complement.
For example, given an input of 73, uninterleaving its binary representation of 1001001b produces 0 1|0 (odd-positioned bits) and 1 0 0|1 (even-positioned bits). The first value has a magnitude of 01b = 1 and should be complemented for a final value of ~1 = -2, and the second value has a magnitude of 100b = 4 and should not be complemented.
Informal demonstration of correctness
I made a testing program that places each input from zero to a user-specified number minus one in its output location on a 2D grid. You can try it online as well. Here's an output of this program showing how the algorithm maps 0-99:
      -8 -7 -6 -5 -4 -3 -2 -1  0  1  2  3  4  5  6  7  8

-8                      92 84 86 94
-7                      88 80 82 90
-6                      76 68 70 78
-5                   96 72 64 66 74 98
-4                60 52 28 20 22 30 54 62
-3                56 48 24 16 18 26 50 58
-2                44 36 12  4  6 14 38 46
-1                40 32  8  0  2 10 34 42
 0                41 33  9  1  3 11 35 43
 1                45 37 13  5  7 15 39 47
 2                57 49 25 17 19 27 51 59
 3                61 53 29 21 23 31 55 63
 4                   97 73 65 67 75 99
 5                      77 69 71 79
 6                      89 81 83 91
 7                      93 85 87 95
 8

The fill pattern looks a bit weird, but it is in fact bijective! With each successive power of 4, it fills a square with double the previous side length. For example, here's how the algorithm maps 0-15:
      -2 -1  0  1  2

-2    12  4  6 14
-1     8  0  2 10
 0     9  1  3 11
 1    13  5  7 15
 2

This makes up the 4x4 square in the middle of the 8x8 square of 0-63:
      -4 -3 -2 -1  0  1  2  3  4

-4    60 52 28 20 22 30 54 62
-3    56 48 24 16 18 26 50 58
-2    44 36 12  4  6 14 38 46
-1    40 32  8  0  2 10 34 42
 0    41 33  9  1  3 11 35 43
 1    45 37 13  5  7 15 39 47
 2    57 49 25 17 19 27 51 59
 3    61 53 29 21 23 31 55 63
 4

Which makes up the 8x8 square in the middle of the 16x16 square of 0-255:
         -8  -7  -6  -5  -4  -3  -2  -1   0   1   2   3   4   5   6   7   8

 -8     252 244 220 212 124 116  92  84  86  94 118 126 214 222 246 254
 -7     248 240 216 208 120 112  88  80  82  90 114 122 210 218 242 250
 -6     236 228 204 196 108 100  76  68  70  78 102 110 198 206 230 238
 -5     232 224 200 192 104  96  72  64  66  74  98 106 194 202 226 234
 -4     188 180 156 148  60  52  28  20  22  30  54  62 150 158 182 190
 -3     184 176 152 144  56  48  24  16  18  26  50  58 146 154 178 186
 -2     172 164 140 132  44  36  12   4   6  14  38  46 134 142 166 174
 -1     168 160 136 128  40  32   8   0   2  10  34  42 130 138 162 170
  0     169 161 137 129  41  33   9   1   3  11  35  43 131 139 163 171
  1     173 165 141 133  45  37  13   5   7  15  39  47 135 143 167 175
  2     185 177 153 145  57  49  25  17  19  27  51  59 147 155 179 187
  3     189 181 157 149  61  53  29  21  23  31  55  63 151 159 183 191
  4     233 225 201 193 105  97  73  65  67  75  99 107 195 203 227 235
  5     237 229 205 197 109 101  77  69  71  79 103 111 199 207 231 239
  6     249 241 217 209 121 113  89  81  83  91 115 123 211 219 243 251
  7     253 245 221 213 125 117  93  85  87  95 119 127 215 223 247 255
  8

Very clever! You can save two bytes by using li4b2fmd2/ instead of 0li2b+W%2/W%. This gives the same integers, but in reversed order.

@Dennis That's also very clever. I've updated the answer to use that trick. Thanks!

Python 2, 49
Edit: Improved to 49 by using better one-step recursion for base -2.
def f(n):x,y=n and f(n/2)or(0,0);return n%2-2*y,x

Here's a Pyth version using reduce.
Edit: Improved to 52 by switching to base -2 from balanced ternary.
Python 2, 52
h=lambda n:n and n%2-2*h(n/4)
lambda n:(h(n),h(n/2))

Python 2, 54
h=lambda n:n and-~n%3-1+3*h(n/9)
lambda n:(h(n),h(n/3))

This uses digit interleaving like Runer112's solution, but with balanced ternary rather than signed binary. Python doesn't have built-in base conversion, so the code implements it recursively.
The helper function h (with 3 in place of the 9) takes a natural number and converts it from ternary to balanced ternary with the digit substitutions
0 -> 0
1 -> +1
2 -> -1

So, for example, 19, which is 201 in base, becomes (-1)(0)(+1) in balanced ternary, which is (-1)*3^2 +(0)*3^1+(+1)*3^0 = -8.
Balanced ternary suffices to encode every integer, and so gives a mapping from natural numbers to integers.
To map to pairs of integers, we interleave the digits in n. To do so, we have h look at every other digit by doing n/9 as the recursive step rather than n/3. Then, for one coordinate, we shift n by floor-dividing by 3.
Here are the first 81 outputs, which cover the region [-4,4]^2.
0 (0, 0)
1 (1, 0)
2 (-1, 0)
3 (0, 1)
4 (1, 1)
5 (-1, 1)
6 (0, -1)
7 (1, -1)
8 (-1, -1)
9 (3, 0)
10 (4, 0)
11 (2, 0)
12 (3, 1)
13 (4, 1)
14 (2, 1)
15 (3, -1)
16 (4, -1)
17 (2, -1)
18 (-3, 0)
19 (-2, 0)
20 (-4, 0)
21 (-3, 1)
22 (-2, 1)
23 (-4, 1)
24 (-3, -1)
25 (-2, -1)
26 (-4, -1)
27 (0, 3)
28 (1, 3)
29 (-1, 3)
30 (0, 4)
31 (1, 4)
32 (-1, 4)
33 (0, 2)
34 (1, 2)
35 (-1, 2)
36 (3, 3)
37 (4, 3)
38 (2, 3)
39 (3, 4)
40 (4, 4)
41 (2, 4)
42 (3, 2)
43 (4, 2)
44 (2, 2)
45 (-3, 3)
46 (-2, 3)
47 (-4, 3)
48 (-3, 4)
49 (-2, 4)
50 (-4, 4)
51 (-3, 2)
52 (-2, 2)
53 (-4, 2)
54 (0, -3)
55 (1, -3)
56 (-1, -3)
57 (0, -2)
58 (1, -2)
59 (-1, -2)
60 (0, -4)
61 (1, -4)
62 (-1, -4)
63 (3, -3)
64 (4, -3)
65 (2, -3)
66 (3, -2)
67 (4, -2)
68 (2, -2)
69 (3, -4)
70 (4, -4)
71 (2, -4)
72 (-3, -3)
73 (-2, -3)
74 (-4, -3)
75 (-3, -2)
76 (-2, -2)
77 (-4, -2)
78 (-3, -4)
79 (-2, -4)
80 (-4, -4)

An alternative coding with quarter-imaginary turned out longer, though it is very pretty.
Python 2, 63
h=lambda n:n and n%4+2j*h(n/4)
lambda n:(h(n).real,h(n).imag/2)

In a language with less clunky handling of complex conversion, this would probably be a better approach. If we could output complex numbers, we could do:
Python 2, 38
f=lambda n:n and n%2+n/2%2*1j-2*f(n/4)

Your original base -2 function would make a mean Pyth answer. L&b-%b2*2y/b4,yQy/Q2 is only 20 bytes long.

@Dennis I just wrote a 15-char Pyth solution.

Balanced Ternary and Quarter-imaginary.  Two of my favorite bases.  Followed only by Base-e.

Python 2, 98 bytes
Let's start out with a simple approach:
def f(N):
 x=a=0;b=2
 while N:x+=1j**b;b+=a<1;a=a or b/2;N-=1;a-=1
 return int(x.real),int(x.imag)

It just forms a rectangular spiral N units long on a 2d grid, starting from the origin, and returns the coordinates of the last point.
The function is bijective since:

Each point can be covered, given a long enough spiral
Each point will only be intersected by the spiral once

The spiral looks something like this (except starting at 0 rather than 1):

@AlexA. 0**0 == 1 in python, so it's just the same as if a == 0: a = b/2

Cool, thanks for explaining.

@AlexA. turns out a=a or b/2 is shorter

@grc 0^0=1 in all math, not just python.

@Daenyth 0**0 is actually indeterminate form in maths

This is quite a cool solution, I like the elegance.

dc, 49
[1+2~2*1-*n]sm?dsa8*1+v1-2/dd1+*2/lar-dlmx32P-lmx

This starts off by arranging the non-negative integers on a grid thus:
..|
4 | 14
3 |  9 13
2 |  5  8 12
1 |  2  4  7 11
0 |  0  1  3  6 10
Y +-----------------
  X  0  1  2  3  4 ...

Note that how the grid positions are filled diagonally with increasing N.  Notice the Y=0 line contains the triangular number sequence, given by N = X(X+1)/2.  This is a quadratic equation which is solved using the normal formula, using just the +ve root, so that we can determine X from N when Y=0.  Next is some simple arithmetic shuffling to give unique {X,Y} for every N.
This provides the required bijective quality, but X and Y are only non-negative, but the question requires all possible integers.  So X and Y are mapped using ((t+1)/2)*((t+1)~2*2-1) to give all possible integers.
dc has arbitrary precision numbers, so input range to 2^31-1 is no problem.  Note also that default precision is 0 decimal digits, and the sqrt() and / round down which is the behavior needed here.
Output:
$ for i in {0..10}; do dc biject.dc <<< $i; echo; done
0 0
0 -1
-1 0
0 1
-1 -1
1 0
0 -2
-1 1
1 -1
-2 0
0 2
$

Matlab, 54 bytes
n=input('')+1;[i,j]=find(spiral(2*n)==n);disp([i,j]-n)

The key here is spiral, this creates a spiral matrix of an arbitrary size.
spiral(3)

returns
ans =

 7     8     9
 6     1     2
 5     4     3

In Matlab, this works for integers, but you will get memory issues way before that, (well, I am assuming you  as the command spiral creates a full matrix first, that has size of about \$4n^2\$. At around \$n \simeq 10^4\$ this matrix takes up more than 1GB of space. So with 1TB of RAM you will get to around \$n \simeq 10^5\$, and about \$2.9\cdot 10^{11}\$ GB  of RAM will get you to \$n=2^{32}\$.

K (ngn/k), 12 bytes
-2/+2 2\0,4\

Attempt This Online! (ATO because the original ngn/k page isn't working at the time of posting)
Uses bit halving followed by base -2. 0, is necessary to get 0 0 for input 0.
-2/+2 2\0,4\
          4\    convert to base 4
        0,      prepend a 0
    2 2\        convert each to base 2, forcing two bits per a base-4 digit
                (base conversion happens column-wise, so the result here is
                 a two-row matrix)
   +            transpose
-2/             evaluate each column in base -2

Neat!  I had a vague notion to try a Hilbert curve but wouldn’t have thought to use base -2.

K (ngn/k), 72 68 66 62 53 bytes
{(-|:)/[0<d;0,d:m*x-1+s*s-1]+(m:*/s#-1)*2#-2!s:-_-%x}

Try it online!
-4 : Squeezed out a few bytes
-2 : A couple more
-4 : Oh yeah, we’re golfing…
-9 : Forgot ngn/k has sqrt

More fun but a byte longer: f:{((0<d)(-|:)/0,d:m*x-1+s*s-1)+(m:*/s#-1)*2#-2!s:(x>*/2#)(1+)/1}

At least no worse: f:{(-|:)/[0<d;0,d:m*x-1+s*s-1]+(m:*/s#-1)*2#-2!s:(x>*/2#)(1+)/1}

J, 11 bytes
_1j1+.@#.#:

Attempt This Online!
Uses complex base -1 + i to generate a Gaussian integer from the binary representation of the given nonnegative integer.
_1j1+.@#.#:
         #:  Convert to binary
_1j1   #.    Evaluate the binary sequence as base -1 + i
    +.@      Take apart its real and imaginary parts

If outputting a complex number were allowed, it would be 8 bytes (delete +.@).
I couldn't find a complete proof that this conversion is bijective, but this challenge mentions it, and I think the following argument is enough to prove it:

Given a Gaussian integer, the lowest bit of base -1 + i representation is determined by (real+imag)%2. Subtract it and divide by -1 + i, and you always get another Gaussian integer with smaller magnitude (at least until it becomes small enough, at which point the proof can be done individually). This conversion algorithm is deterministic and finite, and defines an inverse of conversion from binary to Gaussian using base -1 + i.

Haskell, 78 74 bytes
(concat[[(x,i-x),(x,x-1-i),(-1-x,x-1-i),(-1-x,i-x)]|i<-[0..],x<-[0..i]]!!)

Test run:
*Main> mapM_ (print . (concat[[(x,i-x),(x,x-1-i),(-1-x,x-1-i),(-1-x,i-x)]|i<-[0..],x<-[0..i]]!!) ) [0..20]
(0,0)
(0,-1)
(-1,-1)
(-1,0)
(0,1)
(0,-2)
(-1,-2)
(-1,1)
(1,0)
(1,-1)
(-2,-1)
(-2,0)
(0,2)
(0,-3)
(-1,-3)
(-1,2)
(1,1)
(1,-2)
(-2,-2)
(-2,1)
(2,0)

How it works: list all pairs in the first quadrant in the following order
  |
 2| #4
  |
 1| #2  #5
  |
 0| #1  #3  #6
  +---------------
     0   1   2   3

mirror each point into the other quadrants to make a list of 4 element lists. Concatenate all into a single list and take the nth element.
Edit: function doesn't need a name, reordered math. expressions.

You can save 4 bytes by using do-notation: Try it online!

05AB1E, 35 bytes
>©DÝʒo®sÖ}àsÅÉʒ®sÖ}à<2÷‚εDÈi2÷ë>2÷(

Try it online! or as Test suite
Explanation
Consider
$$\begin{align*}
f: \mathbb{N} &\longrightarrow \mathbb{N} \times \mathbb{N} \\
n&\longmapsto (x,y)\, ,
\end{align*}
$$
where \$x\$ is the largest number so that \$2^x\$ divides \$n+1\$, and where \$2y+1\$ is the largest odd number which divides \$n+1\$. The inverse of \$f\$ is the well-known bijection \$f^{-1}(x,y) = 2^x(2y+1)-1\$.
Then consider
$$\begin{align*}
g: \mathbb{N} \times \mathbb{N} &\longrightarrow \mathbb{Z} \times \mathbb{Z} \\
(m,n)&\longmapsto (h(m),h(n))\, ,
\end{align*}
$$
where
$$\begin{align*}
h: \mathbb{N}  &\longrightarrow \mathbb{Z} \\
n&\longmapsto \begin{cases}\frac n2, & n \text{ even}\\ -\frac{n+1}2, & n \text{ odd}\end{cases}\, .
\end{align*}
$$
Since \$f\$, \$g\$ and \$h\$ all are bijections, the composition \$g\circ f:\mathbb{N} \longrightarrow \mathbb{Z} \times \mathbb{Z}\$ is a bijection.
The program simply computes \$g\circ f\$.
>©DÝʒo®sÖ}àsÅÉʒ®sÖ}à<2÷‚εDÈi2÷ë>2÷( # Full program

                                    # Implicit input: Integer n
>©                                  # Compute n+1 and save it to the register
  DÝ                                # Duplicate n+1 and push the list [0,...,n+1]
    ʒo®sÖ}                          # Only keep those numbers x so that 2^x divides n+1
          à                         # Get maximum element in the list.
           sÅÉ                      # Swap so that n+1 is on top and push [1,3,5,...,n+1]
              ʒ®sÖ}                 # Only keep those numbers z which divides n+1
                   à<2÷             # Compute y = (z-1)/2
                       ‚            # Push the pair [x,y]
                        ε           # Apply the function h to x (and y):
                           i        # if...
                         DÈ         # x is even
                            2÷      # then compute x/2
                              ë>2÷( # else compute -(x+1)/2
                                    # Implicit output: [h(x),h(y)]

wow, upvoted for the nice explanation. but surely 05AB1E should be able to beat Pyth?

Thanks :) Can for sure be improved, but will probably have to use another approach rather than computing $g\circ f$. Can probably golf it a bit lower, but probably not by very much I suspect

JavaScript, 166 168 bytes/characters
New approach using a rectangular spiral like others are using.
function f(n){return b=Math,k=b.ceil((b.sqrt(n)-1)/2),t=2*k+1,m=b.pow(t,2),t+=4,m-t>n?(m-=t,m-t>n?(m-=t,m-t>n?[k,k-(m-n-t)]:[-k+(m-n),k]):[-k,-k+(m-n)]):[k-(m-n),-k]}

I used this answer on Math.SE, translated it to JS and compressed it using UglifyJS.
This approach does not use any loops nor does it create the spiral in any way.
Because the spiral's coordinates cover all integers the function is bijective in the sense of \$f:\mathbb{N}^0\rightarrow \mathbb{Z}^2\$.
Update:
Saved 2 characters by storing Math in b.
Update 2:
Replaced t-=1 with t+=4 to fix the issue that caused \$f(0)=f(8)\$. This does not generate a spiral anymore but works for all non-negative integers \$\mathbb{N}^0\$ (all natural numbers including \$0\$).

Reposting the exact same question won't really help. 2) Copying another answer and then using a minifier for golfing won't too :)

At least it follows all the rules stated in the question and it's a different approach. Also I am not stealing another one's work, but I refer to it on how I made this answer.

@Optimizer: 1) I suggested GiantTree should repost since he got 3 (deserving) downvotes for his original, invalid approach. 2) The code he took from Math.SE isn't even JavaScript, so he did more than just copying it in a minifier.

@Dennis people can retract their downvote, you know. Also, using a minifier to minify code is not really encouraged imo.

@Optimizer I tried to golf the code, but using a compressor led to a better result (less characters) so I used that one instead.

@Optimizer: People can do a lot of things. But since the edit doesn't notify them, three downvoters coming back to revert their vote is highly unlikely. The minifier didn't do a very good job anyway. There are a lot of unneeded brackets, Math could be saved in a variable, etc.

I will update the answer with a little bit more golfed version in a moment. Is that ok?

Golfing personally always helps.

N+ is every integer > 0 ? Try again, the question is about non-negative integers and f(0)==f(8).

@edc65 I fixed it and changed $N^+$ (the definition before) to $N^0$ (the correct definition of all non-negative integers including $0$).

now f(71)==f(150) ... why try random changes, it was off by 1, it was simple to fix ... function F(n){return n<(m=(t=2*(k=Math.ceil((Math.sqrt(++n)-1)/2)))*t+1)+t?n<m?n<m-t?[k,m-n-t-k]:[m-n-k,-k]:[-k,n-m-k]:[n-m-t-k,k]} 126

@edc65 Thanks for your improvement on my submission. I see what you did there. You increment n so that it works again because the function itself is defined for $N^+$ only. Shifting the input up by one fixes this issue. You also connected the variable declarations because they return the value assigned to a variable so it can be used in another declaration, I didn't know this was possible. Another improvement you did was moving t around so that there is no need to subtract it every time it's compared to n, removing the need of all the parentheses.

@edc65 I have an issue with your script. Technically it looks good and I learned something form comparing it to mine, but your script fails to generate pairs for the top part of the spiral. I always get the error: Reference error: n is not defined.

I'm using FireFox and no error. Using this to test g=[],o=10;for(i=0;i<o*o*4;i++)[x,y]=F(i),g[y+o]=g[y+o]||[],g[y+o][x+o]=i;g.map(r=>r.map(c=>('  '+c).slice(-3))).join('\n')

But check for invisible characters added by the editor formatter! Rats! Try http://jsfiddle.net/c40y9ynj/

@edc65 it works now. There was an invisible character that only appeared in the stacktrace. It was somewhere between n and a space.

Haskell, 50 bytes
(0!).succ
l!n=(last$(!).succ:[(,)|odd n])l$div n 2

Try it online or try it with its inverse!
Ungolfed
ntoN2 n = 0 ! (n + 1)

xCounter ! remainingNum
  | odd remainingNum = (xCounter, div remainingNum 2)
  | otherwise        = (xCounter + 1) ! div remainingNum 2

Explanation
This uses the fact that each \$(x,y) \in \mathbb{N}^2\$ can be 1-to-1 mapped to \$2^x \cdot (2\cdot y + 1) - 1 \in \mathbb{N}\$. The above operator (!) computes \$x\$ by dividing the input as long as it's even, keeping track with the zero-initialized variable l (xCounter). Once we reached the even number an integer division computes y.
Note that the actual function f (ntoN2) increments the input before starting with the procedure.

Vyxal, 5 bytes
Þn:Ẋi

Try it Online!
Þn    # All integers
  :Ẋ  # Cartesian product with self
    i # Index input into that

JavaScript, 77 70 bytes
Z=x=>(x&1n?x:-x)/2n
f=(x,y=1n)=>++x&1n?[Z(++x/2n),Z(y)]:f(x/2n-1n,++y)

Takes a BigInt as Input.
Attempt This Online!
First few values:
f(0n)=[0n,0n]
f(1n)=[0n,-1n]
f(2n)=[-1n,0n]
f(3n)=[0n,1n]
f(4n)=[1n,0n]
f(5n)=[-1n,-1n]
...

Explanation:
Uses more or less the same algorithm as Wislaw's solution:
Z is the standard bijection from the positive integers to the integers.
f computes positive integers k and m with x+1=2^(k-1)*(2m-1)
(which is a bijection \$\mathbb{N} \to \mathbb{N}_{>0} \times \mathbb{N}_{>0}\$ by the uniqueness of prime factorizations) and then outputs the pair Z(m),Z(k)

JavaScript, 65 bytes
bijection \$\mathbb{N}_{>0} \to \mathbb{Z} \times \mathbb{Z}\$
Z=x=>(x&1n?x:-x)/2n
f=(x,y=1n)=>x&1n?[Z(++x/2n),Z(y)]:f(x/2n,++y)

Attempt This Online!

JavaScript (Node.js), 48 bytes
f=(x,y)=>x&1?f(x/2,-~y):[x/2,y].map(t=>t/2^-t%2)

Attempt This Online!

Scala, 79 bytes
Port of @ბიმო's Haskell answer in Scala.

Golfed version. Try it online!
n=>for{i<-0 to n;x<-0 to i}yield Seq((x,i-x),(x,x-1-i),(-1-x,x-1-i),(-1-x,i-x))

Ungolfed version. Try it online!
object Main {
  def main(args: Array[String]): Unit = {
    val result = for {
      i <- 0 to 20
      x <- 0 to i
    } yield List((x, i - x), (x, x - 1 - i), (-1 - x, x - 1 - i), (-1 - x, i - x))

    result.flatten.zipWithIndex.take(21).foreach {
      case (tuple, index) => println(s"$index: $tuple")
    }
  }
}

Mathematica, 46
SortBy[Tuples[Range[2#]-#,2],Norm][[#]]&[#+1]&

Sort the vectors their norm, then take the nth one.

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


text:
Write a program that takes as close to 1 second sharp to execute in your language
Write a program that takes as close to 1 second Wall-time sharp to execute in your language.
Anything goes except to have the processor sleep / pause / wait, by either internal or relying on external processes.
It should be interesting to see that adding one character more somewhere will more easily bring you to the correct time (though obviously at the cost of a character). Think for example to have a for loop run 10000 instead of 1000 times which "costs" 1 character.
Execution time will be measured online by ideone.
I guess for an "official time", I'll run a benchmark of say 100 times. Next to a low amount of characters and close to 1.000 seconds, low variance should also earn you street creds.
It might actually be fun to come up with an idea for how much "worth" a character gets in terms of getting closer to 5.00 seconds.
Measures:

abs(5 - execution_time) (lower better)
Number of characters (lower better)
Variability (lower better)
Cleverness (higher better)
Fun (higher better)

Changed it to 1 second (from 5); don't want to torture people.

Execution times for a program can vary significantly depending upon the build and/or execution environments. Making code take a specific amount of time with any degree of accuracy requires waiting based on a time source, but the challenge currently disallows this. It seems to me that this is either an unsolvable problem in its current form or a trivially solvable one with the restriction lifted.

One second on whose computer? As Runner point's out, it will be different without using a timing device.

Good point. Which online interpreter / code executer supports most languages? I suppose they are even more variable, but hey, in the end the best plan probably does well.

ideone supports many languages, reports on execution time, and can be run online.

Thanks BrainSteel. I'll add that to the question. Though I do not see a timing?

What is this list of measures? Are they successive tie-breakers if scores are equal in the earlier categories? If so, none of "variability", "cleverness" and "fun" are objective, which makes them unsuitable winning criteria for PPCG. For future challenges, you might want to give the sandbox a try, where challenge ideas can be polished before people start working on them.

@MartinBüttner I was indeed thinking to figure out a weighted measure, or, when I added the last 2, a winner in each category. But that sandbox sounds like a good idea!

I don't see any rule disallowing for example ruby's inbuilt Time.now? We can't let the processor sleep/pause, but I can just keep it busy checking the current time or doing some meaningless arithmetics. t=Time.now;loop{i=1+2;break if Time.now-t>=5.0-0.03}

Why is everyone downvoting this? It's a wonderful idea.

@ASCIIThenANSI, I also like the base idea, but having the 9th revision in ~50 minutes is not really an indicator of great questions. Would be nice to be able to vote separately on the idea and on its transformation into a challenge… Then I would vote idea ▲, challenge ▼. (For now I not voted, just marked my answer community wiki, to not actually participate in this.)

Linux shell - 0.999 seconds (19 characters)
$ ping -c 2 127.0.0.1
PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.057 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.049 ms

--- 127.0.0.1 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 999ms
rtt min/avg/max/mdev = 0.049/0.053/0.057/0.004

I got 1000ms on the dot a few times, but 999ms was more common.  Perhaps relying on ping's inherent waits between packets to decrease network congestion may cross a line, but in my defense, I didn't write a sleep or busy-wait in my code... I just really wanted a N=2 sample size for my pings.  You never know when your sneaky computer might respond to one message and not another!

I don't see any problems. It says "anything goes except to have the processor sleep/pause".

Well, if we'd look at the processor we would know it is not "working" --> sleep/pause. And indeed, I believe it is a simple argument to ping how long it should wait.

I actually think this is one of the more clever answers for this challenge. Although (if I were remotely capable in the Linux shell, I'd post it myself), I think it would be fun to ping -i 0 -l 1 and kill the ping as soon as the sum of time=... is 1000ms.

What about 0.0.0.0?

Perl: 1.0031 seconds, 16 characters
(An unhandled signal terminates the process, so this code was measured from “outside” with bash's time. Result includes the perl interpreter's startup time too. :()
alarm 1;1while 1

Perl: 1.000059 seconds, 42 characters
(This code was surrounded with Time::HiRes::gettimeofday() calls for more accurate measurement.)
eval{$SIG{ALRM}=sub{die};alarm 1;1while 1}

(No, alarm is not a sleep. Not works on ideone.)

Perl - 1.0065 1.0032 1.0025 seconds
for ($i = 0;$i < 11489000;$i++) {
 "Hey, I can see my post from here!";
}

Tested using the command time perl onesecond.pl, and averaged.
There is also another Perl answer, so it looks like I may have to step up my game...

Quoted: "Anything goes except to have the processor sleep / pause does not count."

@PascalvKooten Sorry, must've missed that. Fixed now.

Your idea is the simple start of where I'd like to see this go!

The Hexadecimal Stacking Pseudo-Assembly Language
Probably the longest program you'll see here at 120. Ranges from (usually; there are some rare cases which are well outside this range for some reason) 0.93 to 1.03 seconds run time (I rigged up a simple timer to my copy of the java interpreter). Pushes 40,960 33s to a stack, prints them all as chars, then halts with status 418.

20A000
400000
000000
200021
400100
410000
400200
200001
400000
410200
400000
220000
420000
400000
030000
010001
010000
000001
140100
0401A2

...on your machine. Does it run equally fast on other peoples machines?

No clue. That's the problem with this challenge unfortunately.


text:
Cops and Robbers
Everyone always wants to implement Conway's Game of Life. That's boring! Let's do cops and robbers instead!
You'll have two teams: the cops and the robbers. Each team has 5 members with 50 health each. The program will loop continuously. Each iteration, the following will occur:

For each team, print the first letter (C for the cops, R for the robbers), a space, a space-separated list of the members' HP, and a newline. This is the teams' status. After both are done, print another newline. For instance, here's what it might look like the first round:
C 50 50 50 50 50
R 50 50 50 50 50

Pick a random number from 1 to 10 (including both 1 and 10). We'll call the number N. If N is even, the robbers lose this round; if odd, the cops lose.
Pick a random member of the losing team whose HP is greater than 0 and deduct N HP. The members' HP should never appear go below 0 on the status.
Restart the loop.

The game ends when all the members of one team lose all their HP. Then, the following will be printed if the cops win:
C+
R-

and if the robbers win:
R+
C-

This is code golf, so the shortest number of characters wins.
Here's a sample implementation in Python 2:
import random

cops = [50]*5
robbers = [50]*5

while any(cops) and any(robbers):
    # print the status
    print 'C', ' '.join(map(str, cops))
    print 'R', ' '.join(map(str, robbers))
    print
    # pick N
    N = random.randint(1, 10)
    # pick the losing team (robbers if N is even, else cops)
    losers = robbers if N % 2 == 0 else cops
    # pick a member whose HP is greater than 0
    losing_member = random.choice([i for i in range(len(losers)) if losers[i]])
    losers[losing_member] -= N
    # make sure the HP doesn't visibly drop below 0
    if losers[losing_member] < 0: losers[losing_member] = 0

if any(cops):
    # robbers lost
    print 'C+'
    print 'R-'
elif any(robbers):
    # cops lost
    print 'C-'
    print 'R+'

Minor irony: out of the 3176+ questions on this site, no more than 11 are tagged game-of-life.

@sanchises Extended irony: and 14 are tagged cops-and-robbers!

@sanchises I was largely referring to programming in general (e.g. "Help me! I'm trying to implement Conway's Game of Life!")...but that's still pretty ironic.

@kirbyfan64sos I know (been there, done that), but this is exactly the kind of site where people go after they've implemented GoL and want more... Anyway, perhaps I'll have a go at this in ><>, lets see if I can do that.

I've removed the CnR tag again. Around here, this tag has a very specific meaning and describes challenges where there are actually two (not necessarily disjoint) parties competing against each other at certain tasks (have a look around the other challenges with that tag).

@MartinBüttner It was already there? I though I had forgotten to put it. :O

At which step in the loop are we supposed to check for the winning condition?

@FUZxxl At the beginning of each iteration.

CJam, 86 bytes
I'm a bit late to the party, but I bring the gift of CJam! ... Hey wait, where are you going?
50aA*{"CR"1$+2/zSf*Nf+oNoAmr{_AmrE&+:P2$=:H!}gPH@)-Ue>t_2/z::+0#:L)!}g;'CL'+'-?N'R2$6^

Try it online.
Explanation
As the questions asks to emulate a straightforward process, this is a relatively straightforward answer. Perhaps one interesting choice I made was to hold the health of both teams interleaved in the same list. This costs 3 bytes to convert to two separate lists, which is needed for both health displaying and checking if a team has lost. But (I think) this is made up for by the 2 bytes saved in initialization and much simpler damage-dealing logic.
50aA*           "Initialize the health list to 10 copies of 50. Even indices
                 hold the health of cops and odd indices hold the health of
                 robbers.";
{               "Do:";
  "CR"1$+2/z      "Split the health list into the two teams for output, adding
                   the corresponding team letter to the start of each.
                       [a b c d e f g h i j]
                    -> [['C a c e g i] ['R b d f h j]]";
  Sf*Nf+          "Insert a space between each element in each team health list
                   and append a newline to the end of each team health list.";
  oNo             "Print the health status for each team and an extra newline.";
  Amr             "Generate the damage amount minus one. If the damage amount is
                   even (robbers lose), then this is odd and aligns with robbers
                   being at odd indices in the health list, and vice versa.";
  {               "Do:";
    _AmrE&+:P       "Add a random even number from [0, 10) to the damage amount
                     minus one. This value modulo the size of the health list
                     (10) selects a person on the losing team to be damaged.";
    2$=:H!
  }g              "... While the selected person's health is zero.";
  PH@)-Ue>t       "Set the damaged person's new health to the maximum of their
                   current health minus the damage amount and zero.";
  _2/z::+0#:L     "Split the health list into the two teams, sum each team's
                   health, and search for a team's health equal to zero.";
  )!
}g              "... While no team's health was found equal to zero.";
;               "Discard the health list.";
'C              "Produce a 'C'.";
L'+'-?          "Produce a '+' if team 1 (robbers) lost, or '-' otherwise.";
N               "Produce a newline.";
'R              "Produce an 'R'.";
2$6^            "Produce the opposite of the sign produced before.";
                "Implicitly print these final results.";

R - 201
S=sum
Z=sample
C=R=rep(50,5)
while(S(R)*S(C)){cat("C",C,"\nR",R,"\n\n")
N=Z(10,1)
F=function(x,i=Z(rep(which(x>0),2),1)){x[i]=max(0,x[i]-N);x}
if(N%%2)R=F(R)else C=F(C)}
cat(c("R+\nC-\n","C+\nR-\n")[1+!S(R)])

Also why the rep(which(x>0),2) as opposed to just which(x>0)?

I am counting the EOL characters, not the last one though. 2) sum(R*C) and sum(R)*sum(C) are not the same thing. For example, you would not want to exit if C=c(0,0,0,10,10) and R = c(10, 10, 10, 0, 0). In that case, I do save by assigning S=sum. 3) The problem with sample is that if the first argument is a single number, e.g. sample(5, 1), then it will be the same as doing sample(1:5, 1): instead of always returning 5, it will return any number from 1 to 5. So sample(rep(x, 2), 1) is my trick for always picking a number among x even in the case when length(x) is 1.

Sorry my bad ... Obviously not enough coffee.  Thanks for the explanation on the rep() trick.  I thought there must be a reason, just couldn't see it

APL (Dyalog) (101)
∇K
S←2 5⍴50
→6/⍨~∧/J←∨/S>0
⎕←3↑'CR',0⌈S
S[L;M[?⍴M←(0<S[L←1+~2⊤N;])/⍳5]]-←N←?10
→2
⎕←'CR',⍪'+-'⌽⍨J⍳0
∇

Explanation:

S←2 5⍴50: at the beginning, set S to a 5-by-2 matrix where each value is 50. The top row of the matrix represents the cops, the second row represents the robbers.
J←∨/S>0: for each row of the matrix, store in J whether any of the HPs are larger than zero.
→6/⍨~∧/J: if not both teams have living members, jump to line 6. (end)
⎕←3↑'CR',0⌈S: for each value in the matrix, output the maximum of it and 0, prepend a 'C' to the first row and an 'R' to the second, and add a third (empty) line.
N←?10: get a random number in the interval [1,10] and store it in N.
L←1+~2⊤N: set L (the losing team) to 1 if the number was odd and to 2 if it was even.
M←(0<S[L...;])/⍳5: get the indices of the living members of that team, and store them in M
M[?⍴M...]: select a random value from M
S[L;M...]-←N: subtract N from the selected team member's value
→2: jump to line 2 (the test for living members)
⎕←'CR',⍪'+-'⌽⍨J⍳0: output the final status, putting the + in front of the winning team and the - in front of the losing team.

Sample output

C, 390 384 371 bytes
My first golf, if there are any possible improvements, just tell me :)
golfed version:
#include <time.h>
#include <stdio.h>
int p[10],j,r,c,w,N,x;int s(){r=c=0;for(j=5;j--;){c+=p[5+j];r+=p[j];}return !!r-!!c;}void t(){for(j=10;j--;)printf("%s %d",j-4?j-9?"":"\n\nC":"\nR",p[j]*=p[j]>0);}main(){srand(time(0));for(j=10;j--;)p[j]=50;t();while(!(w=s())){N=rand()%10+1;while(!p[x=N%2*5+rand()%5]);p[x]-=N;t();}N=(x=w<1?'C':'R')-w*15;printf("\n\n%c+\n%c-",x,N);}

somewhat ungolfed version:
#include <time.h>
#include <stdio.h>
int p[10],j,r,c,w,N,x;

int s(){
    r=c=0;
    for(j=5;j--;){
        c+=p[5+j];
        r+=p[j];
    }
    return !!r-!!c;
}

void t(){
    for(j=10;j--;)printf("%s %d",j-4?j-9?"":"\n\nC":"\nR",p[j]*=p[j]>0);
}

main(){
    srand(time(0));
    for(j=10;j--;)p[j]=50;
    t();
    while(!(w=s())){
        N=rand()%10+1;
        while(!p[x=N%2*5+rand()%5]);
        p[x]-=N;
        t();
    }
    //w=-1 if cops won, w=1 if robbers won
    N=(x=w<1?'C':'R')-w*15;
    printf("\n\n%c+\n%c-",x,N);
}

edit: I found a way to shorten it a bit and fixed a small bug

A small improvement: you can replace loops (e.g. for(j=0;j<10;j++)) with a shorter version (for(j=10;--j;)).

You are totally right, "fixed" this and a few minor other things, thanks.

Batch - 396 Bytes
I don't know if this technically counts - as it doesn't actually select a random member of the team who's health is greater than 0. It just selects a random member, and if the health subtraction generates a number less than 0, then the number becomes 0..
@echo off&setLocal enableDelayedExpansion&for %%a in (C R)do for %%b in (1 2 3 4 5)do set %%a%%b=50
:a
set/aN=%RANDOM%*10/32768+1
set/ac=%N%/2*2
if %c%==%N% (set T=C&set L=R)else set T=R&set L=C
set/aG=%RANDOM%*5/32768+1
set/a%T%%G%-=%N%
for %%a in (C R)do set %%a=0&for %%b in (1 2 3 4 5)do (if !%%a%%b! LEQ 0 set %%a%%b=0
set/a%%a+=!%%a%%b!)
if %C% NEQ 0 if %R% NEQ 0 goto :a
echo !T!+&echo !L!-

The requirement is that the value never shows below 0 on the printed status. I did the same thing in the example I showed.

PHP - 416 bytes
I'm new to golfing and though this challenge would be easy enough to try it out. So here is what I came up with.
<?$c=[50,50,50,50,50];$r=[50,50,50,50,50];while((array_sum($c)!=0)&&(array_sum($r)!=0)){$a="C ".join(" ",$c)."\n";$b="R ".join(" ",$r)."\n";echo$a,$b;$n=rand(1,10);$m=rand(0,4);if($n %2==0){while($r[$m]==0){$m=rand(0,4);}$r[$m]=$r[$m]-$n;if($r[$m]<0){$r[$m]=0;}}else{while($c[$m]==0){$m=rand(0,4);}$c[$m]=$c[$m]-$n;if($c[$m]<0){$c[$m]=0;}}if(array_sum($r)==0){echo"C+\nR-\n";}if(array_sum($c)==0){echo"R+\nC-\n";}}?>

With explanation:
<?
$c=[50,50,50,50,50];$r=[50,50,50,50,50];                       populate Arrays
while((array_sum($c) != 0) && (array_sum($r) != 0)){           loop until on array sums up to 0
    $a="C ".join(" ",$c)."\n";                                 set cops health to a
    $b="R ".join(" ",$r)."\n";                                 set robbers health to b
    echo$a,$b;                                                 print cop and robber health
    $n=rand(1,10);                                             chose random n
    $m=rand(0,4);                                              chose random member
    if($n % 2 == 0){                                           check if n is even
        while($r[$m] == 0){ $m=rand(0,4); }                    loop until value m of array r is not 0
        $r[$m]=$r[$m]-$n;                                      lower health of member m
        if($r[$m] < 0){ $r[$m]=0; }                            if health goes below 0 set it to 0
    }else{
        while($c[$m] == 0){ $m=rand(0,4); }                    same as above
        $c[$m]=$c[$m] - $n;
        if($c[$m] < 0){$c[$m]=0;}
    }
    if(array_sum($r) == 0){ echo"C+\nR-\n"; }                  check if r array sums up to 0 and print that cops won
    if(array_sum($c) == 0){ echo"R+\nC-\n"; }                  check if c array sums up to 0 and print that robbers won
}
?>

I'm not a PHP user, but I'd guess that maybe you'd cut a few chars by removing != 0 and replacing the check for being equal to zero with the not operator (!array_sum($r)).

@kirbyfan64sos that doesn't work

Oh. In most languages, it would.

Mathematica, 246 241 bytes
Could probably be golfed further...
a=ConstantArray[50,{2,5}];b=Or@@(#<1&)/@#&;c=Print;d=StringJoin@Riffle[IntegerString/@#," "]&;e=RandomInteger;Label@f;Which[b@a[[1]],c@"R+\nC-",b@a[[2]],c@"C+\nR-",True,c["C "<>d@a[[1]]<>"\nR "<>d@a[[2]]];a[[Mod[g=e@9+1,2]+1,e@4+1]]-=g;Goto@f]

Ruby, 184
c,r=[p,p].map{('50 '*5).split}
puts([?C,*c]*' ',[?R,*r]*' ')while (u,v=[r,c].map{|a|a.shuffle.find{|x|x>?0}}).all?&&[u,v][rand(1..10)%2].sub!(/.+/){eval"#$&-1"}
puts u ?'R+
C-':'C+
R-'

Octave, 182 177 158 145 bytes
145:
t=repmat(50,5);while prod(any(t))d=ceil(rand*10);c=2-mod(d,2);r=ceil(rand*5);t(r,c)-=d;t.*=t>0;end;p=2*any(t,1);['C-';'R+';'C+';'R-'](1+p:2+p,:)

I gave up checking if the character shoot is above zero - this would only be significant if we were forced to display the state in each turn - here we're just randomly skipping one random number from RNG, making it more random.
Also, replaced
t=max(0,t)

with shorter
t.*=t>0

[note - it is printing 'C+R-' without the newline - it's fixed in 145 byte version]
158:
t=repmat(50,5);while prod(any(t))d=ceil(rand*10);c=2-mod(d,2);do r=ceil(rand*5);until t(r,c);t(r,c)-=d;t=max(0,t);end;p=4*any(t,1);disp('C-R+C+R-'(1+p:4+p))

Degolfed:
t=repmat(50,5);               #only first two columns (cops, robbers) relevant
while prod(any(t))
    d=ceil(rand*10);
    c=2-mod(d,2);
    do r=ceil(rand*5);until t(r,c);
    t(r,c)-=d;
    t=max(0,t);
end;
p=4*any(t,1);
disp('C-R+C+R-'(1+p:4+p))

I changed repmat(50,5,2) to repmat(5) - so we have 5x5 matrix instead of 5x2 now (the additional 3 columns don't affect the algorithm). I also found a way to compress the output.
177:
t=repmat(50,5,2);while prod(sum(t))d=ceil(rand*10);c=2-mod(d,2);do r=ceil(rand*5);until t(r,c);t(r,c)-=d;t=max(0,t);end;if sum(t)(1)printf "C+\nR-\n";else printf "C-\nR+\n";end

Degolfed:
t=repmat(50,5,2);
while prod(sum(t))
    d=ceil(rand*10);
    c=2-mod(d,2);                  #cops or robbers affected?
    do r=ceil(rand*5);until t(r,c);
    t(r,c)-=d;
    t=max(0,t);
end
if sum(t)(1)
    printf "C+\nR-\n"
else
    printf "C-\nR+\n"
end

Basically, we create a 5x2 matrix, where the first column are cops and the second column are robbers:
t =
50     50
50     50
50     50
50     50
50     50
[cops] [robbers]

The sum function when one argument applied makes a sum by columns, so it's initially:
250    250

When one of them reaches zero, the prod(sum(t)) evaluates to zero breaking the loop. Then we can examine who won checking whose column sums to zero.

Javascript: 410
function x(l){var t=this,o=t.p={n:l||"C",h:[50,50,50,50,50],s:function(){return o.h.reduce(function(a,b){return a+b})},r:function(){console.log(o.n+' '+o.h.join(' '))},d:function(m){while(o.h[z=~~(Math.random()*5)]<1){}o.h[z]=m>o.h[z]?0:o.h[z]-m}};o.r()}q=[new x(),new x('R')];while((c=q[0].p.s()>0)&&q[1].p.s()>0){q[(z=~~(Math.random()*10))%2].p.d(z);q[0].p.r();q[1].p.r()}console.log(c?'C+\r\nR-':'R+\n\rC-')


text:
Programming Tetris Blocks (Literally)
In the game Tetris, there are 7 types of bricks or Tetriminoes, which are mathematically known as tetrominoes because they are all made with 4 square segments:

The have the names I, J, L, O, S, T, and Z, that correspond to their approximate shapes. Counting 90° rotations, there are 19 unique shapes in total:
I
I
I
I

IIII

 J
 J
JJ

JJJ
  J

JJ
J
J

J
JJJ

L
L
LL

  L
LLL

LL
 L
 L

LLL
L

OO
OO

 SS
SS

S
SS
 S

TTT
 T

T
TT
T

 T
TTT

 T
TT
 T

ZZ
 ZZ

 Z
ZZ
Z

Challenge
Write a rectangular block of code that acts as the base segment these 19 shapes are made from. When this code is arranged into one of the shapes, a program should be formed that outputs the single uppercase letter associated with that shape. This must work for all 19 shapes.
The leading empty areas present in some of the 19 shapes are filled in entirely with spaces (). The trailing empty areas are not filled with anything (so the programs are not always exactly rectangular).
Example
Suppose this was your code block:
ABC
123

Then either arrangement of the block into the S Tetris piece would be a program that prints S:
   ABCABC
   123123
ABCABC
123123
ABC
123
ABCABC
123123
   ABC
   123
(Notice that all leading empty space is filled with space characters, and that no lines have any trailing spaces.)
The same idea applies to all 6 other pieces and their respective rotations.
Notes

All 19 final programs are to be run in the same programming language.
If desired, you may add a single trailing newline to all programs (not just some, all or none).
Your code block may contain any characters (including spaces) that aren't line terminators.
Output the letter to stdout (or your language's closest alternative) with an optional trailing newline.

Scoring
The submission whose code block has the smallest area (width times height) wins. This essentially means the shortest code wins, which is why this is tagged code-golf. Tiebreaker goes to the highest voted answer.
The ABC\n123 example has area 3×2 = 6.
Snippet
Given a code block, this snippet will generate all 19 programs:

Code Block:
<textarea id='input' rows='8' cols='64'>ABC
123</textarea>
<button type='button' onclick='go()'>Go</button>

All 19 Programs:
<textarea id='output' rows='24' cols='64'></textarea>

So the length-width ratio is 2 to 3? Or can it be any other size? Also, what does the program have to do, at a minimum? Assuming empty programs don't count, but programs that output nothing do.

@ASCIIThenANSI Any width and height are fine. I imagine something larger than 2*3 will be necessary. There are 19 programs, one for each arrangement of the block into one of the 19 distinct tetromino shapes. When one of those programs is run, it outputs the corresponding tetris piece letter.

Wow! What an awesome challenge! Does it matter which language we use?

@theonlygusti Almost all questions on this site allow any language. This is no exception.

@Calvin'sHobbies Yeah, I know; I just misinterpreted the snippet as a controller for running JavaScript-answers. Apparently it just arranges code blocks.

idk, but I am having fun just replacing the characters in your code block with words lol

<>< (Fish) - 12 * 32 = 384
I was planning to go for a more elegant solution, but I somehow ended up with this, which is pretty brute-force:
c  0  g84*%\
c2*0  g84*%\
0  84*g84*%\
c  84*g84*%\
c2*84*g84*%\
0  88*g84*%\
c  88*g84*%\
?v         \
;>?v~~?vv
"L" o;  >
"S" o; >~?v
"T" o;    >
;  >~?v"L"o
;     >"J"o
?v         \
 >~?v~~?vv
"I"  o;  >
"J"  o; >
    \~~?vv
"T"  o;  >
"Z"  o; >
?v         \
 >?v"J"o;
   >?v"Z"o;
"L"o;>?!v
"J"o;   >?v
"T"o;     >
?v?v"I"o;  >
   >"L"o;
 >?v"T"o;
   >?v"O"o;
     >"S"o;

It's pretty simple, it checks the code in a 3x3 square for text and uses the results to see which tetrimino corresponds to the code's shape. I didn't take a lot of effort to golf it yet.
Try the code here (after using the snippet to shape it like a tetrimino)
Example of code in shape Z (v1) here

C (gcc), 26x20 = 520 25x19 = 475 23x17 = 391
#ifndef M            //
#define M(a,b)a##b   //
#define W(z,x)M(z,x) //
char*s,*S[]={"!!!!c",//
"8M !7! M8 878","77",//
"7!!MO887","788OM!!7"//
,"N7!78","7N87!"},r[5//
],*p=r;i=7;main(){for//
(;i--;)strstr(S[i],r)//
&&putchar("ITOJLSZ"[i//
]);}                 //
#endif               //
__attribute__((      //
constructor(__LINE__)//
))W(f,__LINE__)(){s= //
"                     \
";*p++=strlen(s)+12;}//

I was recently informed of GNU's function attributes, and most interestingly the constructor attribute, which allows for a more terse implementation of what I was doing in a more roundabout way in my earlier approach to this problem.
The thrust of the idea is the same as before: Build a string and search for it in a list to identify which tetris block the code is laid out as. This is done by calling functions, each one adding a character to the string. The complication was and remains that the number of functions varies.
Defining a function with attribute((constructor(x))) makes it so that the function is run before main() is entered, with the optional x being the priority (lower means it is run earlier). This removes the need for function pointers, which allows us to drop a macro, some declarations, and the calling chain.
Using __LINE__ for priority is iffy, since priority levels 0-100 are reserved. However, it does not result in errors, only warnings, and those are plentiful when golfing, so what's a few more?
It would have helped shave another column off to not use priorities at all, but the order of execution does not seem to be defined. (They are reversed in this case, but other tests are inconclusive.)
Example of L v2 here
Older, more portable, approach
#ifndef M              //
#define M(a,b) a##b    //
#define W(z,x)M(z,x)   //
#define F W(f,__LINE__)//
#define A W(a,__LINE__)//
char r[5],*S[]={"####k"//
,";<<US##;",";##SU<<;",//
";;",";T<;#","<S #;# S"//
"< <;<","T;#;<"},*s,*p=//
r;i;typedef(*T)();T a17//
,a36,a55,a74;main(){for//
(a17(),a36&&a36(),a55&&//
a55(),a74&&a74();i--;) //
strstr(S[i],r)&&putchar//
("ILJOZTS"[i]);}i=7;   //
#endif                 //
F();T A=F;F(){s=       //
"                       \
";*p++=strlen(s)+12;}  //

One of my favourite problems I've solved on this site.
I began by figuring each block would divine its own coordinates somehow. Rows are easy with __LINE__, and the number of horizontally adjacent blocks could be found by using the length of a string literal, like so:
char*s=//char*s=//
"       ""       "
;        ;

Take the length of the resulting string and and divide by a proper number and you have the width. Sadly, any empty space before the block is invisible by this method. I still suspected strings would be the solution, since whitespace only has meaning outside of strings very rarely, in things like a+++b vs. a+ ++b. I briefly considered something like that, but could not come up with anything useful. Another possibility would have been to let identifiers be "glued" together where blocks met:
A  BA  B

I would not be surprised if this could still make for an interesting solution.
Despite its simplicity, it took me quite some time to find the string solution, which is based on this block fragment:
s=//
"  \
";//

If the fragment has no horizontal neighbours, the newline on the second line is escaped by the backslash, creating a string of length 2. If, however, it does have a neighbour, the backslash will instead escape the quotion mark at the start of line 2 of the next block:
s=//s=//
"  \"  \
";//";//

This will create the string "  \"  " of length 5.
More crucially, this also allows for detection of empty space before the block:
    s=//
    "  \
    ";//

Again, the newline is escaped, and the whitespace of the empty block to the left is included in the resulting string "      " of length 6.
In total there are seven different configurations of blocks on a row that we need to worry about, and they all make strings of unique lengths:
2 "  "
---
s=//
"  \
";//

5 "  \"  "
---
s=//s=//
"  \"  \
";//";//

6 "      "
---
    s=//
    "  \
    ";//

9 "  \"      "
----
    s=//s=//
    "  \"  \
    ";//";//

10 "          "
---
        s=//
        "  \
        ";//

8 "  \"  \"  "
---
s=//s=//s=//
"  \"  \"  \
";//";//";//

11 "  \"  \"  \"  "
----
s=//s=//s=//s=//
"  \"  \"  \"  \
";//";//";//";//

The final blocks will of course not have such short length, but the principle is the same regardless of block size. This also has the bonus that a separate mechanism for detecting width is unnecessary. By adding a character corresponding to the length of this string to a results string, each of the 19 configurations yields a unique string, that needs only be compared to a suitable list once all the blocks have been run.
Once this was sorted, the next big problem was how to "visit" each row of blocks. In C, we are very limited to what can be done outside of functions. We also need main() to appear, but only once. The latter is easily achieved by some #defines, but if we want the code of subsequent blocks to be inside of main(), the problem of how to know when to put the final closing curly bracket. After all, we don't know how many rows of blocks will actually be used. So we need to have main() static and somehow the rest to be dynamic.
If the other block-rows are to be self-contained, they need to be functions, but we need to make sure each function has a name that is unique, while also being predictable enough to be callable from main(). We also need a mechanism for knowing which functions are actually there to be called. Generating unique names is solved by helper macros:
#define M(a,b) a##b     //
#define W(z,x)M(z,x)    //
#define F W(f,__LINE__) //
#define A W(a,__LINE__) //

Calling F will create an identifier whose name begins with an f and ends with the line number. A does the same but with a as prefix, which is used for the second part of the solution, which is function pointers. We declare four such pointers:
typedef(*T)();T a17,a36,a55,a74;

Since these are declared as global variables, they are conveniently set to NULL. Later on, each block-row will have the following piece of code:
F();T A=F;F()

This will first declare a function, define the appropriate function pointer to point to that function (we can only define globals once, but the earlier declaration did not count as a definition, even if it did initialise to NULL), and then define the actual function. This allows main() to call any function pointer that is non-NULL (a17 will never be NULL):
a17(),a36&&a36(),a55&&a55(),a74&&a74()

Doing so will build the string r, which is then looked for in the table of strings and if found, the appropriate letter is output.
The only remaining trick is that the list of strings to match against were shortened whenever ambiguity could be avoided, or overlapping strings could be conflated.
Example of L v2 here

x86 opcode(.com), 86 82 bytes
Tester:
org 100h
macro e {
db $F6,$04,$DF,$78,$13,$75,$08,$00,$C0,$40,$83,$C6,$52,$EB,$F1,$88
db $C2,$00,$D0,$00,$D0,$46,$EB,$E8,$05,$02,$40,$73,$ED,$E8,$26,$00
db $50,$08,$43,$4D,$2C,$0C,$1C,$15,$A5,$14,$10,$13,$3F,$27,$20,$0F
db $51,$1D,$29,$49,$49,$4A,$4A,$4A,$4A,$4C,$4C,$4C,$4C,$4F,$53,$53
db $54,$54,$54,$54,$5A,$5A,$5F,$AE,$75,$FD,$8A,$55,$12,$B4,$02,$CD
db $21,$C3
}

macro n { db 82 dup $20 }

macro s { db 10 }

n
e
s
n
e
s
e
e

Source:
BOF:    ;mov bx, 100h
p:      test [si], byte $DF
        js _a ; exist
        jnz _b ; newline
_z:     add al, al
        inc ax
q:      add si, EOF-BOF
        jmp p
_b:     mov dl, al
        add al, dl
        add al, dl
        inc si
        jmp p
_a:     add ax, 4002h
        jnc q
        call y
        db 80,8,67,77,44,12,28,21,165,20,16,19,63,39,32,15,81,29,41
        db 'IIJJJJLLLLOSSTTTTZZ'
y:      pop di
        scasb
        jnz y+1
        mov dl,[di+18]
        mov ah,2
        int $21
        ret
EOF:

Run in win7dos where init AX=0, SI=100, BX=0 References

If you are comfortable reducing the number of supported environments somewhat, you can assume SI = 100h and use that register instead of BX for indexing, to save 3 bytes by dropping mov bx, 100h at the start.

@gastropner Done and fixed a point where I didn't notice