text:
Counting in bijective base 62
The task is to generate all the strings from 'a' to '999' including upper case characters like so:
'a', 'b', 'c' ... 'y', 'z', 'A', 'B', 'C' ... 'Y', 'Z', '0', '1', 2' ...
'8', '9', 'aa', 'ab', 'ac' ... 'az', 'aA', 'aB' ... 'aZ', 'a0' ... 'a9', 'ba'

and so on (filling in the gaps), optionally starting with the empty string.
Input:

The amount of consecutive characters the program has to print up to.

Output:

An array containing each string OR one string per line

Clarifications:

The order doesn't matter, you can print uppercase or lowercase letters first if you want.
The output can return any type of enumerable, doesn't have to be an array specifically, although I doubt printing all the combinations won't be the easiest way to go.
An input of 3 would print all the string from 'a' (or '') to '999'‚ an input of 5 up to '99999' and so on.

What do you mean by outputting an array?

So letters and numbers only? What order do you use? In ASCII numbers come first, then uppercase letters, the lowercase

An enumerable containing all the values i.e. ['a', 'b', 'c' ..]. You should either see the output on each line via STDOUT or be able to assign it via a = (function return).

@LuisMendo The order doesn't matter, as long as all the number/letter combinaisons are there.

@edc65 As I understand it, the input is the maximum number of characters to combine. So for input 4, you go from a to 9999, for 5 it's a to 99999, and so on.

@edc65 An input of 3 would print all the string from 'a' to '999'‚ an input of 5 up to '99999' and so on.

Is a leading newline for the output okay :p?

So, you're basically listing base 62 numbers up to N digits, where N is the input?

@Wildcard Exactly.

@Adnan Sure as long as the rest of the input is fine, I'll allow a newline. :)

Since a leading newline is allowed, would be returning an array that starts with an empty string be acceptable as well?

@Dennis I guess that's only fair :)

OK, thanks for clearing that up. That saved a lot of bytes. :) I think the current title is a bit confusing since you seem to require bijective base 62.

It's not really base 62 (you would not have 00, 000 and so on). It's more like Excel column naming. We had a challenge about that: http://codegolf.stackexchange.com/q/37515/21348

@Dennis, the question still looks to me like it requires bijective base 62 (and if I didn't have a supervote, I'd vote to close as a dupe of http://codegolf.stackexchange.com/q/54105/194 )

@PeterTaylor it's close but simpler. Not all challenges about bijective base are dupes

What is the largest expected input?

@DigitalTrauma Most people have been using 2 and 3 as their test case, if it works with both your answer will be considered good.

Jelly, 7 bytes
ØWṖṗR;/

This is a monadic link that accepts an integer as input and returns an array of strings.
Try it online!
How it works
ØWṖṗR;/  Main link. Argument: n

ØW       Yield 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_'.
  Ṗ      Remove the last element (underscore).
    R    Range; yield [1, ..., n].
   ṗ     Cartesian product. For each k in the range, this yields the arrays of all
         strings of alphanumeric characters.
     ;/  Concatenate the arrays of strings of each length.

When writing your own language for codegolf, couldn't you just fork it, modify it and use a 1 byte solution?

No. We have strict rules for admissible programming languages, and one is that a working interpreter has to have existed before the challenge was posted. I could add a built-in for this task now, but I could use it only in future challenges.

Ah, that makes sense. A little bit ridiculous that this rule exists though. ;)

How is that ridiculous? If it was allowed, each challenge would be solved with 1 byte

Do those characters fit in a byte each?

@UncleZeiv the Jelly code page is linked in the post title

@edc65 sure, I was just wondering what kind of character set are we talking about here? One that contains Ø, W, Ṗ, ṗ along the standard alphanumeric characters in a single table of 256 symbols?

@UncleZeiv There's really only one character set that does it, which is the Jelly code page.

ah apologies to @edc65 then, when you said "code page" I actually interpreted it as "webpage for the source code" rather than "character set", and also I missed the second link and only followed the first one!

Jelly is angry ;/ or jealous.

Haskell, 65 bytes
a#b=[a..b]
k n=mapM id.('a'#'z'++'A'#'Z'++'0'#'9'<$)=<<(1#)<$>1#n

Usage example: k 3 -> ["a","b","c",....,"997","998","999"].
How it works
a#b = [a..b]        -- helper function that builds a list from a to b

        (1#n)<$>    -- map the function (1#), i.e. "build the list from 1 up to"
                1#n -- on the list from 1 to n

                    -- now we have [[1],[1,2],[1,2,3]]

              =<<   -- map over this list (and combine results in a single list)
  (        <$)      -- a function that makes length of input copies of
 'a'#'z'++ ... '9'  -- all characters we need

                    -- now we have [["a..9"],["a..9","a..9"],["a..9","a..9","a..9"]]

mapM id.            -- and make the cartesian product of each sublist

Python, 86 bytes
f=lambda n:n*[1]and[x+chr(y)for x in['']+f(n-1)for y in range(128)if chr(y).isalnum()]

Outputs a list of non-empty strings. Recursively prepends each alphanumeric character to each output for n-1 and empty string.

05AB1E, 9 8 bytes
Code:
ƒžj¨Nã€,

Explanation:
ƒ          # For N in range(0, input + 1), do:
 žj        #   Push predefined literal [a-zA-Z0-9_]
   ¨       #   Remove the last character (the underscore)
    N      #   Push N
     ã     #   Take the Cartesian product, with N repetitions.
      €,   #   For each element in the array, print with a newline

Uses CP-1252 encoding. Try it online!.

JavaScript (Firefox 30-57), 108 bytes
f=n=>n?[for(s of['',...f(n-1)])for(c of(t='abcdefghijklmnopqrstuvwxyz')+t.toUpperCase()+'0123456789')s+c]:[]

Saved 3 bytes by using toUpperCase. Computing the 62 characters takes me an extra 10 bytes.

I can't get your code to work, says function f is undefined.

@SimonLandry Whoops, I forgot the f= at the start. (I always forget to do that for recursive answers.)

Doesn't work for reasons above.

@CatsAreFluffy I put the f= in, any further problems are due to the way you're trying to call it.

Cinnamon Gum, 15 bytes
0000000: 689b b718 05be a345 9c4b c283 d077 de    h......E.K...w.

Not short enough, despite this being the exact kind of challenge Cinnamon Gum was made for :(
Compressed by converting from bijective base 96 to base 256. Try it online. Inputs greater than 2 will cause problems on TIO.
Explanation
This decompresses to the regex [a-zA-Z0-9]{1,%s}. The h mode then substitutes the input in to %s and outputs all strings matching the regex.

Python 2.7, 136 134 bytes
Thanks to Maltysen and NonlinearFruit for saving 2 bytes
from itertools import*;from string import*;f=lambda n:[''.join(a) for i in range(1,n+1) for a in product(ascii_letters+digits,repeat=i)]

Takes ascii_letters and digits from the string module and uses the Cartesian Product as product from itertools to compute all the combinations.
Output
out = f(3)

print out[:10]
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

print out[100:110]
['aM', 'aN', 'aO', 'aP', 'aQ', 'aR', 'aS', 'aT', 'aU', 'aV']

print out[-10:]
['990', '991', '992', '993', '994', '995', '996', '997', '998', '999']

you can remove the spaces between parenthesis and letters.

Try i in range(n) with repeat=i+1

+1 for the negative input. Is that built in into the range function?

Ruby, 82 bytes
Constructs cartesian products of the character set up to the given length. The character set is generated by grabbing all characters between 0 and z and filtering out non-word characters and also _.
->n{a=(?0..?z).grep(/\w/)-[?_];r=[]
n.times{|i|r+=a.product(*[a]*i).map &:join};r}

Pyth - 13 12 bytes
1 bytes saved thanks to @Jakube.
sm^s+rBG1UTh

Try it online here.
s                    Add up the lists of different lengths
 m          (Q)      Map implicitly over input
  ^     h(d)         Cartesian product of string to implicit lambda var + 1
   s                 Add up list
    ++               Concat up three things
     G               Alphabet
     rG1             Uppercase alphabet
     UT              All digits

Nice one! Care to provide an explanation?

I thought there's a command to iterate through the strings in lexicographical order?

@KennyLau nvm, doesn't do numbers.

rBG1 save one byte over +GrG1

@Jakube oh, Bifurcate works with arguments? thanks.

Python 2, 106 97 bytes
from string import*
f=lambda n,r=['']:n and r+f(n-1,[x+y for x in r for y in letters+digits])or r

Try it on Ideone.

Had almost the same idea, but a few bytes longer...

Wow 2 answers from you @Dennis, you're killing it! :)

MATL, 12 bytes
:"3Y24Y2h@Z^

This takes a number as input.
Try it online!
Explanation
:       % Implicitly take input, say N. Generate range [1 2... N]
"       % For each number in that range
  3Y2   %   Predefined literal: string with all letters, uppercase and lowercase
  4Y2   %   Predefined literal: string with all digits
  h     %   Concatenate horizontally
  @     %   Push number of characters corresponding to current iteration
  Z^    %   Cartesian power. Each result is a row
        % End for each. Implicitly display

, 21 chars / 27 bytes
ⒶïⓜᵖɱĬ⟦ᶛ+ᶐ+⩤9⨝],⧺_)ė)

Try it here (Firefox only).
Nope. Nope. Nope.
Explanation
ⒶïⓜᵖɱĬ⟦ᶛ+ᶐ+⩤9⨝],⧺_)ė) // implicit:
Ⓐïⓜ                    // [...Array(input)].map(($,_)=>...)
    ᵖ                   // push to stack:
     ɱĬ⟦ᶛ+ᶐ+⩤9⨝],⧺_)   // list of n-digit numbers in [a-zA-Z0-9]-ary
                     ė) // formatted into a matrix (no spaces)
                        // implicit stack output, newline-separated

First time I see this language and can't find to find it using Google, care to add a link to its documentation and (or) source code? :)

github.com/molarmanful/ESMin

Is the name of the language seriously 4 spaces?

No, but your browser might not render the doublestruck characters correctly. In ASCII, it's called ESMin.

Perl, 113 bytes + whitespace
@r="";
for (1..shift) {
  @r = sub {
    map { $c=$_; map $c.$_, @{$_[1]} } @{$_[0]}
  }->(\@r, [0..9, "a".."z", "A".."Z"])
}
map say($_), @r

Use "perl -E" on the above, with an argument that's a number. I could probably decently have not counted the last "map say" in the chars count.

APL, 38 37 bytes
{⊃{⍵,,⍺∘.,⍵}/⍵⍴⊂,¨⎕a,⎕d,⍨⎕ucs 96+⍳26}

I have to ask, how does one get around if they can't COMMUTE? (⎕ucs 96+⍳26),⎕d => ⎕d,⍨⎕ucs 96+⍳26

