text:
Calculate Doppelkopf Score
Introduction
Doppelkopf is a traditional German card game for 4 players. The deck consists of 48 cards (9, 10, Jack, Queen, King, Ace of each suit while every card is in the game twice), so each player gets 12 at the start of a round.
There are always 2 teams which are determined by the distribution of the Queens of Clubs. The 2 players who are holding the Queens form a team and play against the other 2 players. The team with the Queens of Clubs are called the "Re"-team, the one without is the "Contra"-team.
At the start of the round noone knows who is on which team. The team distribution will be revealed in the progress of the round, which adds a lot of strategy to the game.
The game consists of 12 tricks. The players who wins a trick gets all the 4 cards in it. Every card has a certain value (King counts 4, Ace counts 11 for example), all cards together sum up to 240 points which is the highest possible result.
At the end of a round the points are counted and the team with the highest amount of points wins the round. Then then next round starts...
The Challenge
Every round has a certain score which is determined by the amount of points the winning team got and potential announcements. You will have to write a program that takes the point distribution and potential announcements (see explanation below) as input and outputs the score of the round and the winner.
The score calculation
As mentioned there is a Re- and a Contra-team. Also there is a maximum of 240 points possible in one round. The Re-team has to get 121 points to win, while the Contra-team only needs 120. There is also the possibility to announce "Re" or "Contra" at the start of the round if you think that you will win the game. By doing this you are raising the score.
Here are the scoring rules:

+1 for winning the game
+1 if the losing team has less than 90 points ("Keine 90")
+1 if the losing team has less than 60 points ("Keine 60")
+1 if the losing team has less than 30 points ("Keine 30")
+1 if the losing team has 0 points ("Schwarz")
+2 for an announcement of Contra
+2 for an announcement of Re
+1 if the Contra team won ("Gegen die Alten")

Note: Re/Contra-Announcements always apply, regardless of the winner. See examples in the testcases below.
Input and Output
The input to the program will be the score of the Re-team and potential announcements of Re or Contra. Since there are always 240 points in the game you can easly calculate the score of the Contra-team.
The input will be a single string which has the score of the Re-team first, followed by the potential announcements, while "R" is for Re and "C" is for Contra. If both got announced, Re will always come first.
Output will be the score of the game followed by the winning team ("C" for Contra, "R" for Re)
Rules

Your submission can be a full program or a function. If you choose the latter include an example on how to invoke it.
Input can be provided by function- or command line arguments or user input.
Output can be provided as return value or printed to the screen.
Standard loopholes apply.
Lowest Byte-Count wins!

Testcases
Input -> Output (Explanation)

145R  -> 3R  (Re won, +1 for winning, +2 for Re-Announcement)
120   -> 2C  (Contra won, +1 for winning, +1 for winning as Contra)
80C   -> 5C  (Contra won, +1 for winning, +1 for no 90, +1 for winning as Contra, +2 for Contra-Announcement)
240R  -> 7R  (Re won, +1 for winning, +1 for no 90, +1 for no 60, +1 for no 30, +1 for no points for the losing team, +2 for Re-announcedment)
90    -> 2C  (Contra won, +1 for winning, +1 for winning as Contra)
110RC -> 6C  (Contra won, +1 for winning, +1 for winning as Contra, +2 for Re-Announcement, +2 for Contra-Announcement)
110R  -> 4C  (Contra won, +1 for winning, +1 for winnins as Contra, +2 for Re-Announcement)
184C  -> 5R  (Re won, +1 for winning, +1 for no 90, +1 for no 60, +2 for Contra-Announcement)

Short note: I left out some rules (like solos and bonus points) on purpose to keep the challenge simple. So if you are already familiar with the game, don't be confused :)
Happy Coding!

CJam, 47 46 bytes
L~]_,2*\0=:S121<:AS240S-e<_g3@30/-Te>--+A"RC"=

Run all test cases.
Hmm, conceptually this challenge is really simple, but it's surprisingly tricky to golf.

Agreed, when I tried golfing this, I came to around 100 bytes with a golfing language. I gave up very soon after.

Labyrinth, 136 103 94 92 87 84 76 74 69 61 bytes
 (}?
;)
,)
`
2
0:
 {
_-+}}82"
}"     {{"(#0/#--!.@
 -=-)}67 )

Try it online!
Ahh, it's been way too long since I used Labyrinth. It's always quite a joy to golf it. :)
Explanation
This is a bit outdated now. The overall structure of the program is still the same, but a few details have changed. I'll update this later. This is the previous solution, for reference:
 (}?
;)
,)
`
2
0 }82{_240{- ("
{ ;        #;`"~#0/#--!.@
:}-"-))}67{{
  ;#

Let's break down the score a bit:

If we count the characters after the number in the input, let's call it M, then there will be 2M+1 points in the final score, for winning, Re, and Contra.
If the score is 120 or less, Contra wins and the score is incremented by 1.
Looking at the losing score, we can (integer) divide it by 30 to determine the additional points. That has three problems though: 1. the value increases in the wrong direction, so we need to subtract it from the score (and add 3 to it to correct for that). 2. This gives an additional point for a result of exactly 120, which we need get rid of. 3. It doesn't handle a result of 0 (for the losing side) yet, but we can include it by turning 0 into -1 (since Labyrinth's integer division rounds towards -∞).

That's pretty much how the code works. Sp3000 posted a good primer for Labyrinth today, so I decided to steal it. :)

Labyrinth is stack-based and two-dimensional, with execution starting at the first recognised character. There are two stacks, a main stack and an auxiliary stack, but most operators only work on the main stack. Both stacks are bottomless, filled with zeroes.
At every branch of the labyrinth, the top of the stack is checked to determine where to go next. Negative is turn left, zero is straight ahead and positive is turn right.
Digits don't push themselves (as they do in Befunge, ><> or Prelude) - instead they "append themselves" to the top of stack, by multiplying the top by 10 and adding themselves.

So execution starts on the ( in the first row, with the instruction pointer (IP) going right. ( just turns the top of the main stack into -1 and } shifts it off to the auxiliary stack, where we can forget about it. The program really starts with the ? which reads the integer from STDIN. The IP then hits a dead end and turns around.
} shifts the input to the auxiliary stack and ( decrements another zero to -1. This will be the final score. We now enter a very tight clockwise loop:
;)
,)

The )) increments the score by two (so the first time we go through the loop, the score becomes 1, the score for winning). Then , reads a character. As long as that's not EOF, the loop continues. ; discards the character, because we don't care if it was R or C and )) adds two to the score again. This will repeat 0, 1 or 2 times depending on the input.
We leave the loop, when we've hit EOF, the top of the stack will be -1. We then run this linear part:
`20{:}-

The ` is unary negation, so we get 1, then 20 turns it into a 120. {:} gets a copy of the input integer from the auxiliary stack and - computes the difference with 120. We can use the sign of this result to determine who won.