I can assure you I can commute (not talking about "making the same journey regularly between work and home", because that's boring). You seem to have found that it can be easy improve on other people's solutions. Especially if you don't have a full time job. Then there's real life that makes everything even harder...

J, 50 bytes
62&(('0123456789',~(,toupper)u:97+i.26){~#~#:i.@^)

Half of the bytes, 25 to be exact, are spent generating the letters and digits needed.

Bash + GNU utilities, 90
printf -vs %$1s
eval printf '%s\\n' ${s// /{=,{a..z\},{A..Z\},{0..9\}\}}|sed s/^=*//\;/=/d

Input as a command-line parameter.  Output is a whitespace-separated list.
Works for inputs upt and including 3.  Run out of memory with 4 - the eval printf takes an the entire set of 63n elements of the bash expansion.

Bash + GNU utils, 66
Different (and I think slightly novel) approach to my other answer:
dc -e"64 $1^[d2 48^r-P1-d0<m]dsmx"|base64 -w8|sed s_^/*__\;/[+/]/d

dc counts down from 248-1 to 248-64n and Prints each resulting number as a bytestream (i.e. base 256).  If the input is between 1 and 4 inclusive, this is guaranteed to be exactly 6 bytes per number.
base64 converts this to base64 output and thus 8 bytes per base64 digit, one per line.
sed strips off leading / (base64 digit 63), and then removes any lines containing + or / (base64 digits 62 and 63).  This leaves the required sequence.

R, 73 bytes
y='';x=c(letters,LETTERS,0:9);for(i in 1:scan())cat(y<-outer(y,x,paste0))

y starts off as empty string, x as the base case 'a','b','c',...,'8','9'. outer takes each of its input arguments, and applies the function paste0 to each combination of elements in y and x which concatenates the strings. y saves the result, cat prints it, and it iterates through STDIN number of times of doing this.
Try it online!

Jq 1.5, 97 bytes
range(.)as$n|[[range(97;123),range(65;91),range(48;58)]|implode/""|combinations($n+1)]|map(add)[]

Expanded
  range(.) as $n           # for each n-digit sequence
| [
      [                    # build array of ordinals for
        range(97;123),     #   a-z
        range(65;91),      #   A-Z
        range(48;58)       #   0-9
      ]
    | implode/""           # make into array of strings
    | combinations($n+1)   # generate array of n-element combinations
  ]
| map(add)[]               # convert to sequence of strings

Try it online!


text:
Filter this string!
Your task is to write a program that will filter out some characters in a string, so that the remaining spells out (part of) the other string.
Let's say we received the string "123456781234567812345678", and the second string is "314159".
First, we put a pointer on the second string:
314159
^

So the pointer is now on 3, and we replace the not-3 characters with a hashtag until the first 3:
##3456781234567812345678

We then move the pointer to the next character until we have iterated through the string.
Specs

You may use any character to replace "#", and the first string will not contain the hashtag (or the replaced hashtag).
The second string will always be longer than enough.
Both strings will only contain ASCII printable characters (U+0020-U+007F).

Testcases
input1: 123456781234567812345678
input2: 314159
output: ##3#####1##4####1###5###

input1: abcdefghijklmnopqrstuvwxyz
input2: dilemma
output: ###d####i##l##############

@KennyLau could always have waited a minute to explain your question before posting it lmao

@KennyLau You're posting a lot of challenges, which is great, but I feel like you could do better taking more time to improve and clarify each one before posting it.

Could you edit to specify which approximations to pi are acceptable? Otherwise I can save a lot of bytes by using the traditional approximation 3.

Really, this whole use of pi seems gratuitous. The string to keep could be any string, or an input. Pi just means languages with it built in have it shorter.

@xnor Thanks for your comment.

Does "The second string will always be longer than enough." mean that it will always contain the first string as a subsequence?

possible duplicate

Related.

You should probably add a testcase where input1 contains all characters of input 2 and more..

C#6, 112 bytes
string c(string h,string n)=>h==""?"":h[0]==n[0]?h[0]+c(h.Substring(1),n.Substring(1)):"#"+c(h.Substring(1),n);

Recursive function, takes haystack h (input1) and needles n (input2).

If Haystack is empty, return it.
if first characters of haystack and needle are equal, keep the first character and call recursively while skipping the first char on both parameters
else return the replacement character (fixed to # here) followed by a recursive call again skipping the first character from haystack only.

Major factor for the length is the long name of Substring, but it's not long enough (compared to the number of usages) that a wrapping function would help to reduce further.

Javascript ES6, 46 bytes
a=>b=>a.replace(/./g,x=>x==b[i]?(i++,x):0,i=0)

Uses 0 as the replacement char.

I think you should be able to save 3 bytes by using replace instead.

Python 3, 69
def f(a,b,c=''):
 for x in a:y=x==b[0];c+=x*y or'#';b=b[y:]
 return c

Uses the hash for the replacement char, and take the original and replacement as a and b respectively.
Test case:
assert f('123456781234567812345678', '314159') == '##3#####1##4####1###5###'

Python, 115 Bytes
n,f=input()
for a in str(f):
 x,r=0,""
 for b in str(n):
  if x==0and b==a:c,x="#",1
  else:c=b
  r+=c
 n=r
print n

Ruby, 44 bytes
If someone helps me golf it down by any amount, then I can say crossed-out 44 is still 44
->s,r{s.gsub(/./){$&==r[0]?(r[0]='';$&):?#}}

Perl, 77 bytes
sub _{$p=substr$f,0,1,''}($_,$f)=@ARGV;_;print map{$_ eq$p?_&&$_||$_:'#'}/./g

, 18 chars / 23 bytes
îⓢ⒨≔í⟨Ḁ?(Ḁ⧺,$):0)⨝

Try it here (Firefox only).
Ayyy not bad. Uses 0 as the replacement char. It's just the same algorithm that I used in my JS answer.

Seems to work on Chrome for me.

Yeah, this answer was made back when Firefox was still the only browser with enough ES6 support for .

I realize that there's already another JS-based solution posted using the .replace method that's shorter, but I'd like to submit my answers anyways...
CoffeeScript, 55 bytes
Builds a string and returns it:
f=(a,b,i=0,s='')->s+=c==b[i]&&b[i++]||'#'for j,c of a;s

JavaScript, 53 bytes
Operates on an array of characters from the original string:
f=(a,b,i=0)=>[...a].map(c=>c==b[i]?b[i++]:`#`).join``

You can drop the f= in both.

C, 81 bytes
A[99];char*b=A,*a=A+50;main(){gets(a),gets(b);while(*a)putchar(*a++^*b?35:*b++);}

Haskell, 56 bytes
""%_="";(a:b)%l|a==head(l++"é")=a:b%(tail l)|0<1='#':b%l

You can pattern match the head and tail together with @ for the whole list. I don't think you need ++"é", because of the 2nd spec: "The second string will always be longer than enough". (a:b)%l@(c:d)|a==c=a:b%d|0<1='#':b%l.

Mathcad, [tbd] bytes

Mathcad byte equivalence to be determined.   Note that the programming operators "while", "break" and "on error" only require 1 key-combination to enter (ctl-], ctl-{ and ctl-', respectively) - they cannot be typed verbatim.  What you see in the image is exactly what gets entered onto the Mathcad worksheet and the results are live - change a or b, or the function arguments, and the results update accordingly.

Java, 136 bytes
void i(int[]a,int[]b){int i=0,j=0,n=a.length;for(;i<b.length;i++)for(;j<n;j++)if(a[j]==b[i]){j++;break;}else a[j]=0;for(;j<n;)a[j++]=0;}

Ungolfed
void i(int[] a, int[] b) {
    int i = 0, j = 0, n = a.length;
    for (; i < b.length; i++)
        for (; j < n; j++)
            if (a[j] == b[i]) {
                j++;
                break;
            } else a[j] = 0;
    for (; j < n; ) a[j++] = 0;
}

Notes

Uses the NUL character as replacement, any of the first 10 would do. If you wanted a visible replacement character, this would be one byte longer.
Input are two integer arrays of charcodes. int[] is one byte shorter than char[].

Outputs
Input 1:    123456781234567812345678
Input 2:    314159
Output:       3     1  4    1   5
Input 1:    abcdefghijklmnopqrstuvwxyz
Input 2:    dilemma
Output:        d    i  l
Input 1:    314asd159asdasd
Input 2:    314159
Output:     314   159

PowerShell v2+, 72 bytes
param($a,$b)$i=0;-join([char[]]$a|%{if($_-ceq$b[$i]){$_;$i++}else{'#'}})

Takes input $a and $b, sets $i to 0 (our pointer). Then, we cast $a as a char-array and pump it through a loop |%{...}. Each iteration, we check if the current character is case-sensitive-equal to the character in $b under the pointer. If it is, add it to the pipeline with $_ and increment our counter. Otherwise, add a '#' to the pipeline. All of those characters are then gathered up (...) and -joined into one string, which is then re-placed onto the pipeline. Output is implicit.
Example
PS C:\Tools\Scripts\golfing> .\filter-this-string.ps1 "Programming Puzzles & Code Golf" "PPCG"
P###########P#########C####G###

05AB1E, 5 bytes
Code:
.o²g£

Explanation:
.o     # Overlap function.
         12345 and 1456 yields:
         1  456
  ²    # Get the second input.
   g   # Take the length.
    £  # Take the substring [0:length] and implicitly output.

Uses CP-1252 encoding. Try it online!

Python 3, 197 bytes
I was determined to solve this with regex, and I did. I did not really think it would be short.
def f(n,h):r=re.match(("([^{}]*)(.)"*len(n)).format(*n),h).groups();return"".join([i if i in n else"#"for i in"".join(["".join(d)for d in zip(["#"*len(i)for i in r[::2]],r[::-1][::2][::-1])])])

Ungolfed:
def fs(needle, haystack):
    rx = "([^{}]*)(.)"
    rx *= len(needle)
    rx = rx.format(*needle)
    r  = re.match(rx, haystack).groups()
    nd = r[::-1][::2][::-1]
    hs = r[::2]
    hs = ["#" * len(i) for i in hs]
    nh = "".join([i if i in needle else "#" for i in "".join(["".join(d) for d in zip(hs, nd)])])
    return nh

I wanted to do it with regex so I can do it again in Factor which, as a point-free functional language, does not do explicit looping. Haskell also does not do explicit looping and the Haskell solution does not use pattern matching but I don't understand the Haskell solution.
Here's what I used to come up with the regex.

Python 3.5, 67
def f(a,b):b=[*b];return"".join(y==b[0]and b.pop(0)or"#"for y in a)

Ungolfed:
def f(a, b):
    b = [*b] #Convert string to list; yeah Python 3.5
    c = []
    for y in a:
       if y==b[0]:
          c.append(b.pop(0))
       else:
          c.append("#")
    return "".join(c)

Try it here

PHP(271)
This is my first php code so it is stronly likely that it can be golfed more
    function g($s,$b){$r='';foreach(str_split(strrev($b))as $i) $r='([^'.$i.']*?)(?:([^'.$i.']$)|'.$i.$r.')';$line=preg_replace_callback('/'.$r.'/',function ($m) {$a='';for($i=1;$i<count($m);$i=$i+2)$a=$a.$m[$i].$m[$i+1].'#';return $a;},$s);echo substr($line,0,strlen($s));}

I used non-recursive regex where I am certain that a recursive breakthrough is available.
Test it
<?php
g("uuuuaaaaavabbbbccccd","abcd");
function g($s,$b){$r='';foreach(str_split(strrev($b))as $i) $r='([^'.$i.']*?)(?:([^'.$i.']$)|'.$i.$r.')';$line=preg_replace_callback('/'.$r.'/',function ($m) {$a='';for($i=1;$i<count($m);$i=$i+2)$a=$a.$m[$i].$m[$i+1].'#';return $a;},$s);echo substr($line,0,strlen($s));}

In/Outputs
 uuuuaaaaavabbbbccccd
 abcd

 uuuu#aaaava#bbb#ccc#

REXX, 97 bytes
arg a b
o=
do while b>''
  parse var b n+1 b
  parse var a p (n)h+1 a
  o=o||translate(p,,p)h
  end
say o

As usual, readability is severely hampered by skipping every possible whitespace and abuttal operator.

PHP, 65 bytes
function f($s,$t){for(;a&$c=$s[$i++];)echo$c==$t[$k]?$t[$k++]:_;}

source: Stack Exchange

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

sort: votes


text:
ASCII piano keyboard
Piano keys are     3 characters wide, and 7 characters tall. However, if every key was 3 charactes wide, there wouldn't be enough room for the black keys. That's why some of the white keys have parts of them cut out. There are 3 types of white keys.
Keys with the right half missing (R):
____
|  |
|  |
|  |
|  |
|   |
|   |
|___|

Keys with the left half missing (L):
 ____
 |  |
 |  |
 |  |
 |  |
|   |
|   |
|___|

And keys with the left and right halves missing (M):
 ___
 | |
 | |
 | |
 | |
|   |
|   |
|___|

On a real keyboard, the pattern of these goes like this:
RMLRMML, RMLRMML, RMLRMML...

and repeats for a total of 88 keys. Now you can't see it when the keys are shown individually, but when you shove them together, you can see the black keys.
_________________________________________________________
|  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |
|  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |
|  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |
|  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |
|   |   |   |   |   |   |   |   |   |   |   |   |   |   |
|   |   |   |   |   |   |   |   |   |   |   |   |   |   |
|___|___|___|___|___|___|___|___|___|___|___|___|___|___|

Your task
Given a positive integer N, print this ASCII-art of a piano with N white keys. You should be able to handle any N from 1 to 52 inclusive (since real 88-key pianos have 52 white keys). Here is test output from 1 to 8, and after that the pattern increases in a similar fashion.
1
____
|  |
|  |
|  |
|  |
|   |
|   |
|___|

2
________
|  | | |
|  | | |
|  | | |
|  | | |
|   |   |
|   |   |
|___|___|

3
_____________
|  | | | |  |
|  | | | |  |
|  | | | |  |
|  | | | |  |
|   |   |   |
|   |   |   |
|___|___|___|

4
________________
|  | | | |  |  |
|  | | | |  |  |
|  | | | |  |  |
|  | | | |  |  |
|   |   |   |   |
|   |   |   |   |
|___|___|___|___|

5
____________________
|  | | | |  |  | | |
|  | | | |  |  | | |
|  | | | |  |  | | |
|  | | | |  |  | | |
|   |   |   |   |   |
|   |   |   |   |   |
|___|___|___|___|___|

6
________________________
|  | | | |  |  | | | | |
|  | | | |  |  | | | | |
|  | | | |  |  | | | | |
|  | | | |  |  | | | | |
|   |   |   |   |   |   |
|   |   |   |   |   |   |
|___|___|___|___|___|___|

7
_____________________________
|  | | | |  |  | | | | | |  |
|  | | | |  |  | | | | | |  |
|  | | | |  |  | | | | | |  |
|  | | | |  |  | | | | | |  |
|   |   |   |   |   |   |   |
|   |   |   |   |   |   |   |
|___|___|___|___|___|___|___|

8
________________________________
|  | | | |  |  | | | | | |  |  |
|  | | | |  |  | | | | | |  |  |
|  | | | |  |  | | | | | |  |  |
|  | | | |  |  | | | | | |  |  |
|   |   |   |   |   |   |   |   |
|   |   |   |   |   |   |   |   |
|___|___|___|___|___|___|___|___|

And last but not least, here is a full 52 key output:
_________________________________________________________________________________________________________________________________________________________________________________________________________________
|  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |
|  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |
|  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |
|  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |  | | | | | |  |  | | | |  |
|   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |
|   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |   |
|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|___|

Standard loopholes are banned, and the shortest answer in bytes wins!

What are "standard loopholes"?

@Wildcard http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default

Are trailing spaces on any/all lines permitted? How about a trailing newline?

@Sok Those are both okay as long as it's visually the same. leading spaces or newlines are not.

Umm... There are 88 keys on a piano...

@AlexL. Since real 88-key pianos have 55 white keys.

@DrGreenEggsandHamDJ Well, after the pattern specification, you said something about an 81 key keyboard.

I thought that pianos had 52 white keys (88 total keys), and a quick Google seems to confirm that.

@BMac >> I don't... << I have no idea what you're talking about. I said 52, see! You can clearly see it in the R̶e̶v̶i̶s̶i̶o̶n̶ ̶H̶i̶s̶t̶o̶r̶y̶ Uh, I mean the state of the post right now! Anyway, thankfully that probably won't break any existing answers, since most of them probably work to 55+ anyway.

Why isn't L describing the key which goes on the left of the middle and is shaped like an L, instead of being named after the bit which isn't there? And Middle is named for the bit which is present, rather than the bits which are missing. :-|  I never did get on with musical notations...

@TessellatingHeckler That's not musical notation, it's a notation that I made up. AFAIK there's no distinction between the shapes of the keys in music notation.

Pyth, 68 65 63 bytes
*lJ:+\|s@Lj;*L" |"_j4536 7*4Q" $"k\_jb+*4]J*2]K+\|*Q"   |":Kd\_

Try it online!
Test suite.
In this version, I just substituted the assignments (J and K) inside to save 2 bytes. Therefore, read the version below.
Previous 65-byte version with explanation
J:+\|s@Lj;*L" |"_j4536 7*4Q" $"kK+\|*Q"   |"*lJ\_jb+*4]J*2]K:Kd\_

Try it online!
J:+\|s@Lj;*L" |"_j4536 7*4Q" $"k    This part generates the most irregular line.

        j;*L" |"_j4536 7            Generate the whole line by black magic
      @L                *4Q         Get the first (4*input) characters of it, with wrapping.
  +\|                               Add "|" in front of it (we took away the first "|")
 :                         " $"k    Replace the ending space by nothing
J                                   Store the line to J.

K+\|*Q"   |"      This part generates the line just below the irregular line.
    *Q"   |"      Repeat "   |" input times
 +\|              Prepend "|"
K                 Store to K

*lJ\_     Now we can actually start printing

*  \_     Repeat "_" ...
 lJ                      [the length of J] times
          (and implicitly print it out)

jb+*4]J*2]K

   *4]J             Repeat J 4 times
       *2]K         Repeat K 2 times
  +                 Concatenate them together
jb                  Join with newlines
                    (and implicitly print it out)

:Kd\_

:K      Replace in K
  d                  " "
   \_                    by "_"
        (and implicitly print it out)

Black magic
We find the irregular line from input=7, and cut out the first "|":
"  | | | |  |  | | | | | |  |"
 2  1 1 1 2  2  1 1 1 1 1 2

j;*L" |"_j4536 7    Black magic.

         j4536 7    4536 converted to base 7: [1,6,1,4,0]
        _           Reverse: [0,4,1,6,1]
  *L" |"            Repeat " |" <each element> times:
                    [""," | | | |"," |"," | | | | | |"," |"]
j;                  Join by whitespace:
                    "  | | | |  |  | | | | | |  |"

I've only just got your joke. Groan...

JavaScript (ES6), 155 149 147 bytes
n=>[`_`[r=`repeat`](n*4+(9>>n%7&1)),s=[...Array(n*12/7|0)].map((_,i)=>1998>>i%12&1?` |`:`  |`).join``,s,s,s,s=`   |`[r](n),s,`___|`[r](n)].join`\n|`

Where \n represents the literal newline character. Leverages the fact that all the lines after the first start with a | character. Explanation:

f=
n=>[                        // Start by building up a list of rows
 `_`[r=`repeat`](n*4+       // 4 underscores per key
  (9>>n%7&1)),              // Third and seventh keys have one extra
 s=[...Array(n*12/7|0)]     // Calculate total of white and black keys
  .map((_,i)=>              // Process each key in turn
   1998>>i%12&1?` |`:`  |`  // Bitmap of narrow and wide keys
  ).join``,                 // Join the keys together
 s,s,s,                     // Repeated 4 times in total
 s=`   |`[r](n),            // Full width part of the white keys
 s,                         // Repeated twice in total
 `___|`[r](n)               // Base of the white keys
].join`\n|`                 // Join the rows together
<input type="number" oninput="o.textContent=f(this.value);"><pre id=o>

Edit: Saved 2 bytes by fixing my misreading of the spec on the height of the keys.

You, sir, just blew my mind.

Oh this is good, can you add some sort of walkthrough?

You should add a runnable snippet if you can.

Ruby, 119 bytes
->n{puts ?_*(1+n*4+(0<=>-n%7%4)),(0..6).map{|i|("01"+("%b"%[0xAADAAAD,13][i/4]*99)).tr('10',' |_|'[i/6*2,2])[0,1+n*4]}}

Ungolfed in test program
f=->n{
  puts ?_*(1+n*4+(0<=>-n%7%4)),           #Draw 1+n*4 _'s for top row (one less if -n%7%4>0, black note), then...
  (0..6).map{|i|                          #Cycle through remaining 7 rows
    ("01"+("%b"%[0xAADAAAD,13][i/4]*99)).   #Generate string version of binary number corresponding to pattern, repeat 99 times.
    tr('10',' |_|'[i/6*2,2]                 #Binary 1-> space or underscore. Binary 0 -> | (These choices ensured no leading 0)
    )[0,1+n*4]                              #truncate to the right amount of keys.
  }
}

10.times{|j|f[j]}

><>, 188 182 bytes
&0"_"o011.
.\:7%8g95*-"_"o1-:a1@@?.~~~1+:&:&=1+1$
.v~:7=?;ao"|"o1+:0$0$
.>:7%8g"0"-4*:9go1+:9go1+:9go1+9go1+:&:&=3$-1$
 ^
.>"| _"{:}7=?$~::oooo1+:&:&(3*2+1$
>^
^
0120112
  | | | |  |

The number of white keys to display should be present on the stack at program start.
Edit: I managed to shave off a few bytes through combining the output for lines 5/6 and 7. Previous version:
&0"_"o011.
.\:7%8g95*-"_"o1-:a1@@?.~~~1+:&:&=1+1$
.v~ao"|"o1+:0$0$.
.>:7%8g"0"-4*:9go1+:9go1+:9go1+9go1+:&:&=3$-1$
 ^
.>"|   "oooo1+:&:&(3*2+1$
 ^
 "|___"oooo1+:&:&=?;
0120112
  | | | |  |

Python 3 2, 191 185 180 182 171 145 144 133 132 bytes
def k(n):print"\n|".join(["_"*(4*n+(9>>n%7&1))]+[''.join("   ||"[1998>>j%12&1::2]for j in range(n*12/7))]*4+["   |"*n]*2+["___|"*n])

This could use some golfing but I've fiddled with the code so much already that I may not see where the golfable spots are. Any golfing suggestions are welcome.
Edit: Misread the spec on the height of the keys. This bug has been fixed.
Edit: Borrowed Neil's 12 key idea from his Javascript answer, removed some parentheses, and switched to Python 2 to save 11 bytes.
Edit: Lots of changes to get the function down to one for loop.
Edit: Now a program instead of a function.
Edit: Now using print"\n|".join() as suggested by Neil to save 11 bytes. Turned the program back into a function to save a byte.

I think you could save another 10 bytes by using my "\n|".join trick.

Ah, I'd forgotten to remove the space between print and "\n|"!

PHP, 238 bytes
$n=$argv[1];$s=str_repeat;echo'_'.$s($a=$s('_',28),$m=($n-$r=$n%7)/7).substr($a,0,$k=4*$r-($r&&$r!=3))."\n",$g='|'.$s($b='  | | | |  |  | | | | | |  |',$m).substr($b,0,$k)."\n",$g,$g,$g,$h='|'.$s('   |',$n)."\n",$h,'|'.$s('___|',$n)."\n";

As usual, prepend the code with <?php , put it into a PHP file (let's name it keyboard.php) and run it using:
$ php -d error_reporting=0 keyboard.php 55

Two more bytes can be saved on PHP7 by squeezing the initialization of $n and $s into their first use:
echo'_'.($s=str_repeat)($a=$s('_',28),$m=($n-$r=($n=$argv[1])%7)/7).substr($a,0,$k=4*$r-($r&&$r!=3))."\n",$g='|'.$s($b='  | | | |  |  | | | | | |  |',$m).substr($b,0,$k)."\n",$g,$g,$g,$h='|'.$s('   |',$n)."\n",$h,'|'.$s('___|',$n)."\n";

The ungolfed code, a test suite and other goodies can be found on github.

C# 1683 bytes
So....after seeing Neil's answer above this is pretty embarrassing, but I'll post it anyway 'cause it took me a while (bless). I used C# to create mine. Inside the "Fncs" class I created an array of the typical order of keys. Then, I created a function which can allow the user to get an appropriate index for this array based on a given integer. In order to edit individual lines, I created a "PianoKeyboard" class which contains a dictionary storing multiple strings representing the individual lines. Finally, I created the "DrawKey" function which appends the appropriate text to the individual lines and the "GetKeys" function which returns the overall string value.
namespace ASCIIPiano{public enum WhiteKeyType{Left,Middle,Right}public static class Fncs{public static WhiteKeyType[] Order{get{return new WhiteKeyType[]{WhiteKeyType.Left,WhiteKeyType.Middle,WhiteKeyType.Right,WhiteKeyType.Left,WhiteKeyType.Middle,WhiteKeyType.Middle,WhiteKeyType.Right};}}public static PianoKeyboard DrawKey(this PianoKeyboard keyboard, WhiteKeyType type){keyboard.Append(1,"_____");if (type == WhiteKeyType.Left){keyboard.Append( 2,"|  | ");keyboard.Append( 3,"|  | ");keyboard.Append( 4,"|  | ");keyboard.Append( 5, "|  | ");}else if (type == WhiteKeyType.Middle){keyboard.Append(2, " | | ");keyboard.Append(3," | | ");keyboard.Append( 4," | | ");keyboard.Append(5," | | ");}else{keyboard.Append( 2," |  |");keyboard.Append(3, " |  |");keyboard.Append(4," |  |");keyboard.Append(5, " |  |");}keyboard.Append(6,"|   |");keyboard.Append(7,"|   |");keyboard.Append(8,"|___|");return keyboard;}public static int GetWhiteKeyIndex(this int number){return number % 7;}public static string GetKeys(this int quantityofwhitekeys){PianoKeyboard keyboard = new PianoKeyboard();for (int i = 0; i < quantityofwhitekeys; i++){WhiteKeyType key=Fncs.Order[i.GetWhiteKeyIndex()];keyboard.DrawKey(key);}return keyboard.TOTALSTRING;}}public class PianoKeyboard{public PianoKeyboard(){}private Dictionary<int, string> lines = new Dictionary<int, string>();public void Append(int index,string value){if (index > 8 || index < 1){throw new Exception("URGH!");}else{if (lines.Keys.Contains(index)){lines[index] += value;}else{lines.Add(index, value);}}}public string TOTALSTRING{get{string returner = "";foreach (int key in lines.Keys){returner += lines[key] + "\n";}return returner;}}}}

Hi, welcome to PPCG! As you might have noticed, code-golf challenges are about writing the shortest code possible. Languages like C#, Java and basically any OO language are therefor most often a bad choice. However, it can be a great practise to write short code so I'm not trying to discourage you from doing so :) As for your answer, it's a nice way to solve this problem if you wouldn't keep the length of code in mind! Have fun, and good luck trying to write small C# code :)

@BassdropCumberwubwubwub Thanks, I'm actually new to this site (of course). Kinda new to programming too but I'll do my best ^_^

Funny to see a 4KB answer between all the <200 byte answers. I personally also like to write Java code in as short as possible for these Codegolf challenges, since I never used any codegolf language at all. Of course Java and C# can never compete with other answers, but it's fun to try and create code as short as possible. Here is a post you might find interesting: Tips for code-golfing in C#. PS: I've copied your code to a file to see the exact amount of bytes, which is: 4,052. ;) Anyway, welcome to PPCG!

@KevinCruijssen Thanks. Tbh I'm not that experienced in anything other than C# so any help with code golf in C# is appreciated.

Welcome to PPCG, but this answer needs to be fully golfed. I see whitespace and comments that can be removed.

1.: Rename your variables, so they're 1 character long 2.: Always add a proper byte count, it needs tk be byte precise

3.: Never even try to compete against javascript with langauges like java, C, C#, C++ etc., you can't. 4.: If not specified, you can assume the input will be correct, thus no correctness-check is needed. 6.: If you use a string multiple times ("|  |"), save it in a variable.

This can be golfed down to ~500 bytes if you want to do it.

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


text:
Golf the K-means algorithm
K-means is a standard unsupervised clustering algorithm, which, given a set of "points" and a number of clusters K, will assign each "point" to one of K clusters.
Pseudo-Code of K-means
Note that there are many variants of K-means. You have to implement the algorithm I am describing below. You may have some variation on the algorithm or use built-ins as long as you would get the same result as this algorithm given the same initial points.
In this challenge, all inputs will be points on the 2D plane (each point is represented by its coordinates in x and y).
Inputs: K, the number of clusters
        P, the set of points

Choose K points of P uniformly at random
Each chosen point is the initial centroid of its cluster

Loop:
     For each point in P:
         Assign to the cluster whose centroid is the nearest (Euclidean distance)
         In case of a tie, any of the tied cluster can be chosen

     Recompute the centroid of each cluster:
         Its x coordinate is the average of all x's of the points in the cluster
         Its y coordinate is the average of all y's of the points in the cluster

Until the clusters don't change from one iteration to the next

Output: the set of clusters

Inputs and Outputs

You may take K and P through STDIN, or as a function argument, etc.
P and the points in P can be represented using any structure that is natural for set/lists in your language of choice.
K is a strictly positive integer.
You may assume that inputs are valid.
There will always be at least K points in P.
You may output the clusters to STDOUT, return them from a function, etc.
The ordering of the clusters and the ordering inside the clusters is unimportant.
-You can either return groups of points to represent clusters, or each point labeled with an identifier for the cluster (e.g. an integer).

Test cases
Since the resulting clusters depend on which points were initially chosen, you may not all get the same results (or the same result each time you run your code).
Therefore, only take the output as an example output.
Input:
  K = 1
  P = [[1,2.5]]
Output:
  [[[1,2.5]]]

Input:
  K = 3
  P = [[4,8], [15,16], [23,42], [-13.37,-12.1], [666,-666]]
Output:
  [[[666,-666]],[[-13.37,-12.1],[4,8]],[[15,16],[23,42]]]

Input:
  K = 2
  P = [[1,1], [1,1], [1,1]]
Output:
  [[[1,1]],[[1,1],[1,1]]]

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

Are built-ins allowed when the results are indistinguishable from your algorithm?

@MartinBüttner if you can justify that given the same initial points, it converges to the same result, yes.

Woud it also be acceptable to output labels of membership of a cluster for each point? (E.g. all points of the first cluster have label 1, all points of the second one have label 2 e.t.c)

@flawr Yes, this is acceptable.

Degenerate test case: K=2, P = [[1,1], [1,1], [1,1]].

Matlab, 25 bytes
@(x,k)kmeans(x,k,'S','u')

Given a n x 2 matrix (one row per point e.g. [[4,8]; [15,16]; [23,42]; [-13.37,-12.1]; [666,-666]]) this functions returns a list of labels for each input point.

C++, 479 474 bytes
Only ~20x as much as Matlab!
Golfed
#define V vector

#define f float
struct P{f x,y,i=0;f d(P&p){return(p.x-x)*(p.x-x)+(p.y-y)*(p.y-y);}f n(P&p){return i?x/=i,y/=i,d(p):x=p.x,y=p.y,0;}f a(P&p){x+=p.x,y+=p.y,i++;}};P z;int l(P a,P b){return a.d(z)<b.d(z);}f m(f k,V&p){f s=p.size(),i,j=0,t=1;V c(k),n=c,d;for(random_shuffle(p.begin(),p.end());j<k;c[j].i=j++)c[j]=p[j];for(;t;c=n,n=V(k)){for(i=0;i<s;i++)d=c,z=p[i],sort(d.begin(),d.end(),l),j=d[0].i,p[i].i=j,n[j].a(p[i]);for(j=t=0;j<k;j++)t+=n[j].n(c[j]);}}

The input/output to the algorithm is a set of points (struct P) with x and y; and the output is the same set, with their i's set to indicate the index of the output cluster that the point ends in.
That extra i is also used to identify the clusters. In the main loop, the closest centroid to each point is found by sorting a copy of the current centroids by proximity to that point.
This handles degenerate cases (empty clusters) by keeping the corresponding centroids' previous position (see definition of P::n, which also returns distance-to-previous-centroid). A few chars could be saved by assuming that these will not crop up.
Ungolfed, with main
#include <cstdio>
#include <ctime>
#include <cstdlib>
#include <vector>
#include <algorithm>
using namespace std;

#define V vector

#define f float
struct P{
    f x,y,i=0;
    f d(P&p){return(p.x-x)*(p.x-x)+(p.y-y)*(p.y-y);} // distance squared
    f n(P&p){return i?x/=i,y/=i,d(p):x=p.x,y=p.y,0;} // normalize-or-reset
    f a(P&p){x+=p.x,y+=p.y,i++;}                     // add coordinates
};
P z;int l(P a,P b){return a.d(z)<b.d(z);}            // closer-to-z comparator
f m(f k,V&p){
    f s=p.size(),i,j=0,t=1;V c(k),n=c,d;
    for(random_shuffle(p.begin(),p.end());j<k;c[j].i=j++)
        c[j]=p[j];                                // initial random assignment
    for(;t;c=n,n=V(k)){
        for(i=0;i<s;i++)                          // assign to clusters
            d=c,z=p[i],sort(d.begin(),d.end(),l),
            j=d[0].i,p[i].i=j,n[j].a(p[i]);       // and add those coords
        for(j=t=0;j<k;j++)t+=n[j].n(c[j]);        // normalize & count changes
    }
}

int main(int argc, char **argv) {
    srand((unsigned long)time(0));

    int k;
    V p;
    sscanf(argv[1], "%d", &k);
    printf("Input:\n");
    for (int i=2,j=0; i<argc; i+=2, j++) {
        P n;
        sscanf(argv[i], "%f", &(n.x));
        sscanf(argv[i+1], "%f", &(n.y));
        p.push_back(n);
        printf("%d : %f,%f\n", j, p[j].x, p[j].y);
    }

    m(k,p);
    printf("Clusters:\n");
    for (int q=0; q<k; q++) {
        printf("%d\n", q);
        for (unsigned int i=0; i<p.size(); i++) {
            if (p[i].i == q) printf("\t%f,%f (%d)\n", p[i].x, p[i].y, i);
        }
    }
    return 0;
}

I know I might be late in this comment, but could you define a macro #define R p){return and change the second argument of l to p so you could use it three times total?

J, 60 54 bytes
p=:[:(i.<./)"1([:+/&.:*:-)"1/
]p](p(+/%#)/.[)^:_(?#){]

Defines a helper verb p which takes a list of points and centroids and classifies each point by the index of the nearest centroid. Then, it uses that to repeat the process of choosing new centroid by taking the averages of the points in each cluster until it converges, and then to partition the points for output.
Usage
The value of k is given as an integer on the LHS. The list of points is given as a 2d array on the RHS. Here it is specified as a list of points which is reshaped into a 2d array of 5 x 2. The output will be the label for which cluster each point belongs in the same order as the input.
If you desire to use a fixed seed for reproducible results, replace the ? with a ?. at (?#).
   p =: [:(i.<./)"1([:+/&.:*:-)"1/
   f =: ]p](p(+/%#)/.[)^:_(?#){]
   3 f (5 2 $ 4 8 15 16 23 42 _13.37 _12.1 666 _666)
0 1 1 0 2

Explanation
[:(i.<./)"1([:+/&.:*:-)"1/  Input: points on LHS, centroids on RHS
           (          )"1/  Form a table between each point and centroid and for each
                     -        Find the difference elementwise
            [:     *:         Square each
              +/&.:           Reduce using addition
                              Apply the inverse of square (square root) to that sum
[:(     )"1                 For each row of that table
     <./                      Reduce using min
   i.                         Find the index of the minimum in that row
                            Returns a list of indices for each point that shows
                            which centroid it belongs to

]p](p(+/%#)/.[)^:_(?#){]  Input: k on LHS, points on RHS
                    #     Count the number of points
                   ?      Choose k values in the range [0, len(points))
                          without repetition
                       ]  Identity function, get points
                      {   Select the points at the indices above
  ]                       Identity function, get points
   (         )^:_         Repeat until convergence
    p                       Get the labels for each point
             [              Identity function, get points
           /.               Partition the points using the labels and for each
      +/                      Take the sums of points elementwise
         #                    Get the number of points
        %                     Divide sum elementwise by the count
                            Return the new values as the next centroids
]                         Identity function, get points
 p                        Get the labels for each point and return it

I would give +1, but I'm scared that breaking your 3k will curse me.

CJam (60 bytes)
{:Pmr<1/2P,#{:z{_:+\,/}f%:C,{P{C\f{.-Yf#:+}_:e<#1$=},\;}%}*}

This is a function which takes its input in the form k p on the stack. It assumes that the points are represented with doubles, not ints. It doesn't implicitly assume anything about the dimension of the points, so it would cluster equally well in 6-D Euclidean space as in the specified 2-D.
Online demo

Mathematica 14 12 bytes
Since built-ins are allowed, this should do it.
FindClusters

Example
FindClusters[{{4, 8}, {15, 16}, {23, 42}, {-13.37, -12.1}, {666, -666}}, 3]

{{{4, 8}, {-13.37, -12.1}}, {{15, 16}, {23, 42}}, {{666, -666}}}

You don't need the brackets. f = FindClusters, f[something].

ok, thanks  I wasn't sure.

Jelly, 24 bytes
_ÆḊ¥þ³i"Ṃ€$
ẊḣµÇÆmƙ³µÐLÇ

Try it online!
Uses features that were implemented after this challenge was posted. Supposedly, this is no longer non-competing.
Explanation
_ÆḊ¥þ³i"Ṃ€$  Helper link. Input: array of points
             (Classify) Given a size-k array of points, classifies
             each point in A to the closet point in the size-k array
    þ        Outer product with
     ³       All points, P
   ¥         Dyadic chain
_              Subtract
 ÆḊ            Norm
          $  Monadic chain
      i"     Find first index, vectorized
        Ṃ€   Minimum each

ẊḣµÇÆmƙ³µÐLÇ  Main link. Input: array of points P, integer k
  µ           Start new monadic chain
Ẋ               Shuffle P
 ḣ              Take the first k
        µ     Start new monadic chain
   Ç            Call helper (Classify)
      ƙ         Group with those values the items of
       ³        All points, P
    Æm            Take the mean of each group
         ÐL   Repeat that until the results converge
           Ç  Call helper (Classify)

R, 273 bytes
function(K,P,C=P[sample(nrow(P),K),]){while(T){D=C
U=sapply(1:nrow(P),function(i)w(dist(rbind(P[i,],C))[1:K]))
C=t(sapply(1:K,function(i)colMeans(P[U==i,,drop=F])))
T=isTRUE(all.equal(C,D))}
cbind(U,P)}
w=function(x,y=seq_along(x)[x==min(x)])"if"(length(y)>1,sample(y,1),y)

Try it online!
Takes Pas a matrix, with x and ycoordinates in the first and second column respectively. Returns P with a first column added which indicates cluster index (integer).
I had to redefine w by copying the source from nnet::which.is.max to conform to the requirement that cluster is chosen randomly in case of ties. Otherwise I would use which.minfrom base for a total of 210 bytes. There is still room for golfing but I did not want to obfuscate it to much to give others a chance to spot possible issues within my code.

Julia 213 bytes
function f(p,k)
A=0
P=size(p,1)
c=p[randperm(P)[1:k],:]
while(true)
d=[norm(c[i]-p[j]) for i in 1:k, j in 1:P]
a=mapslices(indmin,d,1)
a==A&&return a
A=a
c=[mean(p[vec(a.==i),:],1) for i in 1:k]
end
end

Returns an array of the same length as p, with integers indicating which cluster the corresponding element of p belongs to.
I think there is still a fair bit of scope to optimize the character count down.
(Of course I could just use the Clustering.jl package to do it trivially)

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


text:
Interpret DOGO!
Interpret DOGO
DOGO is a lesser known programming language. While the original DOGO (a joke language from a Usenet post) has never been implemented, a language resembling it has been created. The commands for the language are:
+===========+================================================================+
|  Command  |                          Description                           |
+===========+================================================================+
| SIT       | If the value of the current memory cell is 0, jump to STAY.    |
+-----------+----------------------------------------------------------------+
| STAY      | If the value of the current memory cell is not 0, jump to SIT. |
+-----------+----------------------------------------------------------------+
| ROLL-OVER | Select the next operation from the operation list.             |
+-----------+----------------------------------------------------------------+
| HEEL      | Execute the currently selected operation.                      |
+-----------+----------------------------------------------------------------+

The operations are:
+========+=======================================================+====+
| Number |                      Description                      | BF |
+========+=======================================================+====+
|      0 | Increment current memory cell.                        | +  |
+--------+-------------------------------------------------------+----+
|      1 | Decrement current memory cell.                        | -  |
+--------+-------------------------------------------------------+----+
|      2 | Move to next memory cell.                             | >  |
+--------+-------------------------------------------------------+----+
|      3 | Move to previous memory cell.                         | <  |
+--------+-------------------------------------------------------+----+
|      4 | Input a byte and store it in the current memory cell. | ,  |
+--------+-------------------------------------------------------+----+
|      5 | Output the current memory cell as ASCII.              | .  |
+--------+-------------------------------------------------------+----+

Examples
Hello World:
roll-over roll-over heel roll-over roll-over roll-over roll-over heel heel heel
heel heel heel heel heel heel sit roll-over roll-over roll-over heel roll-over
roll-over roll-over heel heel heel heel heel heel heel heel roll-over roll-over
heel roll-over roll-over roll-over roll-over roll-over heel roll-over roll-over
roll-over roll-over roll-over stay roll-over roll-over roll-over heel roll-over
roll-over heel roll-over roll-over roll-over heel roll-over roll-over roll-over
roll-over heel heel heel heel heel heel heel sit roll-over roll-over roll-over
heel roll-over roll-over roll-over heel heel heel heel roll-over roll-over heel
roll-over roll-over roll-over roll-over roll-over heel roll-over roll-over
roll-over roll-over roll-over stay roll-over roll-over roll-over heel roll-over
roll-over roll-over heel roll-over roll-over roll-over roll-over roll-over heel
roll-over heel heel heel heel heel heel heel roll-over roll-over roll-over
roll-over roll-over heel heel roll-over heel heel heel roll-over roll-over
roll-over roll-over roll-over heel roll-over roll-over roll-over heel heel heel
roll-over roll-over roll-over roll-over heel heel heel heel heel heel heel heel
sit roll-over roll-over roll-over heel roll-over roll-over roll-over heel heel
heel heel roll-over roll-over heel roll-over roll-over roll-over roll-over
roll-over heel roll-over roll-over roll-over roll-over roll-over stay roll-over
roll-over roll-over heel roll-over roll-over heel roll-over roll-over roll-over
heel heel heel roll-over roll-over roll-over roll-over heel heel heel heel heel
heel heel heel heel heel sit roll-over roll-over roll-over heel roll-over
roll-over roll-over heel heel heel heel heel heel heel heel heel roll-over
roll-over heel roll-over roll-over roll-over roll-over roll-over heel roll-over
roll-over roll-over roll-over roll-over stay roll-over roll-over roll-over heel
roll-over roll-over roll-over roll-over heel heel heel roll-over roll-over
roll-over roll-over heel roll-over roll-over roll-over roll-over heel heel heel
heel roll-over roll-over heel roll-over heel heel heel roll-over roll-over
roll-over roll-over roll-over heel roll-over roll-over heel heel heel heel heel
heel roll-over roll-over roll-over roll-over heel roll-over roll-over heel heel
heel heel heel heel heel heel roll-over roll-over roll-over roll-over heel
roll-over roll-over roll-over heel heel roll-over roll-over roll-over roll-over
heel roll-over roll-over roll-over roll-over roll-over heel

99 bottles of beer
Rules

Each submission should be either a full program or function. If it is a function, it must be runnable by only needing to add the function call to the bottom of the program. Anything else (e.g. headers in C), must be included.
If it is possible, please provide a link to an online site where your code can be tested.
Your program cannot write anything to STDERR (or something similar).
You can take input from STDIN (or the closest alternative in your language), or as an argument.
Standard loopholes are forbidden.

Scoring
Programs are scored according to bytes. The default character set is UTF-8, if you are using a different one, please specify.
That aside, this is code-golf, and the lowest byte count will be deemed the winner!
Submissions
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
# Language Name, N bytes

where N is the size of your submission. If you improve your score, you can keep old scores in the headline, by striking them through. For instance:
# Ruby, <s>104</s> <s>101</s> 96 bytes

If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the last number in the header:
# Perl, 43 + 2 (-p flag) = 45 bytes

You can also make the language name a link which will then show up in the leaderboard snippet:
# [><>](http://esolangs.org/wiki/Fish), 121 bytes

Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.

/* Configuration */

var QUESTION_ID = 79350; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 53406; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];

  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '
' + c.body.replace(OVERRIDE_REG, '') + '
';
    });

    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });

  });

  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;

    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (/ b.lang) return 1;
    if (a.lang < b.lang) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}

<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">

Leaderboard

	Author	Language	Size

Winners by Language

Language	User	Score

{{PLACE}}	{{NAME}}	{{LANGUAGE}}	{{SIZE}}	Link

{{LANGUAGE}}	{{NAME}}	{{SIZE}}	Link

Update:
Sorry for not clarifying the sit and stay commands very well. They are, as @user6245072 said, like [ and ] in BF.
Update 2:
To clarify @KennyLau's questions:

The default operation is 0.
Memory consists of 8-bit cells.
Cells wrap on overflow/underflow.
Input is required for operation 4.

Do we need to handle extraneous input? Such as an input of sit lie-down roll-over play-dead heel

Also, operation 1 says "increment next cell`, but the corresponding BF code is "decrement current cell". Which one is correct behavior?

@KevinLau-notKenny Thanks, my fault.

Ruby, 287 bytes
Runs on an infinite tape in both directions. DOGO input is a file on the command line. If there is no command line argument, a DOGO program will still work if passed in as STDIN, unless it uses operation 3 (get a byte from STDIN) in which case I have no idea. At any rate, file input is best.
Assumes no other text other than the four commands and whitespace exist in the program file.
Hello World Demonstration
i=k=o=0;m={}
c=$<.read.upcase.split.map{|e|%w{SIT STAY ROLL-OVER HEEL}.index e}.join
(m[k]||=0
e=c[i].to_i
e>2?o>4?$><<m[k].chr:
o>3?m[k]=STDIN.getc.ord:
o>1?k+=o>2?-1:1:
m[k]=o<1?-~m[k]%256:~-m[k]%256:
e>1?o=-~o%6:
e>0?m[k]>0?i=c.rindex(?0,i):0:
m[k]<1?i=c.index(?1,i):0
i+=1)while c[i]