If the result is negative, Re won and we take the northern path, executing:
;}82{_240{-#;

; discards this result, } shifts the score away, 82 puts itself (character code of R) at the bottom of the main stack, { gets the score back on top, _240{- subtracts the integer input from 240 so we can work with Contra's (the losing side's) points.
The #; is just to ensure that we have a non-zero value on the stack so we can join up both paths reliably.
If the result is positive, Contra won and we take the southern path, executing:
;#"-))}67{{#;

The # pushes the stack depth which is 1. This gets subtracted from the score before we add 2 with )). 67 puts itself (character code of C) at the bottom of the main stack. {{ gets the other values back.
If the result is zero, Contra still won. However, that's the 120/120 case for which we need add an extra point to the final score (see above). That's why this path doesn't push a 1 with #, but instead just leaves the zero such that the - simply removes that zero from the stack.

The stacks are now joined back together and we've accounted for everything except the part where we divide by 30. But first, we need to turn a zero-score into -1. That's what this little detour does:
("
`"~

The ` doesn't affect a zero, " is a no-op and ~ is bitwise negation. The bitwise NOT of 0 is -1 as required. If the score was positive instead, then ` makes it negative, ( decrements it by 1 and ~ undoes both of those operations in one go.
#0/#--!.@

The stack depth is now 3 (the winning side's character, the total score so far, and the losing side's points), so # pushes 3. 0 turns it into a 30, / does the division. # pushes another 3 which is subtracted and that result is in turn subtracted from the final score. ! prints it as an integer, . prints the winning side as a character and @ terminates the program.

JavaScript (ES6), 106
Around 100 bytes with a non golfing language.
x=>([,r,t]=x.match`(\\d+)(.*)`,t=1+t.length*2,w=r>120?(r=240-r,'R'):(++t,'C'),t+!r+(r<30)+(r<60)+(r<90)+w)

Test

f=x=>(
  [,r,t]=x.match`(\\d+)(.*)`,
  t=1+t.length*2,
  w=r>120?(r=240-r,'R'):(++t,'C'),
  t+!r+(r<30)+(r<60)+(r<90)+w
)

console.log=x=>O.textContent+=x+'\n'

test=[
['145R', '3R'], //(Re won, +1 for winning, +2 for Re-Announcement)
['120',  '2C'], //(Contra won, +1 for winning, +1 for winning as Contra)
['80C',  '5C'], //(Contra won, +1 for winning, +1 for no 90, +1 for winning as Contra, +2 for Contra-Announcement)
['240R', '7R'], //(Re won, +1 for winning, +1 for no 90, +1 for no 60, +1 for no 30, +1 for no points for the losing team, +2 for Re-announcedment)
['90',   '2C'], //(Contra won, +1 for winning, +1 for winning as Contra)
['110RC','6C'], //(Contra won, +1 for winning, +1 for winning as Contra, +2 for Re-Announcement, +2 for Contra-Announcement)
['110R', '4C'], //(Contra won, +1 for winning, +1 for winnins as Contra, +2 for Re-Announcement)
['184C', '5R'], //(Re won, +1 for winning, +1 for no 90, +1 for no 60, +2 for Contra-Announcement)
]

test.forEach(t=>{
  var i=t[0],k=t[1],r=f(i)
console.log((k==r?'OK ':'KO ')+i+' -> '+r+(k!=r?' (expected: '+k+')':''))
})

Only around twice the byte count of the CJam answer...not bad ^^

ES6, 92 bytes
s=>(p=s.match(/\d+|./g),n=+p[0],r=n>120,p.length*2-r+!(n%120)+3-((r?240-n:n)/30|0)+"CR"[+r])

p.length*2 overestimates the score by 1 if Re wins so I have to subtract r again. !(n%120)+3-((r?240-n:n)/30|0) is what I came up with to encapsulate the rules for scoring "Keine"; I so wish the boundaries had been 31, 61 and 91 as that would have made the formula 4-((r?269-n:29+n)/30|0).

source: Stack Exchange

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

sort: votes


text:
Exploding Cats!
Challenge
You will be making a program/function that takes a string input of length n, and:

Puts the kth char at the center of the space, where k = (n+1)/2. This will be the location of your ground zero.
Puts the rest of the non-whitespace chars randomly arranged around ground zero. The Pythagorean distance from the char must not exceed n.
Outputs the result.

If you need clarifications, see the example below.

Rules

Standard loopholes apply!
I/O must be in the form of a string.
Input will always be odd to ensure that you have a central char to put at ground zero.
Every valid output should occur with a non-zero probability.

This is code-golf; shortest code in bytes wins!

Example
Input: qwert
The boundaries of the explosion emanating from ground zero (x's mark valid places for the rest of the chars to be):
     x
  xxxxxxx
 xxxxxxxxx
 xxxxxxxxx
 xxxxxxxxx
xxxxxexxxxx
 xxxxxxxxx
 xxxxxxxxx
 xxxxxxxxx
  xxxxxxx
     x

Example output:
       t
     r

q    e

      w

Selecting position randomly, one char could go in the same position of an other and overwrite it. Is this alllowed? (My suggestion: no)

You are right: No.

What on earth does this have to do with blowing me up? (I genuinely don't understand the relevance of the title...)

@cat This is a modification of a cat program, except that you explode the input.

A little bit related

APL (Dyalog Classic), 68 66 65 63 62 bytes
{⍵@(n⊣¨¨@(⊢≡¨⌽)i[n?≢i←⍸(××n≥*∘.5)+.×¨⍨n-⍳s])⊢''⍴⍨s←2⍴1+2×n←≢⍵}

Try it online!
{ } anonymous function with argument ⍵
n←≢⍵ variable n is the length
s←2⍴1+2×n variable s is the shape of the result: 2n+1 by 2n+1
''⍴⍨s create a square of spaces with that shape
A@I⊢B puts elements A at (pairs of) indices I in matrix B
+.×¨⍨n-⍳s squared distances from the centre of the matrix
(××n≥*∘.5) boolean matrix indicating where those distances are non-zero and ≤n
⍸ coordinate pairs for the 1s in the boolean matrix
i[n?≢i← ... ] choose n of them randomly (no duplicates)
n⊣¨¨@(⊢≡¨⌽) change the central one to n n
⍵@( ... )⊢ ... put the chars from the argument at the given indices in the matrix of spaces

JavaScript (ES6), 211  216 220
Edit 1 byte saved thx @usandfriends
s=>[...s].map((c,i)=>{for(R=_=>Math.random()*h-l|0;x=R(y=R()),!(i-(l/2|0)?x|y&&x*x+y*y<=l*l&g[y+=l][x+=l]<'!':x=y=l););z=[...g[y]],z[x]=c,g[y]=z.join``},l=s.length,g=Array(h=l-~l).fill(' '.repeat(h)))&&g.join`
`

Test

f=s=>[...s].map((c,i)=>{for(R=_=>Math.random()*h-l|0;x=R(y=R()),!(i-(l/2|0)?x|y&&x*x+y*y<=l*l&g[y+=l][x+=l]<'!':x=y=l););z=[...g[y]],z[x]=c,g[y]=z.join``},l=s.length,g=Array(h=l-~l).fill(' '.repeat(h)))&&g.join`
`

// Less golfed
U=s=>(
  l=s.length,
  h=l-~l, // l+l+1
  g=Array(h).fill(' '.repeat(h)),
  [...s].map((c,i)=>{
    for(R=_=>Math.random()*h-l|0;
        x=R(y=R()), // set x,y to a random value in range -l ... l
        !(i - (l/2|0) // check if at mid point of input string
          ? x|y && // if not, check x and y must not be both 0
            x*x + y*y <= l*l &  // then check position inside the circle of ray L
            g[y+=l][x+=l] < '!' // then add offset L and check if position is not already used
          : x=y=l // if at midpoint in input string, x and y have fixed value L
         );
       ); // loop until valid position found
    z = [...g[y]];  // modify string at current position: convert to array ...
    z[x] = c;       // ... set element ...
    g[y] = z.join`` // ... back to string
  }),
  g.join`\n`
)

setInterval(_=>O.textContent=(f(I.value)),1000)
Word <input id=I value='qwert'>

You have an extra space before g.map(r=>r.join``)...

@usandfriends thx I don't know how I missed it

Use new Date()%h-l instead of Math.random()*h-l|0. It saves bytes.

@ericw31415 use just 0. It saves bytes too. But both won't work

Ruby, 211 207 203 196 characters
Thanks to edc65 for 4 characters
->(x){x=x.chars
o,b,c=x.size
l=o*2+1
a=Array.new(l){Array.new l,' '}
a[o][o]=x.delete_at o/2
a[b][c]=x.pop if a[b=rand(l)][c=rand(l)]==' '&&(b-o)**2+(c-o)**2<=o*o while x[0]
a.map(&:join).join $/}

Explanation:
->(x){...} define an anonymous function that takes in an argument x
x=x.chars transform x from a string into an array of one-character strings
o,b,c=x.size store the length of the input in o for later use. b and c simply need to be initialized to something, so save 2 characters by attaching to a previous assignment.
l=o*2+1 this is the length/width of the field where all characters could possibly go, also the diameter of the explosion circle.
Array.new(l){Array.new l,' '} make an lxl sized 2D array of space characters.
a[o][o]=x.delete_at o/2 sets the center of the array to the center of the values of x (the input), while deleting that value from x
... while x[0] run the block (in this case, the code before while because it is inline) over and over until x is empty. In ruby, accessing an index that does not exist returns nil, which is a falsey value.
a[b=rand(l)][c=rand(l)]==' ' Assign b and c to random values where 0 <= n < l. Then check if the spot at b,c is empty (aka is set to space character)
(b-o)**2+(c-o)**2<=o*o Pythagorean distance check. o is the length of the input. ** is ruby's exponentiation operator, and val<=o*o is shorter than val**0.5<=o.
a[b][c]=x.pop delete the last value from x. Set the position a,b to that value in array a
a[b][c]=x.pop if a[b=rand(l)][c=rand(l)]==' '&&(b-o)**2+(c-o)**2<=o*o while x[0] Set a random position to the last value if that position is free and is within the explosion radius; keep doing this until we run out of characters to place.
$/ is set to the operating system's newline. It's also shorter than "\n"
a.map(&:join).join $/ Map all the arrays in a to a single-string version of themselves (eg ['a','b','c'] -> 'abc'). Take that new array and join it with newlines. Implicit return.

o*o is shorter then **0.5

Python 3, 286 bytes
import random as r
i=input()
l=len(i)
a=range(-l,l+1)
g=[(y,x)for y in a for x in a]
p=[(y,x)for y,x in g if abs(x+y*1j)<=l and x|y]
m=i[l//2]
d=[*i.replace(m,"",1).center(len(p))]
r.shuffle(d)
o=""
for c in g:
	o+=m if c==(0,0)else d.pop()if c in p else" "
	if c[1]==l:o+="\n"
print(o)

Trying it online is an option.
Whoops, stumbled onto this due to recent activity, didn't notice it was over two years old somehow until I spent a good while on this. Well, two answers is kind of sad, so this is probably a good idea to post anyway. I'm sure there are dozens of ways to improve on this—didn't notice until just now that input is always odd, which would've been helpful to know.
Explanation
i=input() is input, of course, l=len(i) is saving the length of the string because it's used quite a few times.
a=range(-l,l+1) — a quick tool to create an iterator ranging the available distances away from the origin both ways along one dimension.
g=[(y,x)for y in a for x in a] builds a list of tuple coordinates that makes up the entire final grid.
p=[(y,x)for y,x in g if abs(x+y*1j)<=l and x|y] creates a subset of the list containing only the coordinates that non-center letters can possibly land on.
m=i[l//2] establishes the center character.
d=[*i.replace(m,"",1).center(len(p))] — the center character's taken out, leaving us with the other debris. The center() function is very nice here, because it allows us to pad out the line (with by default a space) until it's a certain number of characters long. Here, that's the number of spaces the letters can land on, thus mirroring the distribution we need.
r.shuffle(d) naturally shuffles said distribution to be actually... distributed.
The loop, for c in g: o+=m if c==(0,0)else d.pop()if c in p else" ", looks over the entire square of feasible tiles, regardless of anything possibly landing on it or not, and as necessary, adds a character to our output string o. Characters are popped out of our sample of debris so that they only appear once.
if c[1]==l:o+="\n" — Adds line breaks as well. Returns.

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


text:
Find our neighbors
You live in a rectangular neighborhood which is completely partitioned into N rectangular plots, i.e. there are no gaps or overlaps. Plots do not necessarily have the same width/height as other plots. All widths/heights are positive integers. Your goal is to output all shared edges between plots.
Inputs
The input may come from any source desired (stdio, file, function parameters, etc.). The input is a list-like sequence of rectangles. Inputs for rectangles may be any form desired, for example (min_x, max_x, min_y, max_y), (min_x, min_y, width, height), (min_x, min_y, max_x, max_y), etc.
The neighborhood is bounded by min_x = 0 and min_y = 0. You may assume max_x and max_y of the neighborhood both fit in your language's native integer type.
You may flatten the input data into a 1D sequence if desired.
The id of a plot is a sequentially incremented integer based on the order of input, where the first plot may have any id desired.
Outputs
The output may be to any desired target (stdio, file, return value, output parameter, etc.).
The output is a list of lists of neighbors for each plot. A neighbor is defined as the id of the neighboring plot and the min/max bounds of the shared corner/edge. Shared corners/edges with the corner/edge of the neighborhood are not considered a neighbor relation and should not be outputted.
When printing out make some distinction between each list, for example using a newline to separate the neighbors of plot i from the neighbors of plot i+1.
The order of the neighbors of plot i is not important.
Example Test Cases
All listed test case inputs are of the format min_x, max_x, min_y, max_y and plot IDs start with 0. Outputs are formatted as (id, min_x, max_x, min_y, max_y).
Input:
0, 1, 0, 1

Output:
no output, empty list, list containing a single empty list, or anything similar such as null

Input:
0, 1, 0, 1
0, 1, 1, 2

Output:
(1, 0, 1, 1, 1)
(0, 0, 1, 1, 1)

Input:
0, 2, 1, 2
0, 2, 0, 1

Output:
(1, 0, 2, 1, 1)
(0, 0, 2, 1, 1)

Input:
0, 1, 0, 1
0, 1, 1, 2
0, 1, 2, 3

Output:
Regions with no neighbor relationships may be omitted.
(1, 0, 1, 1, 1)
(0, 0, 1, 1, 1), (2, 0, 1, 2, 2)
(1, 0, 1, 2, 2)

It is also ok to output the id of the other region with some indication of "no shared boundary".
(1, 0, 1, 1, 1), (2)
(0, 0, 1, 1, 1), (2, 0, 1, 2, 2)
(1, 0, 1, 2, 2), (0, falsy)

Input:
0, 1, 0, 1
0, 1, 1, 2
1, 2, 0, 2

Output:
(1, 0, 1, 1, 1), (2, 1, 1, 0, 1)
(0, 0, 1, 1, 1), (2, 1, 1, 1, 2)
(0, 1, 1, 0, 1), (1, 1, 1, 1, 2)

One possible alternative output (switched order of neighbors for plot 0):
(2, 1, 1, 0, 1), (1, 0, 1, 1, 1)
(0, 0, 1, 1, 1), (2, 1, 1, 1, 2)
(0, 1, 1, 0, 1), (1, 1, 1, 1, 2)

Input:
You may have corner neighbors.
0, 1, 0, 1
0, 1, 1, 2
1, 2, 0, 1
1, 2, 1, 2

Output:
(1, 0, 1, 1, 1), (2, 1, 1, 0, 1), (3, 1, 1, 1, 1)
(0, 0, 1, 1, 1), (2, 1, 1, 1, 1), (3, 1, 1, 1, 2)
(0, 1, 1, 0, 1), (1, 1, 1, 1, 1), (3, 1, 2, 1, 1)
(0, 1, 1, 1, 1), (1, 1, 1, 1, 2), (2, 1, 2, 1, 1)

Scoring
This is code golf; shortest code wins.
edit clarification that corner neighbors should be outputted as well. Also clarified that if two regions don't share any corners/edges the relation may be completely omitted, or a relation with a falsy edge bounds may be outputted. Both have test cases added.

Wouldn't the output format be simpler if it was the two neighbours and their shared edge together, instead of repeating each shared edge twice? Also are plots considered touching across corners?

@MartinBüttner Yes, corners count as neighbors. See edit for new test case. I had considered outputting a single neighbor relation instead of duplicating them, but at the time for the larger problem I was solving it was much more convenient to have them separate so this is what you get as well.

Mathematica, 179 171 bytes
If[Depth@#2>2,Flatten/@(Thread@{##}/.Line->List)]&~MapThread~{Range@Length@#~Subsets~{2}-1,RegionIntersection/@Subsets[Line@{{##3},{#,#4},{#,#2},{#3,#2},{##3}}&@@@#,{2}]}&

Test cases
Inputs and outputs are list of elements in form {x1, y1, x2, y2}.
%[{{0, 0, 1, 1}, {0, 1, 1, 2}, {1, 0, 2, 2}}]
(*
   {{{0, 0, 1, 1, 1}, {1, 0, 1, 1, 1}},
    {{0, 1, 0, 1, 1}, {2, 1, 0, 1, 1}},
    {{1, 1, 1, 1, 2}, {2, 1, 1, 1, 2}}}
 *)

Why the Nothing?

@LegionMammal978 It is possible that two regions have no common boundary, in which case, Nothing instead of Null will not appear in the output list.

In that case, couldn't you use 1<0 to indicate a falsey value?

@LegionMammal978 Expressions other than Nothing, like False or Null, will appear in the list as elements.

Is there also a problem with using None, then?

@LegionMammal978 There is.

Which is...? None can also mean Nothing, and the OP didn't put an exact specification on the output format.

Let us continue this discussion in chat.

Mathematica 123 134 bytes
g@d_:=Subsets[MapIndexed[List,Apply[Rectangle,d,1]],{2}]/.{{a_,{i_Integer}},
{b_,{j_}}}:>{{i-1,r=RegionIntersection[a,b][[1]]},{j-1,r}}

I prefer this version, at 123 bytes, which returns graphics objects instead of mere coordinates.  It also avoids redundancy, using by MartinBüttner's suggestion,  by listing two rectangle numbers followed by a Line[{{x1,y1},{x2,y2}}] in the case of a shared edge, and Point[{x,y}] in the case of a shared corner.
f@d_:=Subsets[MapIndexed[List,Apply[Rectangle,d,1]],{2}]/.
{{a_,{i_Integer}},{b_,{j_}}}:>{{i,j}-1,r=RegionIntersection[a,b]}

f[{{{0, 0}, {1, 1}}}]

{}

f[{{{0, 0}, {1, 1}}, {{0, 1}, {1, 2}}}]

{{{0, 1}, Line[{{0, 1}, {1, 1}}]}}

f[{{{0, 1}, {1, 2}}, {{0, 0}, {2, 1}}}]

{{{0, 1}, Line[{{0, 1}, {1, 1}}]}}

Shared edges, corners, areas, formatted to a grid for clarity.
f[{{{0, 0}, {1, 1}}, {{0, 1}, {1, 2}}, {{.5, .5}, {1.3, 1.5}}, {{1,
 0}, {2, 1}}, {{1, 1}, {2, 2}}}] // Grid

Python, 189 characters
for p in i:
    for q in i:
        for t in 0,2:
            v,a,b=p[3-t],min(p[1+t],q[1+t]),max(p[t],q[t])
            w,z=[v,v],[b,a]
            if v==q[2-t]and a>b:
                for d in p,q:
                    print[i.index(d)]+(w+z,z+w)[t/2]

The input is given as a list like

i = [[0, 1, 0, 1], [0, 1, 1, 2], [1, 2, 0, 2]]

JavaScript (ES6), 228
Input / output as an array of arrays.
Format as in OP testcases:

inputs min_x, max_x, min_y, max_y.
outputs id (0 based), min_x, max_x, min_y, max_y.

l=>l.map(([x,r,y,s],i)=>l.map(([t,v,u,w],j)=>i-j&&(n=x-t&&x-v,m=r-t&&r-v,u>=s|w<=y||n&&m||q.push([j,z=m?x:r,z,y>u?y:u,s<w?s:w]),n=y-u&&y-w,m=s-u&&s-w,t>=r|v<=x||n&&m||q.push([j,x>t?x:t,r<v?r:v,z=m?y:s,z])),o.push(q=[])),o=[])&&o

This can probably be shortened merging the horizontal and vertical check
TEST

f=l=>
  l.map(([x,r,y,s],i)=>
    l.map(([t,v,u,w],j)=>
      i-j&&(
        n=x-t&&x-v,m=r-t&&r-v,u>=s|w<=y||n&&m||q.push([j,z=m?x:r,z,y>u?y:u,s<w?s:w]), // vertical
        n=y-u&&y-w,m=s-u&&s-w,t>=r|v<=x||n&&m||q.push([j,x>t?x:t,r<v?r:v,z=m?y:s,z])  // horizontal
      )
    ,o.push(q=[]))
  ,o=[])&&o

ArToStr=(a,s)=>a.map?(s?'[':'[\n ')+a.map(x=>ArToStr(x,1)).join(s?',':',\n ')+(s?']':'\n]\n'):a

console.log=x=>O.textContent+=x+'\n';

console.log(ArToStr(f([[0,1,0,1]])))
console.log(ArToStr(f([[0,1,0,1],[0,1,1,2]])))
console.log(ArToStr(f([[0, 2, 1, 2],[0, 2, 0, 1]])))
console.log(ArToStr(f([[0, 1, 0, 1],[0, 1, 1, 2],[1, 2, 0, 2]])))


text:
The Möbius Function
The Möbius function is an important number theoretic function.
Your submission should accept a positive integer \$n\$ and return the value of the Möbius function evaluated at \$n\$.
Definition
The Möbius function \$μ(n)\$ is defined as follows:
$$\mu(n) = \begin{cases}
\hphantom{-}1, &n\text{ is squarefree and has an even number of distinct prime factors} \\
-1, &n\text{ squarefree and has an odd number of distinct prime factors} \\
\hphantom{-}0, &\text{otherwise}
\end{cases}$$
\$n\$ is called squarefree if the exponents of the prime factorization of \$n\$ are all strictly less that two. (Alternatively: No prime to the power of two divides \$n\$).
Test cases
Here you can see the first 50 values of μ:

Public Domain Image from Wikipedia
The Möbius function is sequence number A008683 in the OEIS.
These are the first 77 values:
1, -1, -1, 0, -1, 1, -1, 0, 0, 1, -1, 0, -1, 1, 1, 0, -1, 0, -1, 0, 1, 1, -1, 0, 0, 1, 0, 0, -1, -1, -1, 0, 1, 1, 1, 0, -1, 1, 1, 0, -1, -1, -1, 0, 0, 1, -1, 0, 0, 0, 1, 0, -1, 0, 1, 0, 1, 1, -1, 0, -1, 1, 0, 0, 1, -1, -1, 0, 1, -1, -1, 0, -1, 1, 0, 0, 1

Larger values can also easily be checked in Wolframalpha.com or in the b-file of OEIS, as suggested by @MartinBüttner.

Python 2, 48 bytes
m=lambda n,d=1:d%n and-m(d,n%d<1)+m(n,d+1)or 1/n

Earlier 51 byte version:
m=lambda n:1/n-sum(m(k)for k in range(1,n)if n%k<1)

Möbius-inverts the sequence 1,0,0,0,0....
The Möbius function has the property that for any n>1, the Möbius functions of n's divisors sum to 0. So, for n>1, μ(n) is computed by negating the sum of μ(k) for all proper divisors k of n. For n=1, the output is 1.
The code handles the base case by adding a floor-division 1/n, which gives 1 for n==1 and 0 otherwise.
Thanks to Dennis for saving 3 bytes with better recursive handling inspired by a similar structure in this challenge.

Jelly, 7 bytes
Code:
ÆF>1’PS

Explanation:
ÆF       # This computes the prime factorization as well as the exponent
  >1     # Compares each element if it's greater than 1, resulting in 1's and 0's
    ’    # Decrement on each element
     P   # Compute the product
      S  # Compute the sum of the list

For example, the number 10:
ÆF       # [[2, 1], [5, 1]]
  >1     # [[1, 0], [1, 0]]
    ’    # [[0, -1], [0, -1]]
     P   # [0, 1]
      S  # 1

And results in 1.
Try it online.

-1 byte: ÆFỊNPS (not sure if Ị was a built-in back then, but should be fine now).

Mathematica, 9 bytes
MoebiusMu

Of course, Mathematica has a built-in. (And will probably be is beaten by Jelly anyway.)

CJam, 18 15 bytes
WrimFz~\1&+f/:*

The fact that CJam returns 1 in factorisation builtins for n = 1 makes things a bit tricky.
Try it online | Test suite
Thanks to @PeterTaylor for the neat 1&+ trick for handling the 1 case.
Explanation
W                 Push -1
 ri               Push input as int
   mF             Factorise input into [base exponent] pairs
     z~           Zip and unwrap pairs, leaving stack like [-1 bases exponents]
       \1&        Setwise intersect bases with 1, giving [1] for 1 and [] otherwise
          +       Append to exponent array
           f/     Divide the previously pushed -1 by each element in the array
                  This gives -1 for 1s and 0 otherwise, since / is int division
             :*   Take product

For n > 1, the modified array is just the exponents array. If n is squarefree then the array is all 1s, which become all -1s after division. Otherwise, if n has a prime square divisor, then there will be a 0 somewhere after division, giving a product of 0.
For n = 1 the modified array is [1] + [1], which becomes [-1 -1] after division, giving a product of 1.

Alternative 16:
rimF{1#2+3%(}%:*

This uses # (find) on each [base exponent] array to look for a 1, then maps -1 -> 0, 0 -> 1, 1 -> -1.

Ruby, 65+7=72 62+7=69 bytes
->x{((d=x.prime_division).all?{|_,n|n<2}?1:0)*(d.size%2*-2+1)}

+7 bytes for the -rprime flag.
We're doing this the very naïve way:
->x{
 (
  (d=x.prime_division)  # ex. input 20 results in [[2,2],[5,1]] here
  .all?{|_,n|n<2}?      # are all factors' exponents under 2?
  1:0                   # if so, result in a 1; otherwise, a 0
 )
 *                      # multiply that 1 or 0 by...
  (d.size%2*-2+1)       # magic
}

The "magic" part results in 1 if the number is even and -1 otherwise. Here's how:
Expression       Even  Odd
--------------------------
d.size%2         0     1
d.size%2*-2      0     -2
d.size%2*-2+1    1     -1

Labyrinth, 87 bytes
1
:
}
?   @ "}){/{=:
""({! "      ;
} )   :}}:={%"
* _}}){     ;
{      #}):{{
")`%#/{+

Try it online!
Short explanation
Here's a port of the algorithm used, in Python:
divisor = 1
mobius = 1
n = int(input())

while n != 1:
  divisor += 1
  count = 0

  while n % divisor == 0:
    n //= divisor
    count += 1

  mobius *= (count + 3)//(count + 1)%3*-1 + 1

print(mobius)

Long explanation
The usual primer on Labyrinth:

Labyrinth is stack-based and two-dimensional, with execution starting at the first recognised character. There are two stacks, a main stack and an auxiliary stack, but most operators only work on the main stack.
At every branch of the labyrinth, the top of the stack is checked to determine where to go next. Negative is turn left, zero is straight ahead and positive is turn right.

Execution for this program starts at the top-left 1.
Outer preparation
=================

1        Pop 0 (stack is bottomless and filled with 0s) and push 0*10+1 = 1
:}       Duplicate and shift to auxiliary stack
?        Read int from input
         Stack is now [div=1 n | mob=1]

Top of stack positive but can't turn right. Turn left into outer loop.

Begin outer loop
================
Inner preparation
-----------------

(        Decrement top of stack

If top was 1 (and is now zero), move forward and do...
------------------------------------------------------

{!       Print mob
@        Terminate

If top of stack was greater than 1, turn right and do...
--------------------------------------------------------

)        Increment n back to its previous value
_}       Push 0 and shift to aux
         This will count the number of times n can be divided by div
}){      Increment div
         Stack is now [div n | count mob]

Inner loop
----------

:}}      Dup n, shift both n's to aux
:=       Dup div and swap top of main with top of aux
{%       Shift div down and take mod
         Stack is now [div n%div | n count mob]

If n%div == 0, move forward and do...
-----------------------------------

;        Pop n%div
:={/     Turn n into n/div
{)}      Increment count
         (continue inner loop)

If n%div != 0, turn right (breaking out of inner loop) and do...
================================================================

;        Pop n%div
{{       Pull n and count from aux
:)}      Dup and increment count, giving (count+1), and shift to aux
#+       Add length of stack to count, giving (count+3)
{/       Calculate (count+3)/(count+1)
#%       Mod by length of stack, giving (count+3)/(count+1)%3
`        Multiply by -1
)        Increment, giving (count+3)/(count+1)%3*-1 + 1
         This is 1 if count was 0, -1 if count was 1 and 0 if count > 1
{*}      Multiply mob by this number
         (continue outer loop)

05AB1E, 8 bytes
Code:
.p0K1›<P

Explanation:
.p        # Get the prime factorization exponents
  0K      # Remove all zeroes from the list
    1›    # Compare each element if greater than 1
      <   # Decrement on each element
       P  # Take the product

Uses the CP-1252 encoding

› isn't in ISO 8859-1...

@ETHproductions Heh? What kind of encoding is it then? I got it from this site.

I believe it's called Extended ASCII.

@ETHproductions Thanks, I have edited the post :)

@ThomasKwa Ahh, I have found it. It is the CP-1252 encoding.

Pyth, 9 bytes
^_{IPQlPQ

Explanation:
^_{IPQlPQ    Implicit: Q=input
    PQ       Prime factorization of Q
  {I         Is invariant under uniquify.
  {IPQ       1 if Q is squarefree; 0 otherwise.
 _{IPQ       -1 if Q is squarefree; 0 otherwise.
^     lPQ    Exponentiation to length of PQ.

Try it here.

Java 8, 72 68 65 64 bytes
n->{int r=1,i=1;for(;i++<n;)r=n%i<1?(n/=i)%i<1?0:-r:r;return r;}

-4 bytes thanks to @PeterTaylor.
Port of @Meerkat's .NET C# answer, which I first golfed a bit further, so make sure to upvote him!
Try it online.
Explanation:
n->{                // Method with integer as both parameter and return-type
  int r=1,          //  Result-integer, starting at 1
  i=1;for(;i++<n;)  //  Loop `i` in the range [1, n]:
    r=n%i<1?        //   If `n` is divisible by `i`:
       (n/=i)       //    Divide `n` by `i` first
        %i<1?       //    And if `n` is still divisible by `i`:
         0          //     Change `r` to 0
        :           //    Else:
         -r         //     Swap the sign of `r` (positive to negative or vice-versa)
      :             //    Else:
       r;           //     Leave `r` unchanged
  return r;}        //  Return `r` as result

See my comment on Meerkat's answer.

@PeterTaylor Smart, thanks! And then 3 more bytes can be saved by using r=n%i<1?(n/=i)%i<1?0:-r:r;.

CJam, 20 bytes
rimf1-___&=\,2%!2*(*

Run it against a range of inputs here.
Seems golfable.

The fact that 1 is returned in mf or mF really hurts...

@Sp3000 Tell me about it :-(

R 3916 bytes
numbers::moebius

Requires you having the numbers package installed on your system...
Edit: Far simpler if I read the specs appropriately [thanks @AlexA.]

This returns the Möbius function evaluated for each integer from 1 to the input, but the task for this challenge is simply to evaluate the Möbius function on the input.

Along the lines of the Mathematica answer, you could even do simply numbers::moebius for 16 bytes.

Factor + math.extras, 6 bytes
mobius

Attempt This Online!

Pyth, 16 Bytes
?nl{PQlPQZ^_1lPQ

Try it online!
My first actual Pyth answer. Suggestions appreciated! :)
Explanation
My solution uses the fact that a number is squarefree, if its prime-factors contain no number more than once. If the input is squarefree, the Möbius-Function takes the value -1^(number of primefactors).

?n        if not equal
  l{PQ      length of the list of the distinct input-Primefactors
  lPQ       length of the list of primefactors including duplicates
    Z         Input is not squarefree, so output Zero
  ^_1lPQ  if input is squarefree, output -1^(number of prime-factors)

MATL, 15 17 bytes
tq?YftdAwn-1w^*

This uses current release (10.1.0) of the language/compiler.
Try it online!
Explanation
t         % implicit input. Duplicate that
q         % decrement by 1. Gives truthy (nonzero) if input exceeds 1
?         % if input exceeds 1, compute function. Otherwise leave 1 on the stack
  Yf      % vector of prime factors. Results are sorted and possibly repeated
  td      % duplicate and compute differences
  A       % true if all differences are nonzero
  w       % swap
  n       % number of elements in vector of prime factors, "x"
  -1w^    % -1^x: gives -1 if x odd, 1 if x even
  *       % multiply by previously obtained true/false value, so non-square-free gives 0
          % implicitly end "if"
          % implicitly display stack contents

C# (.NET Core), 86 73 72 65 bytes
a=>{int b=1,i=1;for(;++i<=a;)b=a%i<1?(a/=i)%i<1?0:-b:b;return b;}

Try it online!
-13 bytes: streamlined loops, added return variable (thanks to Kevin Cruijssen)
-1 byte: changed setting b to zero to a ternary from an if (thanks to Kevin Cruijssen)
-7 bytes: changed if statement in for loop to a ternary (thanks to Peter Taylor and Kevin Cruijssen)
Ungolfed:
a => {
    int b = 1, i = 1;           // initialize b and i to 1

    for(; ++i <= a;)            // loop from 2 (first prime) to a
        b = a % i < 1 ?                     // ternary: if a is divisible by i
            ((a /= i) % i < 1 ? 0 : -b) :   // if true: set b to 0 if a is divisible by i squared, otherwise flip sign of b
            b;                              // if false: don't change b

    return b;                   // return b (positive for even numbers of primes, negative for odd, zero for squares)
}

73 bytes I've changed int b=1;for(int i=1; to int b=1,i=1;for(;. Removed the {}-brackets for the loop. Changed both a%i==0 to a%i<1. Changed the b*=-1; to b=-b;. And finally changed the return 0; to b=0;.

Yeah, everything you suggested looked correct. I was ever so slightly worried when you said it wasn't right, because that would've meant my original code was wrong too! :)

Yeah, sorry about that. :) 1 more byte to golf btw is if(a%i<1)b=0; to b=a%i<1?0:b;.

Oh, and if you haven't seen them yet, Tips for golfing in c# and Tips for golfing in  might be interesting to read through. Enjoy your stay! :)

return is so expensive that the same score can be achieved by a function with terminating semicolon: int f(int a,int b=1,int i=1)=>++i>a?b:a%i<1?f(a/=i,a%i<1?0:-b):f(a,b,i);

Actually, that overlooks an easy improvement: b=-b;b=a%i<1?0:b; golfs to b=a%i<1?0:-b;

Continuing on @PeterTaylor's golf above, you can then change if(a%i<1){a/=i;b=a%i<1?0:-b;} to b=a%i<1?(a/=i)%i<1?0:-b:b; to save 3 more bytes.

It's been a while (as in 4+ years xD). ++i<=a can be i++<a for -1 byte.

Pyth, 11
*{IPQ^_1lPQ

Test suite
This multiplies the boolean value of if the prime factors are squarefree by -1 to the power of the number of prime factors that the number has.
I is an invariance check on the preceeding operator, which here is {, which is the unique-ify operator.

Japt, 21 bytes
V=Uk)¬¥Vâ ¬?Vl v ªJ:0

Test it online!

Seriously, 19 18 bytes
,w;`iX1=`Mπ)l1&τD*

Try it online!
Explanation:
,w;`iXDY`Mπ)l1&τD*
,w;                push two copies of the full prime factorization of the input
                      (a list of [base, exponent] pairs)
   `    `M         map the following function:
    iX1=             flatten list, discard, equal to 1
                        (push 1 if exponent == 1 else 0)
          π)       product of list, push to bottom of stack
            1&     push 1 if the # of prime factors is even else 0
              τD   double and decrement (transform [0,1] to [-1,1])
                *  multiply

Julia, 66 bytes
n->(f=factor(n);any([values(f)...].>1)?0:length(keys(f))%2>0?-1:1)

This is a lambda function that accepts an integer and returns an integer. To call it, assign it to a variable.
Ungolfed:
function µ(n::Int)
    # Get the prime factorization of n as a Dict with keys as primes
    # and values as exponents
    f = factor(n)

    # Return 0 for non-squarefree, otherwise check the length of the list
    # of primes
    any([values(f)...] .> 1) ? 0 : length(keys(f)) % 2 > 0 ? -1 : 1
end

PARI/GP, 7 bytes
moebius

Sadly möbius is not available. :)

Julia, 35 bytes
\(n,k=1)=k%n>0?n\-~k-k\0^(n%k):1÷n

Based on @xnor's Python answer. Try it online!

Seriously, 11 bytes
Golfing suggestions welcome. Try it online!
;y;l0~ⁿ)π=*

Ungolfing
     Implicit input n.
;    Duplicate n.
y    Push a list of the distinct prime factors of n. Call it dpf.
;    Duplicate dpf.
l    Push len(dpf).
0~   Push -1.
ⁿ    Push (-1)**len(dpf).
)    Rotate (-1)**len(dpf) to BOS. Stack: dpf, n, (-1)**len(dpf)
π    Push product(dpf).
=    Check if product(dpf) == n.
      This is only true if n is squarefree.
*    Multiply (n is squarefree) by (-1)**len(dpf).
     Implicit return.

Nice solution=) (I guess however that this language is younger that the question, is it?)

@flawr Apparently the answer works just as well in Seriously, and I don't know when Actually first came online, so I changed to Seriously just to be safe.

J, 18 bytes
[:*/3<:@|2+2<._&q:

GNU sed, 89 bytes
#!/bin/sed -rf
s/.*/factor &/e
s/.*://
/\b([0-9]+) \1\b/!{
s/[0-9]+//g
s/$/1/
s/  //g
y/ /-/
}
s/ .*/0/

Microsoft Office Excel, British version, 196 bytes
=IF(ROW()>=COLUMN(),IF(AND(ROW()=1,COLUMN()=1),1,IF(COLUMN()=1,
-SUM(INDIRECT(ADDRESS(ROW(),2)&":"&ADDRESS(ROW(),ROW()))),
IF(MOD(ROW(),COLUMN())=0,INDIRECT(ADDRESS(FLOOR(ROW()/COLUMN(),1),
1)),""))),"")

Excel cell formula to be entered in cells A1 to AX50.

Javascript (ES6), 48 bytes
f=(n,i=1)=>n-1?n%++i?f(n,i):(n/=i)%i?-f(n,i):0:1

First of all - this is my first code golf post so I may misunderstand the rules to some extent. In this submission the last character ; could be omitted and it'll still work but I'm not even sure if the code would be valid according to the ES6 specs. Anyways, a short explanation.
First, I'll explain the idea a bit; we take n, and we try dividing it by the integer i. If it's divisible, then we do so and we check if it's divisible by i again. If that's the case, then we need to return 0. Otherwise, we can try another i. The cool thing is, we can just start at i=2 and just add increase it by 1 every time, so that we divide out all the prime factors.
So, the code works like this:
f=(n,i=1)=>                                           We will increase i by one at the start of
                                                         the function body, so default is 1
           n-1?                                       Check if n==1.
               n%++i?                                 If i isn't, increase i by 1, check if n
                                                         is divisible by i
                     f(n,i):                          if it isn't, we check the next i
                            (n/=i)%i?                 if it is, divide n by i, and check for
                                                         divisibility by i again
                                     -f(n,i):         if it not, then we flip the value to
                                                         account for the 1 and -1 depending on the
                                                         amount of factors
                                             0:       if it's divisible by i twice, done.
                                               1      if we're at 1, divided out all factors,
                                                         then we return 1. The line with
                                                         -f(n,i) will then take care of the sign

So, that's my submission.

Welcome to the site.  I don't know js, but I can tell you that here we don't care about specs, only implementations.  So if removing ; doesn't break it, it doesn't matter the specs you can remove it.

Good to know! I'll remove it then ;)

Haskell, 96 bytes
import Data.Numbers.Primes
import Data.List
m=(\f->last$0:[(-1)^length f|f==nub f]).primeFactors

Try it online!

Vyxal, 47 bitsv1, 5.875 bytes
ǐÞu$†Ǎ*

Try it Online!
What do you mean it's not morbin' time? I love vyncode and how just re-arranging things makes the program shorter.
Explained
ǐÞu$†Ǎ*
ǐ       # prime factors of input with duplicates
 Þu     # all unique?
   $†Ǎ  # -1 ** len(prime_factors(input))
      * # multiply

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


text:
List Prime Numbers
Introduction
Prime numbers are simple, right? Well, now you get your chance to find out!
Challenge
You must write a program or function that takes an input n and outputs the first n prime numbers.
Example Input and Output
Input: 10
Output: 2,3,5,7,11,13,17,19,23,29
Rules

You must not include any of the following builtin functions:

A list of prime numbers
Primality testing
Next prime
Prime factorization
List of divisors

Your output must be in a convenient, unambiguous list format.

This is code-golf, so the shortest answer in bytes wins.

Rule 2 still requires clarification. Does it cover nth prime functions? Next prime functions? Factorization? None of this makes use of a list.

@Dennis To clarify: it covers built in prime functions, next prime function, and factorization.  You need to create the prime testing function yourself.

@feersum That's most definitely not a duplicate. Your linked question involves time complexity in the scoring system.

By the way, there is no need to specify rule 1 (it applies by default), and rule 3 is one of the things to avoid when writing challenges.

Are built-ins allowed that get you a list of divisors or the prime factorisation? Also, by default input and output in unary or as byte values is allowed. If that's not what you want, you should explicitly say that input and output will be decimal. And you should clarify if n can be 0 or will always be positive.

@MartinBüttner i/o in unary/byte values is allowed.  Prime factorization and list of divisors are not allowed.

@ElliotA. Please edit the question when clarifying. Comments are not permanent.

I have voted to close as a duplicate of "find the first n composite numbers" because the difference should be a single logical negation in most languages.

@PeterTaylor But, they're not the same.

@ElliotA. They are related closely enough to be considered duplicates on this site. One could copy an answer from one challenge to the other with a trivial change (negating or not negating a logical condition), which makes them duplicates as far as PPCG is concerned.

Jelly, 14 11 bytes
‘²R©’!²%®Oḣ

Uses Wilson's theorem for the primality test. Try it online!
How it works
‘²R©’!²%®Oḣ     Main link. Input: n

‘               Increment. Yields n + 1.
 ²              Square. Yields (n + 1)².
  R             Range. Yields [1, ..., (n + 1)²].
                This range will always contain max(n,2) or more prime numbers.
   ©            Store the range in the register.
    ’           Decrement. Yields [0, ..., (n + 1)² - 1].
     !          Factorial. Yields [0!, ..., ((n + 1)² - 1)!].
      ²         Square. Yields [0!², ..., ((n + 1)² - 1)!²].
       %®       Mod by the range in the register.
                This yields [0!² % 1, ..., ((n + 1)² - 1)!² % (n + 1)²].
                By Wilson's theorem this gives 1 for primes and 0 for non-primes.
         O      Find the indices of 1's. This yields all prime number in the range.
          ḣ     Keep the first n items.

Java, 116 113 bytes
Saved 3 bytes thanks to @CamilStaps in a regex reduction!
void x(int c){for(int i=2;c>0;i++)if(!new String(new char[i]).matches("(..+?)\\1+")){System.out.println(i);c--;}}
Uses regex to test primality, prints if it is, else, it continues. Call on an instance of your class as .x(10).
Output for x(10):
2
3
5
7
11
13
17
19
23
29

How can you test for primality by regex?

@flawr It does division of the number in unary. It's the same thing as testing with a for loop and modulo-ing up to it, essentially.

Move the c-- into the condition in the loop and the i++ into the body

@Loovjo Won't work - c-- doesn't happen in ever occurrence of the loop. Putting i++ in char[i] will produce incorrect output, and putting it inside of println(i) won't always get executed, causing an infinite loop.

Very nice. You can remove the .?| from the regex: since you're already starting with i=2, you don't need to check for 0 and 1.

@CamilStaps Thanks - this is my standard Java primality testing code, I forgot to remove that bit of the test. :P

By the way, this seems just like your challenge :)

@CamilStaps Unfortunately not. Java can't handle arbitrary precision numbers (look at the rules carefully - "Your program should work on any length input (given enough memory and time).")

@FlagAsSpam you're right, that's a shame though

C, 125 bytes
Most likely I'm not going to win against the Jelly solution haha.
Anyway here's my solution in C. It's not commented and it's very compact to reduce the size of the program.
125 bytes.
c,h,i,j;g(n){for(j=2;j*j<=n;j++)if(n%j<1)return 1;return 0;}main(){scanf("%i",&h);for(i=2;c<h;i++)g(i)?:printf("%i ",i,c++);}

Perhaps is not a small-sized program, but by far the most neat :)

Welcome to Programming Puzzles & Code Golf! According to the rules in our help center, all submissions to a code golf challenge must be golfed. At the very least, you should get rid of the whitespace and shorten your variable names.

Thanks @Dennis, will shorten the code :). Was not aware of that.

I cutted some whitespaces off and reduced names. Here should be the same program but with 218 bytes, http://pastebin.com/jysj1uTT.

@xjose97x No problem :) You could also reduce couple of brackets it seems... If you have one statement inside two brackets, you can throw the brackets away.

As is, this always prints the first 10 primes. Also, there's a lot of extra output (Output:, Prime ) that can be removed. Without changing your algorithm, you can get down to 125 bytes: c,h,i,j;g(n){for(j=2;j*j<=n;j++)if(n%j<1)return 1;return 0;}main(){scanf("%i",&h);for(i=2;c<h;i++)g(i)?:printf("%i ",i,c++);}

@Dennis, thanks for noticing that. i forgot I left it to output 10. Did that for testing purposes. Now it's fixed.

And you're right, now it's 125 bytes.

Pyth, 12 bytes
.fq2/%LZSZ0Q

This uses trial division to check primality.
.f         Q   find first Q positive integers that satisfy lambda Z:
    /     0      the number of zeroes
     %LZ         in map modulo-Z-by
        SZ       over inclusive range 1 to Z
  q2             equals 2

Try it here.

MATL, 16 bytes
2iq:"t`Qtt:\~z2>

This uses current release (10.1.0) of the language/compiler.
Try it online!
Explanation
This uses two nested loops. The outer one produces each prime, and the inner one increases 1 by 1 from latest found prime until the next prime is found.
To test for primality a modulo operation is used: x is prime if computing mod(x,k) for k=1,2,...,x produces no more than two zeros; that is, if only two numbers of the set 1,2,...,x divide x.
2        % push 2 (first prime) to the stack
i        % input number, "n"
q:       % generate vector [1,2,...,n-1]
"        % "for" loop. This runs n-1 times, to find the n-1 primes after 2
  t      % duplicate top of the stack, which contains the latest found prime, "p"
  `      % "do...while" loop. This searches for the next prime
    Q    % increament top of stack by 1. This is the current candidate for next prime, "x"
    t    % duplicate top of the stack (x)
    t:   % produce vector [1,2,...,x]
    \    % compute mod(x,k) for k=1,2,...,x
    ~2>  % if that gives more than two zeros: x is not prime: we need another iteration
         % implicitly end "do...while" loop
         % implicitly end "for" loop
         % implicitly display stack contents

Dyalog APL, 18 bytes
{⍵↑(⊢~∘.×⍨)1↓⍳2*⍵}

Generates a multiplication table from 2 to 2^n. The prime numbers are those that don't occur, so we take the first n of those.
Try it here.

Haskell, 46 bytes
(`take`[x|x<-[2..],mod(product[1..x-1]^2)x>0])

Using @Mauris'/@xnor's prime checker.

Computing the primes list and factorial iteratively gave the same length k%p=[k|p`mod`k>0]++(k+1)%(p*k*k)\n(`take`(1%1)).

Perl 6,  39  37 bytes
{(2..*).grep({![+] $_ X%%2..^$_})[^$_]} # 39 bytes
{(2..*).grep({none $_ X%%2..^$_})[^$_]} # 39 bytes
{(2..*).grep({all $_ X%2..^$_})[^$_]}   # 37 bytes

Usage:
say {(2..*).grep({all $_ X%2..^$_})[^$_]}( 10 );
# (2 3 5 7 11 13 17 19 23 29)

(2..$n).grep({!(2..$_.sqrt.Int).grep($_%%*)}) #45 bytes but less comparissons

@MattOates {(2..*).grep({!first $_%%*,(2.. .sqrt)})[^$_]} would be even more efficient. It takes 0.18 secs for 100 primes vs 15.36 secs for what I have above. The most time efficient for 1000 primes I have come up with is {(2,3,5,7...*).grep({!first $_%%*,(3.. .sqrt)})[^$_]} (It's 0.19 sec for 100 primes though) You have to have the limit outside of your generator so that you can reliably generate 10 primes if given the number 10.

AppleScript (through osascript), 201 158 bytes
If you're wondering how I saved that many bytes: I changed it from AppleScript to osascript (AppleScript from the command line) and used the main method equivalent (on run x) to grab arguments at way less bytes.
It's back. The most annoyingly verbose yet awesome language that I've used...
AppleScript.
on run x
set b to 1
repeat while x>0
set b to b+1
set c to 1
repeat while c<b
set c to c+1
if b mod c=0 then exit
end
if b=c
log c
set x to x-1
end
end
end

Chapel, 108 bytes
This is the simple trial division method.  I tried Wilson's theorem but came up with something slightly longer.
var n=0;read(n);var f=0;var q=0;while(f<n){q+=1;for i in 2..q{if(i==q){writeln(q);f+=1;}if(q%i==0){break;}}}

Chapel is a language designed to run on Cray supercomputers, but I installed it on my laptop.  I literally downloaded the language and learned how to write the above program in a total of 2 hours.
The language has some interesting features, there is a pretty through X in Y minutes page about it.  I'm sure there's some list-based features I haven't seen yet which could cut down on my byte count.
As a bonus stat, this compiles into a 519858-byte executable (based on wc -c).

Oh nice, this is the first time I've seen Chapel here. It's a pretty neat language.

Python 2, 60 bytes
n=input()
k=P=1
while n:
 if P%k:print k
 n-=P%k;P*=k*k;k+=1

Same method as here, Wilson's Theorem, computing the factorial-squared iteratively.
54 bytes as a function:
f=lambda n,k=1,P=1:n*[0]and P%k*[k]+f(n-P%k,k+1,P*k*k)

C#, 207 bytes
using s=System.Console;using System.Linq;class P{static void Main(){int n=int.Parse(s.ReadLine());s.Write(string.Join(",",Enumerable.Range(2,n*n).Where(x=>!Enumerable.Range(2,x-2).Any(y=>x%y<1)).Take(n)));}}

Retina, 43 bytes
Byte count assumes ISO 8859-1 encoding.
+m`^((::+)\2+|:?)1
$1:1
)`(:+)1
$1¶$1:
:+$

The trailing linefeed is significant. Input and output in unary (input using 1 and output using : but any other two printable ASCII characters would work for the same byte count).
Try it online!

Pyth - 13 bytes
Wilson's Theorem
j.f!%h.!tZZQ2

Test Suite.

You don't need the j any more.

Python, 72 bytes
To avoid while statements, it simply computes all the prime numbers up to 3**n and then it returns only the fist n. It works, but it is extremely slow for n >= 7 because of the 3**n.
lambda n:filter(lambda x:all(x%d for d in range(2,x)),range(2,3**n))[:n]

According to out defaults for I/O, you cannot assume that the input is stored in a variable.

@Dennis Now the input comes from the argument of a function.

Unnamed lambdas are also acceptable, and you don't need the square brackets. lambda n:filter(lambda x:all(x%d for d in range(2,x)),range(2,3**n))[:n] is 9 bytes shorter.

@Dennis OK, thanks. Then it is back to 72 bytes.

Befunge 93, 60 bytes
&00p1v<_@#`0p00:-1g00.:<
210pv>1+:
`g01<_v#  %p01+1:g01::_^#

I didn't feel motivated enough to install Befunge 98 to try and use its features to golf this more, but this works quite well in Befunge 93. Try it here. Interestingly, this method also leaves all non-prime numbers on the stack. It works by the method of trial division.

05AB1E, 17 bytes
Uses the same algorithm as Bob's answer. Note that also for this, input greater than 7 will take a while to compute. If you aren't really patient, you can also change the 3 into a 2 in the code.
Code:
3WmGN<!nN%iN}})Z£

Explanation:
3Wm                # 3 ^ input
   G         }     # For N in range(1, 3 ^ input)
    N<!n           # Compute (N - 1)!²
        N%         # mod N
          i }      # If 1
           N       # Place N onto the stack
              )Z£  # Keep the first Z (auto-assigned to input) elements

Uses CP-1252 encoding

Pyth, 14 bytes
.f!}0m%Zdr2ZQ2

Explanation
               - Autoassign Q = eval(input())
.f          Q2 - First Q where ... returns True, starting from 2
         r2Z   - range(2, Z)
     m%Zd      - [Z%d for d in ^]
  !}0          - 0 not in ^

Try it here.

AutoIt, 155 bytes
RegEx to the rescue.
Func _($n,$i=0,$0=2)
Do
$1=''
For $2=1 To $0
$1&='1'
Next
$0+=1
ContinueLoop StringRegExp($1,'^(1?|(11+?)\2+)$')
$i+=1
MsgBox(0,0,$0-1)
Until $i=$n
EndFunc

C#, 316 315 bytes
using System;class P{static void Main(string[]a){int x=int.Parse(Console.ReadLine()),i=0;List<int>b=G(~(2<<30));for(;i<x;i++)Console.WriteLine(b[i]);}static List<int> G(int n){var p=new List<int>();for(var i=2;i<n;i++){var o=0<1;foreach(var k in p){if(k*k>i)break;if(i%k==0){o=1<0;break;}}if(o)p.Add(i);}return p;}}

'Cleaner' & ungolfed version that shows what's happening.
    static void Main(string[]a)
    {
        int x=int.Parse(Console.ReadLine()), i=0;
        List<int> b=G(~(2 << 30));
        for(;i<x;i++)Console.WriteLine(b[i]);
    }
    static List<int> G(int n)
    {
        var p = new List<int>();
        for(var i=2;i<n;i++)
        {
            var o = 0<1;
            foreach (var k in p)
            {
                if (k * k > i)
                    break;
                if (i%k==0)
                {
                    o = 1<0;
                    break;
                }
            }
            if (o)
                p.Add(i);
        }
        return p;
    }

Takes the input from STDIN and prints N primes, each to a new line.
Couple tricks used here are ~(2 << 30), shortened way of saying 2147483647. True and false words have been replaced with 0<1 and 1<0, they'll evaluate accordingly.

Ceylon, 93 bytes
void p(Integer n)=>loop(2)(1.plus).filter((c)=>!(2:c-2).any((d)=>c%d<1)).take(n).each(print);

This is a function which takes an Integer n and prints the first n primes, each in one line.
Here formatted and with comments:
// Print the first n primes.
//
// Question:  https://codegolf.stackexchange.com/q/70001/2338
// My answer: https://codegolf.stackexchange.com/a/70021/2338

void p(Integer n) =>
        // the infinite sequence of integers, starting with 2.
        loop(2)(1.plus)
        // filter by primality (using trial division)
        .filter((c) => !  (2 : c-2).any((d) => c%d < 1) )
        // then take the first n elements
        .take(n)
        // print each element
        .each(print);

This uses the same basic prime check as my answer to the "Is this number prime" question (without the special-casing for 1, which is unnecessary here).
If a full program is needed, we need to incorporate some input, too. With a command line argument it becomes 138 bytes:
shared void run(){loop(2)(1.plus).filter((c)=>!(2:c-2).any((d)=>c%d<1)).take(parseInteger(process.arguments[0]else"")else 0).each(print);}

With reading a line from standard input we get 136 bytes:
shared void run(){loop(2)(1.plus).filter((c)=>!(2:c-2).any((d)=>c%d<1)).take(parseInteger(process.readLine()else"")else 0).each(print);}

Brachylog, 63 bytes
:2{h0|[N:X],X+1=Y,('(X-1=:2reI,X%I=0),Xw,@Nw,N-1=:Y:1&;N:Y:1&)}

'(X-1=:2reI,X%I=0) is the part that checks that a number is prime. the rest is basically setting up a recursive predicate that stops after n primes founds (the h0 part).

Ruby, 75 55 bytes
->n{a=[]
t=2
(a<<t if(2...t).all?{|i|t%i!=0}
t+=1)while !a[n-1]
a}

Works by trial division

Japt, 23 bytes
U+1 ²o f_o2 eY{Z%Y}} ¯U

Test it online!

Javascript ES6, 82 67 Bytes
n=>{for(p=[],i=2;n;i++)!p.some(c=>!(i%c))&&p.push(i)&&n--;return p}

Ungolfed version :
n=>{
    for(p=[],i=2;n;i++)                   //Loop until n prime found
        !p.filter(c=>(i/c|0)==i/c).length //Test if i is not divisible by previous primes
        &&
        p.push(i)                         // If prime add to the list
        &&
        n--;                              // If a prime found, one less to find.
    return p;                             // Return list of primes
}

Changed the function to detect prime number thanks to @neil output.

That isn't ES5.

Assuming you meant ES6, !p.some(c=>!(i%c)) perhaps?

Sorry, Forgot that arrow function is ES6 only.
TIL about array.prototype.some in ES6. Awesome function, will change code for that.

Perl 5 - 75
This is actually adapted and golfed from an old perlmonks post.
sub p{for(@n=(2..2**20);@p<@_[0]&&push@p,shift@n;){@n=grep{$_%$p[-1]}@n}@p}

The output is an array containing the prime numbers, so usage can be:
print join(',',p(100));


text:
How far is the Sun?
Introduction
tl;dr
Continuously output the current distance from the Earth to the Sun.

Simplified, the orbit of the Earth around the Sun is an ellipse. So the actual distance between both is constantly changing. This distance can be calculated for any given day using this formula:

The equation can be split into the following parts2:

1 represents 1 AU (astronomical unit), equals 149,597,870.691 km
0.01672 is the  orbital eccentricity between the Earth and the Sun
cos is of course the cosine function, but with argument in degrees rather than radians
0.9856 is 360° / 365.256363 days, a full rotation in one year, where 365.256363 is the length of a sidereal year, in mean solar days
day is the day of the year [1-365]
4 represents the offset to the perihelion, which is between 4th and 6th of January

The formula takes a whole day but for the purpose of this challenge – a continuously output – you have to be more accurate; or nothing much will happen till the next day. Simply add the percentage of the past time to the current day, like1:
day + (h * 3600 + m * 60 + s) / 864 / 100

A few Examples:

1 January, 23:59:59 1.99998842592593
1 January, 18:00:00 1.75
1 January, 12:00:00 1.50
1 January, 06:00:00 1.25

Input
This challenge has no input.

If your language can't get the current time, you can get it as an input to your program. Valid inputs are timestamps or complete date-time strings that suits the language best. Passing the current day alone (like 5 for 5th January or 5.25 for the same day at 6 o'clock) is not allowed.
Output
Output the current distance from the Earth to the Sun:

Output the value in km.
Update the value at least every second.

Example output:
152098342

If it doesn't increase your byte count, you can also pretty print the result:
152,098,342
152,098,342 km

Requirements

You can write a program or a function. If it is an anonymous function, please include an example of how to invoke it.
This is code-golf so shortest answer in bytes wins.
Standard loopholes are disallowed.

Example implementation
I've prepared an example implementation in JavaScript. It's neither competitive nor golfed.

// dayOfYear from http://stackoverflow.com/a/8620357/1456376
Date.prototype.dayOfYear = function() {
    var j1= new Date(this);
    j1.setMonth(0, 0);
    return Math.round((this-j1)/8.64e7);
}

// vars
var e = document.getElementById('view'),
    au = 149597870.691,
    deg2rad = Math.PI/180,
    date = now = value = null;

// actual logic
function calculate() {
    date = new Date();
    now = date.dayOfYear() + (date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds()) / 864 / 100;
    value = 1 - 0.01672 * Math.cos(deg2rad * 0.9856 * (now - 4));
    // supported in Firefox and Chrome, unfortunately not in Safari
    e.innerHTML = Math.round(value * au).toLocaleString('en-US') + ' km';

    setTimeout(calculate, 1000);
}

// let's do this
calculate();

1 To not unreasonably increase complexity, you don't have to convert your local time to UTC. If you use UTC please add a note to your answer.
2 For more details see "Earth-Sun distance on a given day of the year" over at Physics

What should programming languages do that cannot access the current time? Like BF etc?

I believe your example is incorrect, since Math.cos uses radians. And since this formula seems very approximate, you'll have to be clear on how answers are to be verified.

@grc I've fixed the error in my example - thanks for pointing me to it.

@flawr You can get the time as an input to your program. The question is updated accordingly.

This challenge was discussed on meta. It's back with some improvements now.

I think your estimate of the length of a year is slightly high.

What formats are allowed for the time input, for languages that cannot query the current time?

What do we do on leap years?

@ThomasKwa Not much I'd say, the year has just 366 days then.

Can I use an alternate, more accurate formula?

@busukxuan Yes you can. I'd like to see another approach. Do you want to use Kepler's equation? If you add an answer, it would be great to explain how it works or differ from this approach as well – so that everybody learns something. Your answer will not be competitive though as it will differ from the rules of the challenge. This means you can receive upvotes for your answer but you can't win, even if you have the lowest byte count.

@insertusernamehere I just posted my answer. The formula I used is basically the same as yours, only with different constants in the cos, and seconds rather than days. Is it still non-competing? If it is, I will strikethrough the "(probably)" in the title.

@busukxuan Ah I see how you solved it. You adjusted the values to get a more accurate value I think this is fine. :)

@insertusernamehere Oh ok thank you. I guess now I will strikethrough "(probably) non-" instead :-)

Are six digits of accuracy sufficient?

I bet Mathematica has a built-in for it!

TI-BASIC, 38 bytes
Disp 25018086(59.8086-cos(5022635.4⁻¹checkTmr(83761
prgmA

For a TI-84+ series calculator. Name this prgmA. Note that this overflows the stack after a few thousand iterations; use a While 1:...:End instead if this is a problem, for two extra bytes.
This uses the perihelion on January 1, 1997, 23:16 UTC for reference, and is accurate to within a few dozen kilometers (about 7 digits of accuracy) for the next few years.

Now this is short. Kudos!

Java - 185 180 bytes
static void d(){while(true){System.err.println(149597870.691*(1-.01672*Math.cos(Math.toRadians(.9856*(Calendar.getInstance().get(6)+LocalTime.now().toSecondOfDay()/8.64e4-4)))));}}

This uses the fact that there are 86,400 seconds in a day and is using local time, not GMT. Output happens much more than once per second.
Not sure if import statements should be included in byte count.
To include a 1 second delay adds about 26 bytes e.g.
static void d(){try{while(true){System.err.println(149597870.691*((1-.01672*Math.cos(Math.toRadians(.9856*(Calendar.getInstance().get(6)+LocalTime.now().toSecondOfDay()/8.64e4-4)))));Thread.sleep(1000L);}}catch(Exception e){}}

Java definitely isn't the most golfable language. :)
Removed a few bytes thanks to @insertusernamehere

Nice. Couldn't 1.0 become 1? And can you remove the leading 0 from 0.01672 and 0.9856?

Very true, that's what I get for copy-paste from the question :p
I could drop some more bytes if I used  import static but that might be "cheating"... I'm still rather new here.

Why System.err?

I used System.err so there would be no buffering. I know the println is supposed to print immediately anyway, but it doesn't always seem to do that. Of course it could be converted to System.out without changing the byte count :)

Hmm... the conversion to radians could be combined with the constant .9856 to give 0.0172019651, but how much precision is required?

I've noticed that many people are forgetting to convert from degrees to radians.  I'd comment on them, but I'm a newbie with too little rep :p

Python, 101 bytes
import time,math
a=149597870.691
while 1:print(a-a*.01672*math.cos((time.time()-345600)/5022635.53))

345600 = 4*24*3600 (four days)
5022635.53 ≌ (365.256363*24*3600)/(2π) (seconds in year/2π)

Welcome to Programming Puzzles and Code Golf. This is a good solution, +1. However, it may improve the answer if you added an ungolfed and commented version, explaining what you have done, or even just added a simple comment before the code.

I get 107 for the byte count.

Right, I've included the last newline.

You can save 7 bytes by combining the imports: import time,math. Also, if you use Python 2 you can drop the parenthesis from print.

Also true, with all of that PEP I've forgotten it is possible :)

Bash/coreutils/bc, 101 bytes
#!/bin/bash
bc -l <<<"149597870.691*(1-.01672*c((`date +%s`-`date -d 4-Jan +%s`)/5022635.5296))"
sleep .5
exec $0

This computes the offset from the 4th of January in seconds, so uses a corresponding constant to convert to radians.  Half a year converts to roughly pi:
$ bc -l <<<"(365.256363/2*86400)/5022635.5296"
3.14159265361957033371

The rest of the calculation is straight from the question.

Nice job. I wondered if bc might be useful for this.  I noticed that you have dc in your header, but use bc in the code.  I often confuse the two myself.

Thanks, @Robert - I've fixed the title.  I started off looking at dc, then realised I needed bc's mathlib, so had both calculators in my mind at the wrong moment!

Yep, been there, done that.  I always forget which is which.

F#, 178 bytes
open System
Seq.initInfinite(fun _->
let n=DateTime.Now
(1.-0.01672*Math.Cos(0.0172*((n-DateTime.Today).TotalDays+float(n.DayOfYear-4))))*149597870.691)|>Seq.iter(printfn"%f")

This is an F# script that runs well in F# Interactive. For simplicity's sake, the "continuous output" requirement is taken to literal levels, although I did lose a byte to make the output print on a new line every iteration so that it wasn't too bad. =P
Ungolfed and explained:
Seq.initInfinite (fun _ ->            // Create an infinite sequence, with each element being defined by the following function
    let n = DateTime.Now
    let dayOffset = n.DayOfYear - 4   // Day of year returns the day as a number between 1 and 366
    let today = n - DateTime.Today    // Extract the current day, so the hours, minutes and all
    let partialDay = today.TotalDays  // Get the value of 'today' as a floating point number of days
                                      // so between 0 and 1 in this case - exactly what I needed
    // And now, the formula - note that 0.9856 has been combined with the conversion from degrees to radians, giving 0.0172
    (1. - 0.01672 * Math.Cos (0.0172 * (partialDay + float dayOffset))) * 149597870.691
)
|> Seq.iter (fun i -> printfn "%f" i) // For each of the (infinity of) numbers, print it

Mathematica, 97 bytes
Dynamic[1496*^5-2501*^3Cos[.9856#&@@Now~DateDifference~{DateValue@"Year",1,4}],UpdateInterval->1]

Explanation
{DateValue@"Year",1,5} represents 5th of January this year, and ...~DateDifference~... gives the temporal distance.
Dynamic[...,UpdateInterval->1] update the expression once per second.

Just to remind you, you need to output the answer in km, not AU. I suppose Mathematica has built-in converters so you could save some bytes for the unit conversion, yes?

@busukxuan I have multiplied the coefficient to the formula.

Oh sry I missed it. Didn't expect it to be in 4 significant figures.

Alternatively, Dynamic[Round[PlanetData["Earth", "DistanceFromSun"]~QuantityMagnitude~"Kilometers"]]

Python 2.4 - 158 bytes
import time,math
while 1:t=time.localtime();print(int(149597870.691*(1-.01672*math.cos(math.radians(.9856*(t[7]+(t[3]*3600+t[4]*60+t[5])/864.0/100.0-4))))))

Takes the local time and spits out the distance. time.localtime() returns a tuple and can be referenced here.

Can you remove .0 from 864.0 and 100.0 to save a few bytes?

The only thing I am worried about with doing that is that it will no longer be a floating point division. I kept the .0 so they would be floating point and not integer.

Pyth, 51 bytes
#*149597870.691-1*.01672.t*c-.dZ86400 31558149*2.nZ1

Alternate formula
d/AU = 1 - 0.01672 cos ( 2π [time since perihelion]/[orbital period] )
This formula is essentially the same as the OP's formula, except it is generalized to be able to use any perihelion as a reference date.
The OP's formula has [time since perihelion] as ( day - 4 ) and has ( 2π rad / [orbital period] ) pre-calculated as 0.9856deg/day.
In my solution I am using the perihelion closest to the Unix epoch, 2nd January 1970.
 The code
Hand-compiled to pythonic pseudocode:
#                        while 1:
  *149597870.691             print( 149597870.691 * (                 # implicit print
    -1                           1 - (
      *.01672                        0.1672 * (
        .t                               trigo(
          *                                  multiply(
            c                                    divide(
              -.dZ86400                              unixTime-86400,
              31558149                               31558149
                                                 ),
            *2.nZ                                2*pi
                                             ),
          1                                  1                        # 1 means cos
                             )))))

This is essentially just turning the following formula into code:
d = ( 1 - 0.01672 cos ( 2π (t - 86400)/31558149 ) ) * 149597870.691
where t is the Unix time.

C, 338
#include <stdio.h>
#include <time.h>
#include <math.h>
int main ()
{
  time_t rt;
  struct tm * ti;
  while(1) {
  time(&rt);
  ti = localtime(&rt);
  double d = 1.0 - .01672*cos(0.0174533 * .9856*((ti->tm_yday + (ti->tm_hour * 3600.0 + ti->tm_mday * 60.0 + ti->tm_sec) / 86400.0) - 4));
  printf ("%f\n", d * 149598000.0);}
}

Welcome to Programming Puzzles and Code Golf! While this looks like a correct answer, it doesn't seem to be golfed very much. For questions with the [code-golf] tag, answers need to make an effort at reducing their size as much as possible to be considered on-topic - see the help center. I'll be looking forward to seeing the golfed version! =)

HP‑41C series, 78 Bytes
This program requires an HP‑41CX or an HP‑41C/CV with a time module plugged in.
It works only correctly from October 15, 1582 through September 10, 4320.
Ensure the display format allows for displaying 9 digits (e. g. FIX 4, the default setting).
You may set flag 29 to enable the insertion of a thousands separator for every group of three digits in the integer part.
Set flag 28 to use commas as thousands separators (as opposed to periods).
Flag 28 and 29 set are the default setting.
01♦LBL⸆S           5 Bytes  global label requires 4 + (length of string) Bytes
02 DEG             1 Byte   ensure Degree mode is selected
─── get day number (zero-based) ────────────────────────────────────────────────
03 DATE            2 Byte   today’s date: has MM.DDYYYY or DD.MMYYYY format
04 ENTER↑          1 Byte   replicate value
05 ENTER↑          1 Byte   again because `ENTER↑` disables stack lift
   NULL            1 Byte   invisible Null byte before numbers
06 1 E6            3 Bytes  put 1,000,000 on top of stack
07 *               1 Byte   multiply so X = MMDDYYYY or DDMMYYYY
   NULL            1 Byte
08 1 E4            3 Bytes  put 1,000 on top of stack
09 MOD             1 Byte   isolate YYYY
   NULL            1 Byte
10 1 E6            3 Bytes
11 /               1 Byte   divide YYYY by 1,000,000
   NULL            1 Byte
12 1.01            4 Bytes
13 +               1 Byte   X = January 1, current year
14 X≷Y             1 Byte   swap X and Y so difference is positive
15 DDAYS           2 Bytes  difference of days – accounts for leap year
─── get fractional time of day ─────────────────────────────────────────────────
16 TIME            2 Bytes  obtain time in HH.MMSSss format
17 HR              1 Byte   convert HH.MMSSss into decimal hours format
   NULL            1 Byte
18 24              2 Bytes  24 hours
19 /               1 Byte
─── compose `day` as in specification ──────────────────────────────────────────
20 +               1 Byte   combine day number and time
   NULL            1 Byte
21 3               1 Byte   perihelion bias for zero-based day numbering
22 −               1 Byte
─── perform calculation ────────────────────────────────────────────────────────
   NULL            1 Byte
23 .9856           5 Bytes  use .985609113 for improved precision
24 *               1 Byte
25 COS             1 Byte
   NULL            1 Byte
26 −.01672         7 Bytes
27 *               1 Byte
   NULL            1 Byte
28 149,597,870.7  11 Bytes
29 +               1 Byte
30 PSE             1 Byte   delay execution for about one second
31 GTO⸆S           3 Bytes  `PSE` displays contents of X-register

NB:
The actual calculator (in hardware) is too slow to perform all operations within one second.
It needs roughly 3 seconds + 1 second for PSE.
However, this is a circumstance outside the realm of the programming language.

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


text:
Clock (card game)
Clock is an interesting card game, as it requires no skill.  It is a single player game, and the same card configuration always leads to a win or a loss.  In this challenge, you need to figure out whether a given card configuration wins or loses.  You can play the game here.
The game is played as follows:

Thirteen piles of cards are dealt face down.  Each pile is numbered from 0 to 12.
We set the 0th pile to be the current pile
We flip the top card of the current pile face up.
We move the face up card at the bottom of its respective pile (A 4 card goes under the 4th pile).  The card remains face up.  This pile becomes the current pile.
If the current pile is completely face up, then the game is over. Otherwise, go back to step 3.

Tip: The game will always end on the 0th pile
The game is won if all cards end up face up, and is lost if there are remaining face down cards.
Input/Output
A 2D array containing each of the piles.  Cards are represented with numbers from 0 to 12 (suit is irrelevant, and not given).  The top card of each pile is the first element of each array.
You can assume that the input will be well formed:  it will contain 52 cards from 0 to 12 (inclusive), and contain each number exactly 4 times.
You must return a truthy value if the game can be won, and falsy if it cannot.
Test cases
Truthy:
[[11, 11, 7, 7], [8, 6, 5, 0], [2, 10, 9, 1], [12, 3, 0, 6], [8, 7, 4, 8], [3, 10, 5, 12], [11, 7, 1, 10], [3, 1, 6, 0], [2, 3, 0, 6], [5, 10, 5, 4], [12, 9, 11, 2], [9, 4, 12, 4], [1, 9, 8, 2]]
[[0, 9, 4, 8], [1, 4, 11, 3], [10, 12, 4, 0], [5, 9, 11, 5], [7, 0, 11, 2], [6, 5, 6, 0], [5, 7, 6, 7], [1, 10, 3, 4], [10, 11, 12, 3], [9, 9, 3, 6], [12, 12, 2, 1], [1, 8, 8, 2], [7, 2, 10, 8]]
[[11, 11, 9, 5], [3, 0, 1, 7], [6, 2, 9, 4], [6, 9, 11, 2], [10, 9, 6, 1], [12, 8, 10, 0], [2, 3, 12, 3], [3, 12, 5, 11], [4, 1, 8, 12], [7, 0, 2, 5], [4, 1, 10, 4], [7, 10, 6, 5], [8, 8, 0, 7]]
[[2, 3, 4, 11], [6, 12, 5, 9], [11, 0, 5, 9], [1, 8, 0, 12], [11, 9, 5, 8], [12, 7, 1, 0], [10, 3, 1, 11], [3, 12, 7, 2], [2, 7, 1, 5], [6, 3, 4, 10], [10, 10, 9, 8], [6, 2, 4, 4], [6, 8, 0, 7]]
[[1, 2, 12, 9], [5, 6, 4, 11], [0, 0, 7, 10], [9, 7, 12, 0], [12, 1, 8, 6], [10, 1, 4, 8], [9, 2, 6, 11], [10, 12, 1, 8], [6, 7, 0, 3], [2, 2, 5, 5], [8, 11, 9, 3], [4, 7, 3, 10], [5, 11, 4, 3]]
[[8, 12, 5, 3], [3, 10, 0, 6], [4, 11, 2, 12], [6, 1, 1, 12], [7, 6, 5, 0], [0, 8, 8, 7], [4, 8, 1, 2], [2, 3, 11, 6], [11, 10, 5, 2], [10, 1, 9, 4], [12, 5, 9, 7], [7, 3, 10, 9], [9, 0, 11, 4]]
[[3, 4, 8, 7], [2, 2, 8, 9], [12, 7, 0, 4], [4, 7, 10, 11], [5, 10, 3, 11], [10, 9, 8, 7], [5, 2, 11, 8], [6, 0, 3, 10], [9, 1, 4, 12], [12, 3, 12, 6], [2, 5, 1, 1], [6, 11, 5, 1], [6, 9, 0, 0]]
[[11, 9, 11, 1], [1, 3, 2, 8], [3, 3, 6, 5], [8, 11, 7, 4], [9, 4, 5, 1], [6, 4, 12, 6], [12, 10, 8, 7], [3, 9, 10, 0], [2, 8, 11, 9], [2, 4, 1, 0], [12, 5, 6, 0], [10, 7, 10, 2], [5, 0, 12, 7]]
[[9, 9, 6, 5], [7, 5, 11, 9], [8, 12, 3, 7], [1, 2, 4, 10], [11, 3, 3, 10], [2, 0, 12, 11], [4, 7, 12, 9], [3, 6, 11, 1], [1, 10, 12, 0], [5, 6, 8, 0], [4, 10, 2, 5], [8, 8, 1, 6], [0, 7, 2, 4]]
[[4, 0, 7, 11], [1, 5, 2, 10], [2, 9, 10, 0], [4, 12, 1, 9], [10, 12, 7, 0], [9, 4, 1, 8], [6, 6, 9, 12], [5, 3, 6, 2], [11, 3, 6, 4], [7, 3, 5, 5], [11, 8, 1, 11], [10, 7, 2, 8], [8, 12, 0, 3]]

Falsy:
[[8, 1, 6, 1], [7, 9, 0, 12], [11, 12, 12, 12], [11, 5, 9, 3], [2, 10, 9, 7], [11, 2, 0, 8], [0, 10, 4, 6], [8, 0, 4, 2], [6, 5, 3, 8], [4, 10, 3, 1], [5, 11, 9, 6], [7, 5, 1, 4], [2, 7, 3, 10]]
[[1, 4, 4, 6], [3, 11, 1, 2], [8, 5, 10, 12], [7, 10, 7, 5], [12, 8, 3, 7], [4, 0, 12, 12], [1, 1, 9, 6], [8, 7, 5, 10], [11, 0, 11, 0], [5, 10, 3, 11], [3, 2, 9, 8], [9, 6, 0, 2], [2, 6, 9, 4]]
[[10, 1, 10, 7], [12, 3, 11, 4], [0, 5, 10, 7], [5, 11, 1, 3], [6, 6, 9, 4], [9, 0, 8, 6], [9, 12, 7, 10], [1, 6, 3, 9], [0, 5, 0, 2], [4, 8, 1, 11], [7, 12, 11, 3], [8, 2, 2, 2], [8, 4, 12, 5]]
[[3, 8, 0, 6], [11, 5, 3, 9], [11, 6, 1, 0], [3, 7, 3, 10], [6, 10, 1, 8], [11, 12, 1, 12], [8, 11, 7, 7], [1, 8, 2, 0], [9, 4, 0, 10], [10, 2, 12, 12], [7, 4, 4, 2], [9, 4, 5, 5], [6, 2, 9, 5]]
[[0, 1, 9, 5], [0, 1, 11, 9], [12, 12, 7, 6], [3, 12, 9, 4], [2, 10, 3, 1], [6, 2, 3, 2], [8, 11, 8, 0], [7, 4, 8, 11], [11, 8, 10, 6], [7, 5, 3, 6], [0, 10, 9, 10], [1, 4, 7, 12], [5, 5, 2, 4]]
[[9, 8, 0, 6], [1, 1, 7, 8], [3, 2, 3, 7], [9, 10, 12, 6], [6, 12, 12, 10], [11, 4, 0, 5], [10, 11, 10, 7], [5, 3, 8, 8], [1, 2, 11, 4], [0, 5, 6, 0], [5, 9, 2, 4], [4, 2, 3, 11], [9, 1, 12, 7]]
[[4, 3, 5, 7], [1, 9, 1, 3], [7, 9, 12, 5], [9, 0, 5, 2], [7, 2, 11, 9], [1, 6, 6, 4], [11, 0, 6, 4], [3, 0, 8, 10], [2, 10, 5, 3], [10, 11, 8, 12], [8, 1, 12, 0], [7, 12, 11, 2], [10, 6, 8, 4]]
[[9, 5, 11, 11], [7, 7, 8, 5], [1, 2, 1, 4], [11, 11, 12, 9], [0, 12, 0, 3], [10, 6, 5, 4], [4, 5, 6, 8], [10, 9, 7, 3], [12, 6, 1, 3], [0, 4, 10, 8], [2, 0, 1, 12], [3, 9, 2, 6], [2, 7, 8, 10]]
[[4, 1, 5, 7], [7, 12, 6, 2], [0, 11, 10, 5], [10, 0, 0, 6], [10, 1, 6, 8], [12, 7, 2, 5], [3, 3, 8, 12], [3, 6, 9, 1], [10, 9, 8, 4], [3, 9, 2, 4], [11, 1, 4, 7], [11, 5, 2, 12], [0, 8, 11, 9]]
[[3, 11, 0, 1], [6, 1, 7, 12], [9, 8, 0, 2], [9, 6, 11, 8], [10, 5, 2, 5], [12, 10, 9, 5], [4, 9, 3, 6], [7, 2, 10, 7], [12, 6, 2, 8], [10, 8, 4, 7], [11, 3, 4, 5], [12, 11, 1, 0], [1, 3, 0, 4]]

ES6, 57 bytes
a=>(g=n=>a.map((x,i)=>i&&x[3]==n&&++c&&g(i)),g(c=0),c>11)

This works because only the cards on the bottom of piles 1-12 are relevant, and they need to form a directed graph back to pile 0. So, I count the number of piles whose bottom card is 0, then the number of piles whose bottom card was one of the piles I counted earlier, etc. If I reach 12 piles then the configuration is a winning one.
Outline proof:
The game always ends when you turn over the last 0, since that pile effectively has one fewer card than the others.
If the bottom cards on piles 1-12 form a directed graph to pile 0, then in order to clear pile 0, we have to clear all the piles whose last entry is 0, and so on recursively to all the piles we have to clear so that we can clear the piles whose last entry is 0, and so forth. The configuration is therefore a winning one.
If the cards on the bottom of piles 1-12 do not form a directed graph to pile 0, there must exist at least one cycle. No pile in this cycle can be cleared, since it depends on the previous pile in the cycle. (In the case of a cycle of length 2, this is a chicken-and-egg situation.) The configuration is therefore a losing one.

CJam, 23 21 bytes
q~({(\a@+1$ff-m<(}h*!

Run all test cases.
If the assignment of truthy and falsy was the opposite I could save 3 bytes:
q~{((\a@+1$ff-m<}h

Explanation

 Putting the cards face up under another pile is a red herring. We might as well remove them from the game and keep playing until the current pile is empty. So that's what I'm doing: the code simply plays the game until the current pile is empty and then checks if any cards are left.

q~    e# Read and evaluate input.
(     e# Pull off the first (current) pile.
{     e# While the current pile is non-empty...
  (\  e#   Pull off the top card and swap with the remaining pile.
  a   e#   Wrap the pile in an array.
  @+  e#   Prepend it to the list of piles
  1$  e#   Copy the drawn card.
  ff- e#   Subtract it from all all remaining cards.
  m<  e#   Rotate the stack to the left by the drawn card
  (   e#   Pull off the top pile as the new current pile.
}h
*     e# The top pile is empty. Joining the other piles with it, flattens them.
!     e# Logical not, turns an empty array into 1 and a non-empty array into 0.

Haskell, 85 bytes
(a:b)?n|n<1=tail a:b|1>0=a:b?(n-1)
l%i|null(l!!i)=all null l|1>0=l?i%(l!!i!!0)
f=(%0)

Pyth, 13 bytes
!su@LGGXeMQZZ

Relies on @Neil's proof. !su&VG@LGGeMQ also works.
                 implicit: Q=input
! s u            Sum of (apply lambda G,H on ... until fixed point) equals 0
      @L         Index G into itself.
         G
         G
                  Apply that to:
      X                                            set to
        eM Q      Last elts of input, with the
        Z                                      0th
        Z                                                 0

Try it here.

Request Line is too large (7173 > 4094)

Fixed the link.

Python, 55 bytes
x=lambda l,i=0:x(l,l[i].pop(0))if l[i]else[]==sum(l,[])

If the sublist is not empty, continue poping items. When it's empty, Return either all the lists are empty (by grouping them into one big list) or not.

I get False for the first true test case using Python 3.4.2.

I'm taking the last item of each list, so you need to flip the lists: l = [i[::-1] for i in l]

The question explicitly says the first item of every list is the top. You'll need to include the code to flip in your byte count.

Fixed. Now it's poping the first item.

Jelly, 11 bytes
‘ịa
Ṫ€ÇL¡S¬

Try it here.