Python 3, 388 398 373 371 bytes
Assumes 256 memory cells. Just a straightforward implementation, easily beatable, probably can be golfed more. Try it on repl.it.
Thanks to @EasterlyIrk for having me realize that Python 3 is much shorter that Python 2.
EDIT: Realized I only accounted for over/underflow while printing, not in actual value.
Thanks to @KevinLau-notKenney for saving 25 (!) bytes with list multiplication and inversion operator tricks
EDIT: -3 bytes by putting 256 into a variable, -4 messing with operators, +8 making sure it is lowercase
def p(s):
 b=256
 l,m=[w[-1]for w in s.lower().split()],[0]*b
 i=p=x=0
 while x<len(l):
  c=l[x]
  if'm'>c:
   if 1>i:m[p]=-~m[p]%b
   if 1==i:m[p]=~-m[p]%b
   if 2==i:p=-~p%b
   if 3==i:p=~-p%b
   if 4==i:m[p]=ord(input()[0])
   if 4<i:print(chr(m[p]),end="")
  if'r'==c:i=-~i%6
  if't'==c and m[p]<1:x+=l[:x].index('y')
  if'x'<c and m[p]>0:x-=l[x::-1].index('t')
  x+=1

Why use sys.stdout.write? Why not print?

@EᴀsᴛᴇʀʟʏIʀᴋ print adds newlines. the actual print function with the end arg is in Python 3

What makes python3 out of the question? Just tested, works fine with print(...,end='')

@EᴀsᴛᴇʀʟʏIʀᴋ I was too lazy to install it. I might as well change the answer, tho

Then maybe try ideone or a online python interpreter for that. Or install it. :P

[0]*256 generates the tape in much fewer bytes than your range trick. Also, -~p%256 saves 2 bytes over (p+1)%256, and same with ~-p%256 for (p-1)%256

@KevinLau-notKenny wow, I had no idea the inversion operator could do that! Thanks!


text:
Traveling on a flat Earth
Coordinates in the flat-Earth world consist of latitude (x) and longitude (y), which are integers in the range 0...9999. Much like Gaussian integers, but they are always written using this notation:
411S 370E

That is, with S or N appended to the latitude, and E or W appended to the longitude, with space(s) between the two components.
Goal
Write a program (not a function) that reads two coordinates, separated by whitespace, and outputs their sum. The first coordinate is a starting point, the second one is a displacement, and the output is the resulting position.
Input/Output
Since this challenge is partially about formatting, I'll try to define the input and output formats unambiguously.
The preferred input format has 1 space between the coordinate components, no leading zeros, and a newline character between the two coordinates. The program must be able to read the preferred format.
The output can contain any amount of whitespace and leading zeros. If it's different from the preferred input format, the program must be able to read this format too.
Just to make it clear, the input cannot (will not) contain any additional formatting characters. Just spaces and newlines where needed.
Scoring
This is an experiment on a new winning condition. I'll choose the winner by accepting an answer in a few weeks. If a better answer appears afterwards, I'll change the accepted answer.
The score for the program is its byte count. The winning program is one that is shorter than 400 bytes, has the fewest byte count, but is written in the most verbose programming language. To determine the winner:

Remove programs with byte count 400 or more (they can participate but cannot win)
Consider only the shortest program for each programming language
The longest program wins

Polyglots compete against programs in all languages in which they are valid (e.g. if a program is valid in both bash and sh, it competes against programs in both languages).
Test cases
In the test cases, the first two lines are the input, and the third line is the output.
0S 0E
0S 0W
0N 0E

(the direction of zero doesn't matter, both in input and output)

0S 9999E
9999N 9999W
9999N 0E

(maximal values)

42S 314W
42N 2718W
0N 3032W

(the direction of zero doesn't matter in the output)

5555N 8888W
7777S 0E
2222S 8888W

(no negative values; change the direction if you need to change the sign)

0001N        4545W
0999N        5454W
1000N        9999W

(if the program outputs leading zeros and several spaces, it must be able to read them; it must also be able to read input that doesn't contain them)

8888N 8888W
9999N 9999W

(invalid input - any behavior is acceptable, including crash and infinite loop)

I'm genuinely curious if this scoring mechanism will work out, but I feel like it's game-able. In particular, I could write a (suboptimal) solution at exactly 399 bytes in some crazy hard esolang (or one of my own) and even though it might be easily golfable, it would be somewhat unlikely that anyone else would be willing to learn the language just to beat my score in this challenge.

I hope it's clear now. Please look for "preferred input format" in the text and ask for further clarification if it's still ambiguous.

@anatolyg I find that paragraph very misleading. You talk about "flexibility" and a preferred input format, but then require all solutions to use exactly that format. Where is the flexibility and what is "preferred" about this format? I think for this challenge it's fine to require one very specific format, but then the specification should unambiguously say so.

No unary input for me?

@MartinBüttner The flexibility is in the output. Not much though.

@KennyLau No, sorry

I don't know why you're saying the Lua answer was winning when the most recent edit to the MATLAB answer was shorter by the time you'd posted the bounty, but hey, it produced more answers! Can't argue with that~ (edit: nvm I forgot that your criteria was not code golf)

A certain Befunge interpreter has a single line input field. If you paste text with a newline your given a space instead. Is this acceptable?

@Linus Seems reasonable

I am not quite sure what You are trying to achieve with your winning condition. You may want to put it to discussion in meta or open chat for it.

ABAP, 377 365 bytes
REPORT r.PARAMETERS: x TYPE string,y TYPE string.DEFINE m.SHIFT &1 RIGHT CIRCULAR.TRANSLATE &1 USING 'W-E+S-N+'. END-OF-DEFINITION. DEFINE o.&1 = |{ &1 * 1 SIGN = RIGHTPLUS DECIMALS = 0 }|.TRANSLATE &1 using &2. END-OF-DEFINITION.
SPLIT: x AT space INTO DATA(a) DATA(b),y AT ' ' INTO DATA(c) DATA(d). m: a,b,c,d.a = a + c.b = b + d.o: a '-S+N',b '-W+E'.WRITE: a, b.

Ungolfed:
REPORT r.
PARAMETERS: x TYPE string,
            y TYPE string.
DEFINE m.
  SHIFT &1 RIGHT CIRCULAR.
  TRANSLATE &1 USING 'W-E+S-N+'.
END-OF-DEFINITION.

DEFINE o.
  &1 = |{ &1 * 1 SIGN = RIGHTPLUS DECIMALS = 0 }|.
  TRANSLATE &1 using &2.
END-OF-DEFINITION.

SPLIT: x AT space INTO DATA(a) DATA(b),y AT ' ' INTO DATA(c) DATA(d).
m: a,b,c,d.
a = a + c.
b = b + d.
o: a '-S+N',b '-W+E'.
WRITE: a, b.

It was actually challenging to be within 400 characters.
Some notes:

Original version had ADD c TO a. which is one of my favourite verbose statements.
The built-in editor would not accept this as a 1 liner
Using subroutines with FORM and PERFORM exploded the char count, so I kept to macros
Chaining statements with colons is discouraged outside of data declarations, but was needed for saving bytes
+ without a preceding space is an offset operator, requiring many spaces in the code
ABAP writes a space after numbers, hence the trick to just replace the sign
In order to use RIGHTPLUS the expression needed to be a number, so the need to mulitply with 1, but then the format has decimals.. so hence DECIMALS

Great! A modern language I have never heard of!

MATLAB, 327 304 296 290 282 276 267 259  255  253 bytes
I think I'm closing in on a limit now. I've managed to remove 51, 60 68 72 74 bytes from an answer I thought was well golfed. =)
Removed 8 bytes by taking the input inside the strsplit, thanks to Luis Mendo. Removed another 6 bytes by taking all the input into one cell array instead of two. Removed another 8 bytes by taking both last statements inside disp(). Removed 6 bytes by removing char and some brackets. This wasn't possible in a previous revision of the answer. Splitting the cell elements into four variables costed 15 bytes, but saved 24, thus 9 bytes saved! 8 additional bytes due to improved disp scheme. 5*~~s saves two bytes compared to (s>0)*5. Thus 4 new bytes saved (for s and t). Taking the opposite of this last expression saves yet another 2 bytes, 83-5*~s is shorter than 78+5*~~s
Golfed code:
x=strsplit([input('','s'),' ',input('','s')]);[a,b,c,d]=x{:};f=@str2num;n=@num2str;i=@sign;s=f(a(1:end-1))*i(a(end)-79)+f(c(1:end-1))*i(c(end)-79);t=f(b(1:end-1))*i(b(end)-79)+f(d(1:end-1))*i(d(end)-79);disp([n(abs(s)),83-5*~s,32,n(abs(t)),87-18*~t,''])

Same code, but with line breaks:
x=strsplit([input('','s'),' ',input('','s')]);
[a,b,c,d]=x{:};
f=@str2num;
n=@num2str;
i=@sign;
s=f(a(1:end-1))*i(a(end)-79)+f(c(1:end-1))*i(c(end)-79);
t=f(b(1:end-1))*i(b(end)-79)+f(d(1:end-1))*i(d(end)-79);
disp([n(abs(s)),78+5*~~s,32,n(abs(t)),69+18*~~t,''])

Test cases:
Save the above as flat_earth.m
flat_earth
0S 0E
0S 0W
0N 0E

flat_earth
0S 9999E
9999N 9999W
9999N 0E

flat_earth
42S 314W
42N 2718W
0N 3032W

flat_earth
5555N 8888W
7777S 0E
2222S 8888W

flat_earth
0001N        4545W
0999N        5454W
1000N 9999W

JavaScript (ES6), 118 bytes
s=>(g=([i,j,k,l,m,n],[o,p])=>(i=(j>p?-i:+i)+(n>p?-j:+j))<0?-i+o:i+p)(a=s.match(/\d+|\w/g),"SN")+' '+g(a.slice(2),"WE")

R, 196 bytes
R is pretty verbose, by golfing standards. Let's see...
i=scan(,'');l=nchar(i);S=W=`-`;N=E=c;n=as.double(substr(i,1,l-1));d=substr(i,l,l);for(j in 1:4)n[j]=get(d[j])(n[j]);o=c(n[1]+n[3],n[2]+n[4]);cat(paste0(abs(o), ifelse(o<0,c("S", "W"),c("N","E"))))

Ungolfed:
input = scan(,'')       # Take input from stdin, separating at newlines and spaces
length = nchar(input)   # Get the number of characters in each input
S=W=`-`                 # These two lines create aliases of `-` (the minus function)
N=E=c                   # and c (the concatenate function).
                        # We will later treat the NSEW part of the coordinate
                        # as a call to a function, to ensure that the numbers
                        # are treated with the correct polarity.
numbers = as.double(substr(input, 1, length-1))
                        # Strip the last character off of every coordinate, convert
                        # to integer
directions = substr(input, length, length)
                        # Strip off the numbers and grab the cardinal directions
for(j in 1:4)
    numbers[j] = get(directions[j])(numbers[j])
                        # For our four numbers, treat the cardinal direction as
                        # a function, which is mapped to `-` for south and west, and
                        # `c` for north and east (which is essentially identity)
output = c(numbers[1]+numbers[3], numbers[2]+numbers[4])
                        # Add together the numbers
cat(paste0(abs(output), ifelse(output<0, c("S", "W"), c("N","E"))))
                        # Output the absolute values of the new coordinates, followed
                        # by "S" or "W" if the number is negative and "N" or "E" if
                        # the number is positive

Edit to add: I just looked at the other answers, and I'm surprised that my entry is one of the shortest! Perhaps R isn't as verbose as I thought...

Java, 372 bytes
import static java.lang.System.*;class A{public static void main(String[]v){String l=" ",s=console().readLine()+l+console().readLine();Integer i=0,n[]=new Integer[4],y;for(;i<4;i++)n[i]=i.parseInt(s.replaceAll("[A-Z] *",l).split(l)[i])*(s.replaceAll("\\d| ","").charAt(i)==(i%2<1?83:87)?1:-1);i=n[0]+n[2];y=n[1]+n[3];out.println((i<0?-i+"N":i+"S")+l+(y<0?-y+"E":y+"W"));}}

Ungolfed
import static java.lang.System.console;
import static java.lang.System.out;

class A {
    public static void main(String[] v) {
        String l = " ", s = console().readLine() + l + console().readLine();
        Integer i = 0, n[] = new Integer[4], y;
        for (; i < 4; i++)
            n[i] = i.parseInt(s.replaceAll("[A-Z] *", l).split(l)[i]) * (s.replaceAll("\\d| ", "").charAt(i) == (i % 2 < 1 ? 83 : 87) ? 1 : -1);
        i = n[0] + n[2];
        y = n[1] + n[3];
        out.println((i < 0 ? -i + "N" : i + "S") + l + (y < 0 ? -y + "E" : y + "W"));
    }
}

Notes

Save as A.java, compile with javac A.java, run with java A. Then enter the inputs line separated or as two separate inputs on stdin.

Outputs:
0S 0E
0S 0W
0S 0W

0S 9999E
9999N 9999W
9999N 0W

42S 314W
42N 2718W
0S 3032W

5555N 8888W
7777S 0E
2222S 8888W

0001N        4545W
0999N        5454W
1000N 9999W

8888N 8888W
9999N 9999W
18887N 18887W

Java, 308 bytes
import java.util.*;class x{public static void main(String[]a){Scanner r=new Scanner(System.in);int[]v=new int[2];int l,x,g,i;for(i=5;i-->1;System.out.println(i<3?""+x*g+"ENWS".charAt(i-g):"")){String s=r.next();x=Integer.parseInt(s.substring(0,l=s.length()-1));x=v[i%2]+=x*=s.charAt(l)>80?-1:1;g=x<0?-1:1;}}}

A more readable version:
import java.util.*;
class x
{
    public static void main(String[]args)
    {
        Scanner r = new Scanner(System.in);
        int[] v = new int[2];
        for (int i = 5; i-->1; )
        {
            String s = r.next();
            int l = s.length() - 1;
            int x = Integer.parseInt(s.substring(0, l));
            x = v[i%2] += x *= s.charAt(l) > 'N' ? -1 : 1;
            int g = x < 0 ? -1 : 1;
            System.out.println(i < 3?"" + x * g + "ENWS".charAt(i-g):"");
        }
    }
}

Golfing in Java is a special kind of fun. The following two lines of code do the same, but the first one is shorter:
(x<0?-x:x)
Math.abs(x)

The code reads 4 tokens from standard input. For each token, the part up to the last character is converted to int, and the last character optionally flips its sign.
Then it adds the value that was read 2 iterations ago. Java initializes arrays to 0, so at the first two iterations this will do the right thing.
Then it will format the values and print them. However, in the first two iterations, it prints the empty string instead (so two extra linebreaks appear in the output).
It uses some funky arithmetic so the iteration variable (4,3,2 or 1) and the sign (-1 or 1) can be combined to a zero-based index into the string "ENWS".

SQL (PostGreSQL 9.4), 305 bytes
PREPARE p(char,char)AS
SELECT string_agg(abs(n)||substr('SNNEEW',i+sign(n)::int,1),' ')FROM(SELECT i,sum(to_number(v,'9999')*CASE right(v,1)WHEN'N'THEN 1 WHEN'E'THEN 1 ELSE -1 END)n
FROM(SELECT CASE WHEN v~'[NS]' THEN 2 ELSE 5 END i,v
FROM regexp_split_to_table($1||' '||$2,' ')v)i
GROUP BY i ORDER BY i)g

Implemented as a prepared statement that takes 2 character parameters.  One parameter for each input line.
It is called as follows
execute p('0S 9999E','9999N 9999W');

and outputs a row containing a single character column for the result.  9999N 0E

Ruby, 186 bytes
It's too short, sorry. I did my best.
x=-1
puts gets.scan(/\d+\D/).map{|i|i.to_i*(i[-1]=~/[WS]/?-1:1)}.zip(gets.scan(/\d+\D/).map{|i|i.to_i*(i[-1]=~/[WS]/?-1:1)}).map{|a,b|a+b}.map{|s|s.abs.to_s+%w"NNS EEW"[x+=1][s<=>0]}*' '

C - 267 bytes
I though C would be long... might as well just put it up. ;_;
#include <stdio.h>
#include <stdlib.h>
int main(){int x,y,z,w;char m,n,o,p;scanf("%d%c %d%c",&x,&m,&y,&n);scanf("%d%c %d%c",&z,&o,&w,&p);int a=x*(m<'O'?1:-1)+z*(o<'O'?1:-1),b=y*(n<'F'?1:-1)+w*(p<'F'?1:-1);printf("%d%c %d%c\n",abs(a),a<0?'S':'N',abs(b),b<0?'W':'E');}

Befunge-93, 240 bytes
v
  v$      <
>&>~:" "-!|
vp01p02   <
  v$      <
>&>~:" "-!|
vp03p04   <
  v$      <
>&>~:" "-!|
vp05p06   <
  v$      <
>&>~:" "-!|
 vp07p08  <
v>30g70g40g80g-!
_-:0` v1+
\v\g04_01-*80g
v>10g50g20g60g-!
_-:0` v1+
\v\g02_01-*60g
@>.," ",.,

Note that the interpreter has a single line input box. Pasting the preferred format replaces the newline with a space. Getting integer values with & already consumes leading spaces and zeros, so the preferred format can be read to the stack with &~&~&~&~ alone. Adding steps to put the values in a blank line so that one can retrieve and compare the vectors one coordinate at a time, the following 136 byte program (excluding  notes right of line) can be used:
v                      | blank line to store data
> &10p~20p&30p~40pv    | read and store first vector
 vp08~p07&p06~p05&<    | (backwards) read and store second vector
v>30g70g40g80g-!       | load E/W coordinates
_-:0` v1+              | subtract or add (based on direction)
\v\g04_01-*80g         | change directions if negative
v>10g50g20g60g-!       | load N/S coordinates
_-:0` v1+              | subtract or add (based on direction)
\v\g02_01-*60g         | change directions if negative
@>.," ",.,             | output

The Catch: The output forces an additional space after integers, so it is impossible to output in the preferred format. For example, output will appears as 1000 N 9999 W instead of 1000N 9999W. To check for and ignore spaces before each coordinate's direction on input, four additional loops (one for each coordinate) are needed. A single loop is shown below:
  v$      <            | throw out " " and repeat
>&>~:" "-!|            | (start read number) get and check character
vp01p02   <            | store

The resulting program can have multiple spaces anywhere in the input (except between digits).
Example Input: 0001   N   4545   W   0999   N   5454   W

Perl 6, 130 bytes
my (\h,\v)=[Z+] lines».split(' ')».map: {m/(.*)(.)/;$1 eq'S'|'W'??-$0!!$0}
say "{abs h}{h <0??'S'!!'N'} {abs v}{v <0??'W'!!'E'}"

Lua, 333 328 bytes
Features high-level invalid input system and absolutely innovative infinite loop for repeated use.
m=math.abs p=print::e::c={}for i=1,2 do for s in io.read():gmatch'%S+'do c[#c+1]=s end end for i=1,4 do n=c[i]:sub(1,-2)d=c[i]:sub(-1,-1)c[i]=d==("N"or"E")and n or-n end x=c[2]+c[4]y=c[1]+c[3]a=m(x)b=m(y)if(a or b)>9999 then p'Invalid input\n'goto e end x=x<0 and a.."W"or a.."E"y=y<0 and b.."S"or b.."N"p(y.." "..x.."\n")goto e

Enjoy ;)
Edit: saved 5 bytes from renaming math.abs as m and print as p

PHP, 169 bytes
Inspired by @Paul Drewett:
<?for($i=2;$i--;$e+=$p[1]*(substr($p[1],-1,1)<W?:-1))$n+=($p=explode(' ',trim(fgets(STDIN))))[0]*(substr($p[0],-1)<S?:-1);echo abs($n),'NS'[$n<0],' ',abs($e),'EW'[$e<0];

breakdown
for($i=2;$i--;                                  // loop twice
    $e+=$p[1]*(substr($p[1],-1,1)<W?:-1)        // add longitude to result
)
    $n+=
        ($p=explode(' ',trim(fgets(STDIN))))    // read line, split at blank
    [0]*(substr($p[0],-1)<S?:-1)                // add latitude to result
    ;
echo abs($n),'NS'[$n<0],' ',abs($e),'EW'[$e<0]; // print result

PHP, 206 197 195 bytes
literally speaking, "moste verbose" would probably be Mathematica or Mathlab?
<?function i(){preg_match('#\d+(.) (\d+)(.)#',fgets(STDIN),$m);return[$m[0]*($m[1]<S?:-1),$m[2]*($m[3]<W?:-1)];}echo abs($v=($a=i())[0]+($b=i())[0]),'NS'[$v<0],' ',abs($v=$a[1]+$b[1]),'EW'[$v<0];

output is pretty unformatted, not even a trainling newline
prints large numbers for too large result

Now, how can I double the size of this ...
breakdown
function i()
// read a pair of coordinates from STDIN, return signed values
{
    // read line from STDIN and take (number,character,number,character) from it
    // will produce something like ["111N 222E","N","222","E"]
    preg_match('#\d+(.) (\d+)(.)#',fgets(STDIN),$m);
    return[
        // using a numerical operation on $m[0] casts the string to number (int in this case)
        $m[0]*($m[1]<S?:-1) // convert latitude to signed int: multiply with -1 for $m[1]=='S'
        ,
        $m[2]*($m[3]<W?:-1) // convert longitude to signed int
    ];
}
$a=i();$b=i();  // read coordinates from STDIN
echo            // output:
    abs($v=$a[0]+$b[0])     // 1. unsigned sum of latitudes
    ,'NS'[$v<0]             // 2. direction depending on sign
    ,' ',                   // 3. delimiter
    abs($v=$a[1]+$b[1]),    // 4. unsigned sum of longitudes
    'EW'[$v<0]              // 5. direction depending on sign
;

PHP 291 Bytes.
<?php $E=0;$N=0;$l=explode(PHP_EOL,STDIN);foreach($l as $i){ $x=explode(' ',$i); $s=(substr($x[0],-1,1)=='N')?1:-1; $N=$N+((substr($x[0],0,-1)*$s));$s=(substr($x[1],-1,1)=='E')?1:-1;$E=$E+((substr($x[1],0,-1))*$s);}$l=($E<=0)?'W':'E';$u=($N<=0)?'S':'N';echo'
'.abs($N).$u.' '.abs($E).$l;

Does not do anything clever, just plods through the problem.
<?php
$lines = explode(PHP_EOL, STDIN);
foreach ($lines as $line) {
    $bits = explode(' ', $line);
    $sign = (substr($bits[0],-1, 1) == 'N')? 1 : -1;
    $N = $N + ( (substr($bits[0],0,-1) * $sign) );
    $sign = (substr($bits[1],-1, 1) == 'E')? 1 : -1;
    $E = $E + ( (substr($bits[1],0,-1)) * $sign );
}
$side = ($E<=0)?'W':'E';
$up = ($N<=0)?'S':'N';
echo '
'.abs($N).$up.' '.abs($E).$side;

The rules should have an additional clause saying only the language with at least 2 entries can win.

I count 291. But your breakdown can be golfed down to 205. Nice approach.

:-( You are quite right. Must have been a late night.

but thanks for the inspiration.

GolfScript - 111 bytes
{~)}:"S":"E";{}:"N":"W";"
"/~[{' '/[{.-1<~\-1>`~}/]\}2*]zip[{{+}*}/](.0<{abs'S'}{'N'}if' '+@~.0<{abs'E'}{'W'}if

Explanation
{~)}:"S":"E";    # Aliases these as *-1
{}:"N":"W";      # Alieses to nop
"\n"/~           # Splits lines
[{' '/[{.-1<~\-1>`~}/]\}2*]zip    # Parses the input as vectors and applies the aliases
[{{+}*}/]                         # Vector sum
(.0<{abs'S'}{'N'}if' '+@          # Formats output
~.0<{abs'E'}{'W'}if

Python 2.7 - 232 175 bytes
Works for all of the test cases. Always inserts N or W for 0. I'm sure a better Python golfer than me could shave a good few more bytes off.
f=(raw_input().split(" ")+raw_input().split(" "))
for x in range(4):
 i=f[x]
 if "S" in i or "E" in i:i="-"+i
 f[x]=int(i[:-1])
n=f[0]+f[2]
q=f[1]+f[3]
print str(abs(n))+("S" if n<0 else "N"),str(abs(q))+("E" if q<0 else "W")

EDIT
Golfed off a mighty 57 bytes due to some great tips from @mbomb007 and @Titus plus by spotting the fact that I could combine the two raw_inputs with a space then just use one .split() which splits on the space without specifying it. The algorithm is the same but just much better golfed.
f=(raw_input()+" "+raw_input()).split()
for x in 0,1,2,3:
 i=f[x]
 if i[-1]in"SE":i="-"+i
 f[x]=int(i[:-1])
n=f[0]+f[2]
q=f[1]+f[3]
print`abs(n)`+"NS"[n<0],`abs(q)`+"WE"[q<0]

replace ...str(x)... with ...`x`...; replace ("E" if q<0 else "W") with "WE"[q<0]

This should get you started. See the Python tips page

Thanks @mbomb007. Much appreciated. Will check out the tips page and see what else I can do.

https://repl.it/DRWh

"S" in i or "E" in i can surely be written i in "ES" or similar.

@Titus - I think i [-1] in "SE" should do it. Thanks. I'll give it a try later.

Thanks guys. I think that's about the best I can do on this one.


text:
Tiling by substitution
EDIT: The incorrect A rhomb substitution has been fixed. Apologies to anoyone who had started working on a solution.
Consider the following substitutions, where the substituted rhomb(us) is scaled up and shown in red:
EDIT: Note the anchor points (circle) created where a corner of each new rhomb touches the substituted rhomb. Also note the substitution's anchor point (black circle).
A rhomb (144°, 36°)

... becomes ...

B rhomb (72°, 108°)

 ... becomes ...

Each substitution is made up of some combination of A rhombs and B rhombs, on which the same substitutions can be performed.
A tiling can be created by repeating the substitutions n times.
After n=2 substitutions of A rhomb:
EDIT: The substitution is oriented by aligning the rhomb's anchor point with the substitution's anchor point

In the fewest bytes of code (given input n>=0) draw the tiling after n substitutions, where n=0 is A rhomb

Notes:

The red lines and anchor points shouldn't be included, they only illustrate the substitution.
In each substitution the tiling is scaled up so the rhombs have a constant size.
Any rotation is optional.
Graphical choices (colour, dimensions, cropping etc.) are optional if not exploited for loopholes.

Doesn't this require us to pay royalties to Roger Penrose?

very possibly, though as I understand it this isn't properly a Penrose tiling

Please provide the exact angles and dimensions.

@flawr angles provided. each rhomb side is 1 unit, exact pixel dimensions are up to you

The substitution for A does not match the n=2 example for the second level of substitution, no? In the substitution, two A rhombi are attached to a corner. In your example, one B rhombus is attached to a corner.

Also it would be very helpful to know where the "origins" for the substitutions are, otherwise you're pretty much left playing the guessing game. My solution works for n=2 now, but I'm still getting wrongly rotated substitutions for n=3

@Marv that's a mistake, I can't fix it yet but the substitution shown in n=2 is correct (one b rhomb attached to corner). sorry about this!

@Marv and regarding origins: when you perform a substitution each rhomb created has an anchor point where it touches a corner of the substituted rhomb. the next substitution is anchored to that point as seen in n=2. I'll make it clearer in an edit later

@jsh Great edit, that clears things up.

@jsh You should probably swap the angles for the B rhomb now since A is anchored at the first angle listed but B at the second.

Java, 881 bytes
import java.awt.image.BufferedImage;import static java.lang.Math.*;class J{BufferedImage o=new BufferedImage(999,999,1);java.awt.Graphics g=o.getGraphics();double v=2.5132,w=1.2566,p=PI,s=(p-v)/2,u=(p+w)/2;public static void main(String[]v){new J(Integer.parseInt(v[0]));}J(int i){d(609,391,v,p/4+s,500,i);try{javax.imageio.ImageIO.write(o,"png",new java.io.File("a.png"));}catch(Exception e){}}void d(int x,int y,double o,double q,double l,int r){int m=(int)(2*l*sin((p-o)/2)),a=(int)(x+cos(q)*l),b=(int)(y+sin(q)*l),c=(int)(x+cos(q+o/2)*m),d=(int)(y+sin(q+o/2)*m),e=(int)(x+cos(q+o)*l),f=(int)(y+sin(q+o)*l);if(r-->0){double n=l/(2*sin((v)/2));if(o>w){d(x,y,v,q-s,n,r);d(c,d,v,q+p+s,n,r);d(a,b,w,q+u,n,r);}else{d(x,y,w,q-s,n,r);d(c,d,w,q+p+s,n,r);d(e,f,w,q-p/2,n,r);d(a,b,v,q+p/2-s-s,n,r);}}else{g.drawLine(x,y,a,b);g.drawLine(a,b,c,d);g.drawLine(x,y,e,f);g.drawLine(c,d,e,f);}}}

Ungolfed
import java.awt.image.BufferedImage;

import static java.lang.Math.*;

class Q79373 {
    BufferedImage image = new BufferedImage(999, 999, 1);
    java.awt.Graphics graphics = image.getGraphics();
    double aRad = 2.5132, bRad = 1.2566, pi = PI, aAcuteHalf = (pi - aRad) / 2, bRadHalfPi = (pi + bRad) / 2;

    public static void main(String[] v) {
        new Q79373(Integer.parseInt(v[0]));
    }

    Q79373(int i) {
        draw(609, 391, aRad, pi / 4 + aAcuteHalf, 500, i);
        try {
            javax.imageio.ImageIO.write(image, "png", new java.io.File("a.png"));
        } catch (Exception e) {
        }
    }

    void draw(int x, int y, double rad, double rot, double length, int recDepth) {
        int
                height = (int) (2 * length * sin((pi - rad) / 2)),
                a = (int) (x + cos(rot) * length),
                b = (int) (y + sin(rot) * length),
                c = (int) (x + cos(rot + rad / 2) * height),
                d = (int) (y + sin(rot + rad / 2) * height),
                e = (int) (x + cos(rot + rad) * length),
                f = (int) (y + sin(rot + rad) * length);

        if (recDepth-- > 0) {
            double lengthNew = length / (2 * sin((aRad) / 2));
            if (rad > bRad) {
                draw(x, y, aRad, rot - aAcuteHalf, lengthNew, recDepth);
                draw(c, d, aRad, rot + pi + aAcuteHalf, lengthNew, recDepth);
                draw(a, b, bRad, rot + bRadHalfPi, lengthNew, recDepth);
            } else {
                draw(x, y, bRad, rot - aAcuteHalf, lengthNew, recDepth);
                draw(c, d, bRad, rot + pi + aAcuteHalf, lengthNew, recDepth);
                draw(e, f, bRad, rot - pi / 2, lengthNew, recDepth);
                draw(a, b, aRad, rot + pi / 2 - aAcuteHalf - aAcuteHalf, lengthNew, recDepth);
            }
        } else {
            graphics.drawLine(x, y, a, b);
            graphics.drawLine(a, b, c, d);
            graphics.drawLine(x, y, e, f);
            graphics.drawLine(c, d, e, f);
        }
    }
}

Notes

The results arent 100% acurate thanks to integer precision. I used integers for the coordinates because Graphics::drawLine only takes integers as arguments, and I would've ended up with way more integer casts than I have now.
I'll probably golf a bit more later, still not optimal.

Results
Full image filled

Recursion 1

Recursion 2

Recursion 3

+1 but to fully meet the spec rhombs should have a constant size between recursions

@jsh Oh gotcha, I'll change that later.

@jsh now I'm wondering if my solution is even correct. Penrose tilings on wikipedia have those neat stars all over, however I'm not getting those.

this isn't a Penrose tiling though. I think your solution is correct