Find the generating function of a sequence

Python 256 bytes

a=raw_input().split();r=range(len(a));m=[[(i+1.)**p for p in r]+[int(a[i])]for i in r]
for j in r:s=m[j];m=[map(lambda a,b:a-b*(i[j]-(i==s))/s[j],i,s)for i in m]
while~j:
 c=m[j][-1]
 if c:print('%+.15g'%c)[s>c>0:j>=c*c==1or 18]+('x^%d'%j)[:j*j],;s=0
 j-=1

Sets up a system of linear equations, matrix style, and then uses Gaussian elimination to solve. Quite a few bytes are spent pretty-printing the output. Non-integer solutions are displayed to 15 digits of accuracy.

As every sequence of n real numbers can be generated by a polynomial of order no more than n-1, the "function does not exist" case is not handled.

Sample usage:

$ echo 1 11 41 79 | python find-poly.py
-2x^3 +22x^2 -42x +23

$ echo 1 11 35 79 | python find-poly.py
x^3 +x^2 -1

$ echo 12 38 78 | python find-poly.py
7x^2 +5x

$ echo 43 12 -5 19 57 | python find-poly.py
-2.25x^4 +27x^3 -98.75x^2 +110x +7


Operation Flashpoint scripting language,  174  171 bytes

s=""
#l
t=_time
t=t-t%1
a=t%60
c=(t-a)/60
b=c%60
c=(c-b)/60
d=""
e=d
f=d
?a<10:d=0
?b<10:e=0
?c<10:f=0
s=s+format["%1%2:%3%4:%5%6\n",f,c,e,b,d,a]
hint s
@t+1<_time
goto"l"

In action:

158 bytes, if the previous time is overwritten by the next time:

#l
t=_time
t=t-t%1
a=t%60
c=(t-a)/60
b=c%60
c=(c-b)/60
d=""
e=d
f=d
?a<10:d=0
?b<10:e=0
?c<10:f=0
hint format["%1%2:%3%4:%5%6",f,c,e,b,d,a]
@t+1<_time
goto"l"

Technically, no carriage return is used, so I'm not sure if this version confines to the rules.


Python, 103

I hate sudoku.

b = [[1,2,3,4,5,6,7,8,9],
     [4,5,6,7,8,9,1,2,3],
     [7,8,9,1,2,3,4,5,6],
     [2,3,1,5,6,4,8,9,7],
     [5,6,4,8,9,7,2,3,1],
     [8,9,7,2,3,1,5,6,4],
     [3,1,2,6,4,5,9,7,8],
     [6,4,5,9,7,8,3,1,2],
     [9,7,8,3,1,2,6,4,5]]

e=enumerate;print 243-len(set((a,t)for(i,r)in e(b)for(j,t)in e(r)for a in e([i,j,i/3*3+j/3]*(0<t<10))))

How it works: each row, column, and block must have each number from 1 to 9.  So for each 0 <= i, j < 9, the cell i,j is in block 3*floor(i/3) + floor(j/3).  Thus, there are 243 requirements to satisfy.  I make each requirement a tuple ((item index,item type number),symbol) where item index is a number between 0 and 8 (inclusive), item type number is 0,1, or 2 to denote row, column or block respectively, and symbol is the entry b[i][j].

Edit: I mistakenly didn't check for valid entries.  Now I do.


Python 2, 55 bytes

i=2
exec"print(i%2*' '+`2%i*1122`*i)[:i];i+=1;"*input()

Try it online!

Cycles between blocks of 22, 44, except the top row is 00. For example, on input 10, prints

00
 22
2244
 2244
224422
 224422
22442244
 22442244
2244224422
 2244224422

Prints rows of increasing length i=2,3,.. by creating a space for odd lengths, repeating the pattern i times, and trunctating to length i. The pattern is 2244 for all rows except the first one i=2 for which it's 0. This is achieved with the arithmetic expression 2%i*1122.


Can this value be made with unique coins and/or notes?

Brachylog 2 (TIO Nexus), 2 bytes

⊇+

Try it online!

Takes the list of coins either via standard input or via prepending it to the start of the program as an array literal (either will work, so it's up to you as to which you feel is "more legitimate"; the former is allowed by default PPCG rules, the latter specifically allowed by the question); and takes the value to produce as a command-line argument.

Explanation

This program makes use of implementation details of the way TIO Nexus's wrapper for Brachylog functions; specifically, it lets you give a command-line argument to give input via the Output. (This wasn't envisaged in the original design for Brachylog; however, languages are defined by their implementation on PPCG, and if an implementation comes along that happens to do what I need, I can therefore take advantage of it.) That means the program looks like this:

⊇+
⊇   Some subset of {standard input}
 +  sums to {the first command-line argument}

As a full program, it returns a boolean value; true. if all the assertions in the program can be simultaneously satisfied, or false. if they can't be.

(A reminder, or for people who don't already know: Brachylog 2 uses its own character encoding in which ⊇ is a single byte long.)


Python, 60 bytes

f=lambda n,k:n>1<k and f(n,k-1)+f(n-1,k)or'987654321\n'[~n:]

Test it on Ideone.

How it works

The k-dimensional countdown from n can be defined with a single base case:

  If n = 1 or k = 1, the output is n || n-1 || ... || 1 || ¶, where || indicates concatenation.

Using the recursive definition from the question, f(n,k) returns f(n,k-1)+f(n-1,k) if n > 1 and k > 1; otherwise it returns the last n + 1 characters from '987654321\n'.


k (72 bytes)

Credit for this goes to Arthur Whitney, creator of the k language.

p,:3/:_(p:9\:!81)%3
s:{*(,x)(,/{@[x;y;:;]'&21=x[&|/p[;y]=p]?!10}')/&~x}


Translate English Characters to the Emoji Flag Alphabet

Pyth - 18 16 bytes
Supports lowercase.
XzGsCMrF+BC\26

Test Suite.


Jelly,  21  20 bytes
Probably beatable by a number of bytes using some clever mathematics...
:g/
ÇµSRRUĖ€UÐeẎÇ€Qi

A monadic link accepting a list of [p,q] which returns the natural number assigned to p/q.
Try it online! Or see the test-suite.
How?
First note that the Nth diagonal encountered contains all of the grid's rational numbers for which the sum of the numerator and denominator equals N+1, so given a function which reduces a [p,q] pair to simplest form ([p/gcd(p,q),q/gcd(p,q)]) we can build the diagonals as far as need be*, reduce all the entries, de-duplicate and find the index of the simplified input.
* actually one further here to save a byte
:g/ - Link 1, simplify a pair: list of integers, [a, b]
  / - reduce using:
 g  - Greatest Common Divisor -> gcd(a, b)
:   - integer division (vectorises) -> [a/gcd(a,b), b/gcd(a,b)]

ÇµSRRUĖ€UÐeẎÇ€Qi - Main Link: list of integers, [p, q]
Ç                - call last Link as a monad (simplify)
 µ               - start a new monadic chain (call that V)
  S              - sum -> the diagonal V will be in plus one
   R             - range -> [1,2,3,...,diag(V)+1]
    R            - range (vectorises) -> [[1],[1,2],[1,2,3],...,[1,2,3,...,diag(V)+1]]
     U           - reverse each       -> [[1],[2,1],[3,2,1],[diag(V)+1,...,3,2,1]]
      Ė€         - enumerate €ach     -> [[[1,1]],[[1,2],[2,1]],[[1,3],[2,2],[3,1]],[[1,diag(V)+1],...,[diag(V)-1,3],[diag(V),2],[diag(V)+1,1]]]
         Ðe      - apply only to the even indexed items:
        U        -   reverse each     -> [[[1,1]],[[2,1],[1,2]],[[1,3],[2,2],[3,1]],[[4,1],[3,2],[2,3],[1,4]],...]
           Ẏ     - tighten            -> [[1,1],[2,1],[1,2],[1,3],[2,2],[3,1],[4,1],[3,2],[2,3],[1,4],...]
            Ç€   - for €ach: call last Link as a monad (simplify each)
                 -                    -> [[1,1],[2,1],[1,2],[1,3],[1,1],[3,1],[4,1],[3,2],[2,3],[1,4],...]
              Q  - de-duplicate       -> [[1,1],[2,1],[1,2],[1,3],[3,1],[4,1],[3,2],[2,3],[1,4],...]
               i - index of V in that list


Retina, 5 bytes

.*\.

Replaces everything and a dot with nothing at all.

Try it online!


APL (Dyalog Extended), 23 bytes

-4 thanks to ovs.
Anonymous tacit infix function, taking coordinates of a cell and radius as left and right arguments. Requires 0-based indexing.
{⍺∘+¨⍵-⍸⍵≥+/¨|∘.,⍨⍵…-⍵}

Try it online!
{…} "dfn"; left argument is ⍺ and right argument is ⍵:
 ⍵…-⍵ inclusive integer range from radius to negative radius
 ∘.,⍨ Cartesian selfie product
 ⊢m← assign to m and pass that
 | absolute values
 +/¨ sum each (gives matrix of Manhattan distances)
 ⍵≥ indicate which ones are less than or equal to the radius
 ⍸ ɩndices where true
 ⍵- subtract from radius
 ⍺∘+¨ add the cell coordinates to each


Solve a mathematical expression from alternating sides


MATL, 33 bytes
,it7#utb,&S]2XQw)]-Us6*1GntUq*/_Q

Try it online!
Explanation
,           % Do...twice
  it        %   Input a numeric vector. Duplicate
  7#u       %   Replace each element by a unique integer label (1, 2, ...)
  t         %   Duplicate
  b         %   Bubble up: moves original numeric vector to top
  ,         %   Do...twice
    &S      %     Sort and push the indices of the sorting
  ]         %   End
            %   The above do...twice loop gives the sorted indices (as
            %   explained in the challenge text) for the current input
  2XQ       %   Compute average for entries with the same integer label
  w         %   Swap: move vector of integer labels to top
  )         %   Index. This gives the rank vector for the current input
]           % End
-           % Subtract the two results. Gives d
Us          % Square each entry, sum of vector. S
6*          % Times 6. Gives 6*S
1G          % Push first input vector again
n           % Number of entries. Gives n
t           % Duplicate
Uq          % Square, minus 1. Gives n^2-1
*           % Times. Gives n*(n^2-1)
/           % Divide. Gives 6*S/(n*(n^2-1))
_Q          % Negate, plus 1. Gives 1-6*S/(n*(n^2-1))


Python 2, 45 - 4 - 4 = 37

a=1;b=0
exec"a,b=b,34*b-a+2;"*input()
print a

Iterates using the reccurence

f(0) = 1
f(1) = 0
f(k) = 34*f(k-1)-f(k-2)+2

In theory, this supports numbers of any size, but runs in exponential time, so it shouldn't qualify for the bonuses. Should work for numbers of any size. For example, for 100, gives

1185827220993342542557325920096705939276583904852110550753333094088280194260929920844987597980616456388639477930416411849864965254621398934978872054025

A recursive solution uses 41 chars, but shouldn't qualify because it takes exponential time.

f=lambda k:k>2and 34*f(k-1)-f(k-2)+2or~-k


Prisoner's Dilemma with access to opponent

BoomBot

function boom(them) {
  throw 1;
}

If the opponent is run first and calls this without try..catch, this bot automatically wins 3 points. Zero points in any other case.


Seriously, 245 bytes:

All ten programs concatenated:

Q9ucQc8<WX#dXεj0WX.Q9ucQc8<WX#dXεj0WX.
Q9ucQc8<WX#dXεj0WX.

Q9ucQc8<WX#dXεj0WX.

Q9ucQc8<WX#dXεj0WX.

Q9ucQc8<WX#dXεj0WX.

Q9ucQc8<WX#dXεj0WX.

Q9ucQc8<WX#dXεj0WX.

Q9ucQc8<WX#dXεj0WX.

Q9ucQc8<WX#dXεj0WX.

There are invisible characters that become visible when executed, a strange property of byte 7F. The trailing newlines on each program are significant. In fact, Seriously automatically appends newlines to its output whether you want it to or not. This just counts the number of newlines in the output, and as soon as that number exceeds 8, it deletes the last character of output. As such, p1..pK will print p1..pK for all K>4.

Q                                  Push source code.
 9uc                               Push \n
    Qc                             Push the number of times it appears in source code.
      8<                           Check if it appears more than 8 times.
        WX     0WX                 If so, run the included code.
          #dX                      Convert string to list, dequeue and discard a newline.
             εj                    Join list back into string.
                  .                Print and halt. (Invisible byte here.)


Find the intersection point of a plane and ray

Perl, 107 bytes

Tested for all test cases (i.e. not tested at all)
Run with each input number on its own line on STDIN

perl -M5.010 plane.pl
0
1
0
0
0
1
3
3
1
0
0
1
^D

plane.pl:

#!/usr/bin/perl
$$_=<>for a..l;say$a+($t=($j*($g-$a)+$k*($h-$b)+$l*($i-$c))/($j*$d+$k*$e+$l*$f))*$d,$",$b+$t*$e,$",$c+$t*$f

This kind of problem is absolutely not a good match for perlgolf. Perl lacks vector operations and uses too many $s


Challenge: compress co-occuring columns into cartesian product

I'll start things off with the simplest possible answer.. According to my own specifications, the input file qualifies as a 'compression' of itself (albeit not a very efficient one).

Python: 22+3359+183735+239 with 10% bonus = 168619.5

print open('testfile').read()


Change the Code, Change the Sequence: Cops

Brain-Flak, 28 bytes, Distance of 4, A002817, A090809 Cracked
This answer uses 1-indexing
(({({}[()])}{}){({}[()])}{})

Try it online
For anyone interested there are 27475 valid Brain-Flak programs with Levenshtein distance 4 from this program and 27707 with distance 4 or less.  So a brute force solution would be feasible on a consumer grade computer.


Snails, 14 bytes

&
o.,\Q!(z.,\Q

Try it online!

Nothing like a 2D pattern matching language for a 2D decision problem. :)

Explanation

The & on the first line is a match mode option which requires the pattern on the second line to match from every possible position in the input. If that's the case, the program prints 1, otherwise it prints 0.

As for the pattern itself, note that there's an implicit ) at the end.

o       ,, Move in any orthogonal direction (up, down, left or right).
.,\Q    ,, Make sure that there's a Q somewhere in that direction from the
        ,, starting position of the match.
!(      ,, After finding the Q, make sure that the following part _doesn't_ match:
  z     ,,   Move in any orthogonal or diagonal direction.
  .,\Q  ,,   Try to find another Q in a straight line.
)

Why this works is easiest to see by starting from the negative lookahead: by ensuring that there is no Q in a straight line from the other Q we've already found, we make sure that there are no more than N queens (otherwise, there would have to be two in one row, and it wouldn't be possible to find these queens without finding another). Then the first part, making sure that there's a queen reachable in an orthogonal direction from any position, makes sure that there are exactly N queens. If one was missing, there would be a row and a column without a queen. Starting from the intersection of these, it wouldn't be possible to find a queen by going only in an orthogonal direction.


Find 10 large prime numbers with n digits


Write a program that is valid after circular character shift

Use the right language for the task. In this case, that's Befunge.

This language naturally allows rotations because:

All commands are a single character.
The control wraps around when it reaches the end of the program, starting again from the beginning.

This Befunge program prints the exact same output ("Hello") regardless of how many "circular character shifts" you use:

86*01p75*1-02p447**1-03p439**04p439**05p455**1+06p662**07p75*1-08p645**2-09p69*4+019+p57*029+p59*1-039+p555**1-049+p88*059+p86*01p75*1-02p447**1-03p439**04p439**05p455**1+06p662**07p75*1-08p645**2-09p69*4+019+p57*029+p59*1-039+p555**1-049+p88*059+p645**2-00p645**2-00p

It runs on Befungee. It requires that the board is increased (not the 80 character default). It can be run like this:

python befungee.py -w400 hello.bef

It works by first dynamically generating and storing a program that prints "Hello" and then overwriting the first byte to redirect the control into the newly written program. The program is written twice so that if a byte is not written correctly the first time, it will be corrected the second time.

The idea could be extended to produce any program of arbitrary complexity.


Python, 644

A simple recursive equation generator.  S generates an equation that is satisfied iff the list of vars adds up to total.

There are some obvious improvements to be done.  For instance, there are a lot of common subexpressions that appear in the 15/5 output.

def S(vars, total):
    # base case
    if total == 0:
        return "(" + " and ".join("not " + x for x in vars) + ")"
    if total == len(vars):
        return "(" + " and ".join(vars) + ")"

    # recursive case
    n = len(vars)/2
    clauses = []
    for s in xrange(total+1):
        if s > n or total-s > len(vars)-n: continue
        a = S(vars[:n], s)
        b = S(vars[n:], total-s)
        clauses += ["(" + a + " and " + b + ")"]
    return "(" + " or ".join(clauses) + ")"

def T(n, total):
    e = S(["x[%d]"%i for i in xrange(n)], total)
    print "equation", e
    print "score", e.count("[")

    # test it
    for i in xrange(2**n):
        x = [i/2**k%2 for k in xrange(n)]
        if eval(e) != (sum(x) == total):
            print "wrong", x

T(2, 1)
T(5, 2)
T(15, 5)

Generates:

equation (((not x[0]) and (x[1])) or ((x[0]) and (not x[1])))
score 4
equation (((not x[0] and not x[1]) and (((not x[2]) and (x[3] and x[4])) or ((x[2]) and (((not x[3]) and (x[4])) or ((x[3]) and (not x[4])))))) or ((((not x[0]) and (x[1])) or ((x[0]) and (not x[1]))) and (((not x[2]) and (((not x[3]) and (x[4])) or ((x[3]) and (not x[4])))) or ((x[2]) and (not x[3] and not x[4])))) or ((x[0] and x[1]) and (not x[2] and not x[3] and not x[4])))
score 27
equation (((not x[0] and not x[1] and not x[2] and not x[3] and not x[4] and not x[5] and not x[6]) and (((((not x[7] and not x[8]) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (not x[9] and not x[10]))) and (x[11] and x[12] and x[13] and x[14])) or ((((not x[7] and not x[8]) and (x[9] and x[10])) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((x[7] and x[8]) and (not x[9] and not x[10]))) and (((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (x[13] and x[14])) or ((x[11] and x[12]) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))))) or ((((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (x[9] and x[10])) or ((x[7] and x[8]) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10]))))) and (((not x[11] and not x[12]) and (x[13] and x[14])) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((x[11] and x[12]) and (not x[13] and not x[14])))) or ((x[7] and x[8] and x[9] and x[10]) and (((not x[11] and not x[12]) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (not x[13] and not x[14])))))) or ((((not x[0] and not x[1] and not x[2]) and (((not x[3] and not x[4]) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))) or ((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (not x[5] and not x[6])))) or ((((not x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2])))) or ((x[0]) and (not x[1] and not x[2]))) and (not x[3] and not x[4] and not x[5] and not x[6]))) and (((not x[7] and not x[8] and not x[9] and not x[10]) and (x[11] and x[12] and x[13] and x[14])) or ((((not x[7] and not x[8]) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (not x[9] and not x[10]))) and (((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (x[13] and x[14])) or ((x[11] and x[12]) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))))) or ((((not x[7] and not x[8]) and (x[9] and x[10])) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((x[7] and x[8]) and (not x[9] and not x[10]))) and (((not x[11] and not x[12]) and (x[13] and x[14])) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((x[11] and x[12]) and (not x[13] and not x[14])))) or ((((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (x[9] and x[10])) or ((x[7] and x[8]) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10]))))) and (((not x[11] and not x[12]) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (not x[13] and not x[14])))) or ((x[7] and x[8] and x[9] and x[10]) and (not x[11] and not x[12] and not x[13] and not x[14])))) or ((((not x[0] and not x[1] and not x[2]) and (((not x[3] and not x[4]) and (x[5] and x[6])) or ((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))) or ((x[3] and x[4]) and (not x[5] and not x[6])))) or ((((not x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2])))) or ((x[0]) and (not x[1] and not x[2]))) and (((not x[3] and not x[4]) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))) or ((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (not x[5] and not x[6])))) or ((((not x[0]) and (x[1] and x[2])) or ((x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2]))))) and (not x[3] and not x[4] and not x[5] and not x[6]))) and (((not x[7] and not x[8] and not x[9] and not x[10]) and (((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (x[13] and x[14])) or ((x[11] and x[12]) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))))) or ((((not x[7] and not x[8]) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (not x[9] and not x[10]))) and (((not x[11] and not x[12]) and (x[13] and x[14])) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((x[11] and x[12]) and (not x[13] and not x[14])))) or ((((not x[7] and not x[8]) and (x[9] and x[10])) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((x[7] and x[8]) and (not x[9] and not x[10]))) and (((not x[11] and not x[12]) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (not x[13] and not x[14])))) or ((((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (x[9] and x[10])) or ((x[7] and x[8]) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10]))))) and (not x[11] and not x[12] and not x[13] and not x[14])))) or ((((not x[0] and not x[1] and not x[2]) and (((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (x[5] and x[6])) or ((x[3] and x[4]) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))))) or ((((not x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2])))) or ((x[0]) and (not x[1] and not x[2]))) and (((not x[3] and not x[4]) and (x[5] and x[6])) or ((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))) or ((x[3] and x[4]) and (not x[5] and not x[6])))) or ((((not x[0]) and (x[1] and x[2])) or ((x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2]))))) and (((not x[3] and not x[4]) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))) or ((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (not x[5] and not x[6])))) or ((x[0] and x[1] and x[2]) and (not x[3] and not x[4] and not x[5] and not x[6]))) and (((not x[7] and not x[8] and not x[9] and not x[10]) and (((not x[11] and not x[12]) and (x[13] and x[14])) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((x[11] and x[12]) and (not x[13] and not x[14])))) or ((((not x[7] and not x[8]) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (not x[9] and not x[10]))) and (((not x[11] and not x[12]) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (not x[13] and not x[14])))) or ((((not x[7] and not x[8]) and (x[9] and x[10])) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((x[7] and x[8]) and (not x[9] and not x[10]))) and (not x[11] and not x[12] and not x[13] and not x[14])))) or ((((not x[0] and not x[1] and not x[2]) and (x[3] and x[4] and x[5] and x[6])) or ((((not x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2])))) or ((x[0]) and (not x[1] and not x[2]))) and (((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (x[5] and x[6])) or ((x[3] and x[4]) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))))) or ((((not x[0]) and (x[1] and x[2])) or ((x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2]))))) and (((not x[3] and not x[4]) and (x[5] and x[6])) or ((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))) or ((x[3] and x[4]) and (not x[5] and not x[6])))) or ((x[0] and x[1] and x[2]) and (((not x[3] and not x[4]) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))) or ((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (not x[5] and not x[6]))))) and (((not x[7] and not x[8] and not x[9] and not x[10]) and (((not x[11] and not x[12]) and (((not x[13]) and (x[14])) or ((x[13]) and (not x[14])))) or ((((not x[11]) and (x[12])) or ((x[11]) and (not x[12]))) and (not x[13] and not x[14])))) or ((((not x[7] and not x[8]) and (((not x[9]) and (x[10])) or ((x[9]) and (not x[10])))) or ((((not x[7]) and (x[8])) or ((x[7]) and (not x[8]))) and (not x[9] and not x[10]))) and (not x[11] and not x[12] and not x[13] and not x[14])))) or ((((((not x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2])))) or ((x[0]) and (not x[1] and not x[2]))) and (x[3] and x[4] and x[5] and x[6])) or ((((not x[0]) and (x[1] and x[2])) or ((x[0]) and (((not x[1]) and (x[2])) or ((x[1]) and (not x[2]))))) and (((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (x[5] and x[6])) or ((x[3] and x[4]) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))))) or ((x[0] and x[1] and x[2]) and (((not x[3] and not x[4]) and (x[5] and x[6])) or ((((not x[3]) and (x[4])) or ((x[3]) and (not x[4]))) and (((not x[5]) and (x[6])) or ((x[5]) and (not x[6])))) or ((x[3] and x[4]) and (not x[5] and not x[6]))))) and (not x[7] and not x[8] and not x[9] and not x[10] and not x[11] and not x[12] and not x[13] and not x[14])))
score 644


Python 2, 104 bytes

c=lambda x:x>1and 1+c([x/2,x*3+1][x%2])
lambda n:[1]+[x for x in range(2,n)if c(x)>max(map(c,range(x)))]

c is a helper function that calculates the Collatz distance for a given integer. The unnamed lambda is the main function, which computes the super Collatz numbers up to (but not including) the input.


PHP - 22 bytes

<?=date('n.j',8899e5);

Pi Day in year 1998 was really cool!


Write an program that terminates after 60 seconds - Robbers Thread

Jelly, edit distance 5 from 30 bytes

Original:

69266249554160949116534784œSÆl

Crack:

69266249554160949116534784œSÆl_29$$

I just subtracted 29 from the timeout immediately before the œS runs. (_29 subtracts 29, the dollars control precedence, a bit like parentheses in other languages.)


Minimum number of transactions so everyone has paid the same

Python, 308 Characters

I chose not to go after the bonus because the last time I used VB was over a decade ago, and I am still suffering from the PTSD ;-)

I didn't try and golf this very much because I'm not sure if that's the goal.  This code is guaranteed to return a solution with the minimum number of transactions.

def t(p):
 a=sum(p)/float(len(p))
 q=[([],p)]
 l=len(p)
 r=range(l)
 while q:
  n=q.pop(0)
  g=1
  for i in r:
   d=n[1][i]-a
   if d>0:
    g=0
    for j in r:
     if n[1][j]<a:
      v=min(d,a-n[1][j])
      y=list(n[1])
      y[i]-=v
      y[j]+=v
      if i!=j:q+=[(n[0]+[(j,i,v)],y)]
  if g:return n[0]

Usage

The t function takes a list of the amounts that each person paid.  Using the example from the question:

> print t([50,25,5,0])
[(2, 0, 15.0), (3, 0, 15.0), (3, 1, 5.0)]

So the solution is for person 2 (George) to pay person 0 (Dave) $15 and for person 3 (Barry) to pay 0 (Dave) $15 and also to pay 1 (John) $5.


Japt, 6 bytes
¤é r0J

Try it online!
Explanation:
¤é r0J  // Test input:                  25
¤       // Binary the input:            11001
 é      // Rotate 1 chars to the right: 11100
   r0J  // Replace 0s with -1:          111-1-1


CJam (22 bytes)

1{_~$(~$-)~$)}A6#(/]S*

Online demo for only 15 terms

This relies on one of the formulae given in the entry for OEIS A001462, and the use of ~$ to index the stack from the bottom.


TyPe LiKe ThIs AnD iRrItAtE yOuR fRiEnDs

JavaScript, 116

s=>{x=!0;return s.split("").map(e=>{if(e.match(/[a-zA-Z]/))x=!x;return x?e.toUpperCase():e.toLowerCase()}).join("")}

Saved two bytes thanks to NTCG


Python 3, 115 bytes

def f(l):
 r={}
 for n,m in l:q=m*0!=0;r[[n,m][q]]=r.pop(n,0)+[m,0][q]
 return sorted(r.items(),key=lambda i:-i[1])

Try it online!


Haskell - 192 175
f y=sum.map(\x->length.fst$break(==x)y)
main=interact(\s->snd$minimum$[(f"etaoinshrdlcumwfgypbvkjxqz"r,show(26-n)++" "++r)|n<-[0..25],let r=map(\x->([x..'z']++['a'..])!!n)s])

Running
% ./rot-n <<< "pmttwxmwxtmwnxzwoziuuqvoxchhtmakwlmowtnabiksmfkpivom"
8 hellopeopleofprogrammingpuzzlescodegolfstackexchange


Pari/GP, 84 bytes
f(p)=[if(q'',[f(q),r],p)|r<-x*divisors(p\x),r''&&p==subst(q=substpol(p,r,x),x,r)][1]

Based on the algorithm described here.
Try it online!


Python 3, 74 bytes

def g(a,b,l):
 for x,y in l:
  if x<len(a)and y<len(b):a[x],b[y]=b[y],a[x]

Try it online!

Requires l to be sorted in lexicographical order. a and b are lists of characters representing (left ribbon, top ribbon).

Returns by modifying the list a and b.


Pure Bash (no external utils), 64

2 bytes saved thanks to @NahuelFouilleul

x={A..Z}
eval f=($x$x-%03d-$x$x)
printf ${f[$1/1000]} $[$1%1000]

Try it online! - takes about 10s to run over the 7 testcases.

Line #1 is a simple assignment of a string to a variable
Line #2 is a brace expansion to build an array of printf format strings, one for all 456,976 possible letter combinations, with the digits not yet specified.  The eval is required to ensure variable expansion (of x) occurs before brace expansion.
Line #3 indexes the array to get the appropriate format string and takes the digits portion as its parameter.


Ruby, 258 256 249 246+8 = 264 257 254 bytes

Uses the -rprime flag.

Geez, what a mess.

Uses this algorithm from stackoverflow.

->c{m=->x,y{x-y*eval("%d+%di"%(x/y).rect)};a=c.abs2.prime_division.flat_map{|b,e|b%4<2?(1..e).map{k=(2..d=b).find{|n|n**(~-b/2)%b==b-1}**(~-b/4)%b+1i;d,k=k,m[d,k]while k!=0;c/=d=m[c,d]==0?d:d.conj;d}:(c/=b<3?(b=1+1i)**e:b**e/=2;[b]*e)};a[0]*=c;a}

Try it online!


The Death Of Low-Resolution Pixel Art (Or, Draw That Death)


T-SQL (40)

SELECT RANK()OVER(ORDER BY B DESC)
FROM @

Assume @ is a table containing the scores as rows.


When was the last time the date was divisible by n?

Mathematica, 93 60 bytes

For[i=0,(r=DatePlus@i--~FromDigits~100)>0&&!n∣r,];r~Max~-1

Expects the input to be stored in n.

Note that the vertical line ∣ is the unicode character for "divides", which I've counted as 3 bytes (UTF-8).

Edit: Found a neat trick to avoid the bloated DateString and format specification :).

Edit: Totally forgot about the -1 requirement. Fixed now.

Here is an explanation

For[i=0,            i--                        ,];         (* i is the number of days AFTER
                                                              today. Hence, we decrement
                                                              it. *)
For[i=0,   DatePlus@i--                        ,];         (* If no reference date is
                                                              provided, DatePlus will add
                                                              the given number of days to
                                                              today's date. The result is a
                                                              list of 3 integers, luckily
                                                              in order {year,month,day} *)
For[i=0,   DatePlus@i--~FromDigits~100         ,];         (* Interpret these as the digits
                                                              of a base 100 number. The
                                                              beauty is that FromDigits
                                                              doesn't care about digits
                                                              greater than the base and
                                                              just carries them over. *)
For[i=0,(r=DatePlus@i--~FromDigits~100)        ,];         (* Store the number in r. *)
For[i=0,(r=DatePlus@i--~FromDigits~100)>0      ,];         (* Make sure it's positive. *)
For[i=0,(r=DatePlus@i--~FromDigits~100)>0&&!n|r,];         (* And keep going while n does
                                                              not divide r. *)
For[i=0,(r=DatePlus@i--~FromDigits~100)>0&&!n|r,];r~Max~-1 (* Clamp result to -1. *)

Note that I've used | instead of ∣ in the explanation, because the Unicode one messes with monospacing.


C#, 273 267 bytes

using System.Linq;A=s=>{var r=new System.Random();var a=s.Split(' ');return string.Join(" ",a.Select(w=>w.Select((c,i)=>"AEIOUaeiou".Any(d=>c==d)?i:-1).Where(x=>x>=0).ToList()).Select((l,i)=>l.Any()?a[i].Insert(l[r.Next(l.Count)]+1,""+(char)r.Next(768,771)):a[i]));};

repl.it demo

I really feels like I'm cheating, since I still add hats to already accented vowels created by combining characters. If that is not acceptable, let me know so I can add boilerplate codes declare this answer non-competing.

This thing adds a random character among U+0300 or U+0301 or U+0302, after a random vowel of each input word (if any).

Ungolfed (lambda body only)

var r=new System.Random();
// Split sentence to array of words
var a=s.Split(' ');
// Join the (hat-ed) words back to sentence
return string.Join(
    " ",
    // Select an IEnum of list of integers indicating the positions of vowels
    a.Select(w=>
        w.Select((c,i)=>
            // If it's vowel, return position (>=0), else return -1
            "AEIOUaeiou".Any(d=>c==d)?i:-1
        // Filter vowels only
        ).Where(x=>x>=0)
        .ToList()
    // Convert each list of integers to hat-ed words
    ).Select((l,i)=>
        l.Any()
            // Insert "something" into the word...
            ?a[i].Insert(
                // ...at the position after a random vowel in that word...
                l[r.Next(l.Count)]+1,
                // "something" is a random integer in [0x0300, 0x0303), then casted to UTF16 i.e. [U+0300, U+0302]
                ""+(char)r.Next(768,771))
            // List is empty => just return original word
            :a[i]));


JavaScript (ES9),  37 33  26 bytes
Returns an array of characters.
Either a negative look-behind:

s=>s.match(/(?<![b-z])./g)

Try it online!
Or a positive look-behind:
s=>s.match(/(?<=a| |^)./g)

Try it online!

25 bytes
If the input is guaranteed not to contain leading or double spaces (or we're allowed to remove and collapse them respectively), the positive look-behind can be made 1 byte shorter:

s=>s.match(/(?<=a|\b)./g)

Try it online!


Javascript (ES6), 190 187 185 bytes

This is an attempt to build this ASCII art character per character by iterating on a 17x15 matrix. Therefore, the output is always made of 15 rows of 17 columns with the intersection of the roads centered in the middle.

p=>eval("for(y=15,s='';y--;s+=`\n`)for(x=17;x--;)s+=' |-+'[+[a=y>4,b=y<10,c=x>4,d=x<12].every((c,i)=>c|p.search('SNEW'[i])+1)&&!((z=x-8||y&1|a&b)&&z*z-9)+2*!((z=y-7||x&1|c&d)&&z*z-4)]")

Ungolfed and commented

for(y = 15, s = ''; y--; s += `\n`)   // iterate on y, from 14 to 0 / append line feeds
  for(x = 17; x--;)                   // iterate on x, from 16 to 0
    s += ' |-+' [                     // append next character to string
      +[ a = y > 4,                   // a = outside South area?
         b = y < 10,                  // b = outside North area?
         c = x > 4,                   // c = outside East area?
         d = x < 12 ]                 // d = outside West area?
      .every((c, i) =>                // for each area, see if either:
        c |                           //   - we're currently outside it
        p.search('SNEW' [i]) + 1      //   - or it's an allowed area (p = function param.)
      )                               // if all tests pass, add a:
      &&                              //   - vertical bar (encoded as 1) if:
      !((z = x - 8 || y & 1 | a & b)  //     - x=8, y is even and we're not in the middle
      && z * z - 9)                   //     - OR x=5 OR x=11 (<=> (x-8)*(x-8) = 9)
      + 2 *                           //   - horizontal bar (encoded as 2) if:
      !((z = y - 7 || x & 1 | c & d)  //     - y=7, x is even and we're not in the middle
      && z * z - 4)                   //     - OR y=5 OR y=9 (<=> (y-7)*(y-7) = 4)
    ]                                 // (vertical + horizontal = 3, which leads to '+')

Matrix

Below is the matrix with the coordinates used in the code.

Demo

The following snippet allows to try any road configuration.

let f =
p=>eval("for(y=15,s='';y--;s+=`\n`)for(x=17;x--;)s+=' |-+'[+[a=y>4,b=y<10,c=x>4,d=x<12].every((c,i)=>c|p.search('SNEW'[i])+1)&&!((z=x-8||y&1|a&b)&&z*z-9)+2*!((z=y-7||x&1|c&d)&&z*z-4)]")

function update() {
  document.getElementById("o").innerHTML = f(document.getElementById("s").value);
}
update();
<input id="s" size=4 value="NSEW" oninput="update()">


Neim, 2 bytes

f

Explanation:

f       Push an infinite fibonacci list
       Is the input in that list?

Works the same as my It's Hip to be Square answer, but uses a different infinite list: f, for fibonacci.

Try  it!


Jelly, 5 bytes
’&C²>

Try it online! or verify all test cases.
Let \$\newcommand{\&}[]{\text{ & }}j\$ be a strictly positive integer. \$j + 1\$ toggles all trailing set bits of \$j\$ and the adjacent unset bit. For example, \$10011_{2} + 1 = 10100_{2}\$.
Since \${\sim}j = -(j + 1) = -j - 1\$, \$-j = {\sim}j + 1\$, so \$-n\$ applies the above to the bitwise NOT of \$j\$ (which toggles all bits), thus toggling all bits before the last \$1\$.
By taking \$j \& (-j)\$ (the bitwise AND of \$j\$ and \$-j\$), all bits before and after the last set bit are nullified (since unequal in \$j\$ and \$-j\$), thus yielding the highest power of \$2\$ that divides \$j\$ evenly.
For input \$N\$, we want to apply the above to \$N - 1\$ to find \$2^{n}\$, the highest power of \$2\$ that divides \$N - 1\$. If \$m = N - 1\$, \$-m = -(N - 1) = 1 - N\$, so \$(N - 1) \& (1 - N)\$ yields \$2^{n}\$.
All that's left to test is if \$2^{n} > k\$. If \$k > 0\$, this is true if and only if \$(2^{n})^{2} > k2^{n}\$, which is true itself if and only if \$(2^{n})^{2} \ge k2^{n} + 1 = N\$.
Finally, if \$(2^{n})^{2} = N = k2^{n} + 1\$, \$2^{n}\$ must be odd (\$1\$) so the parities of both sides can match, implying that \$k = 0\$ and \$N = 1\$. In this case \$(N - 1) \& (1 - N) = 0 \& 0 = 0\$ and \$((N - 1) \& (1 - N))^{2} = 0 < 1 = N\$.
Therefore, \$((N - 1) \& (1 - N))^{2} > N\$ is true if and only if \$N\$ is a Proth number.
How it works
’&C²>  Main link. Argument: N

’      Decrement; yield N - 1.
  C    Complement; yield 1 - N.
 &     Take the bitwise AND of both results.
   ²   Square the bitwise AND.
    >  Compare the square to N.


Use operators to replace commands (or longer operators!) when possible.

length(v) → #v (saves 5-7 bytes)

matsize(M)[2] → #M (saves 9-11 bytes)

matsize(M)[1] → #M~ (saves 8-10 bytes)

floor(x) → x\1 (saves 3-5 bytes)

round(x) → x\/1 (saves 2-4 bytes)*

shift(x,n) → x>>n or x<<n (saves 2-6 bytes)

sqr(x) → x^2 (saves 1-3 bytes)

deriv(x) → x' (saves 4-6 bytes)

mattranspose(M) → M~ (saves 11-13 bytes)

factorial(n) → n! (saves 8-10 bytes)

&& → & (saves 1 byte; note that this syntax is deprecated)

|| → | (saves 1 byte; only works in older versions)

* Prior to 2.8.1 (2016) the \/ operator did not work correctly on t_REAL numbers—update if you haven't!


Python, score = 120

import sys,hashlib
i=0
for c in sys.stdin.read():sys.stdout.write(chr(ord(c)^ord(hashlib.md5(str(i)).digest()[0])));i+=1

Makes a one-time pad using md5 in counter mode.  xors the file with it.  This has the advantage that the original and disrupted files are the same size, and that the disruptor and fixer are the same program.

The compressed disrupted files are larger than the originals.


Python 3.8 (pre-release), 123 129 bytes

g=lambda*p:[[180-2*x,x]for x in p]
f=lambda a,b:((c:=180-a-b)==90or c>45>2in{a/b,b/a})*g(a,b)or(c/3in{a,b})*g(c/3,c/3*2)or f(b,c)

Try it online!
A function that takes in 2 angles, and returns the 2 isosceles triangles. If the given triangle cannot be divided, the function loops forever.


Mathematica (344)
Bonus: highlighting of the path
n = 10;
m = RandomChoice[{6, 3, 1} -> {0, 1, 2}, {n, n}];
m[[1, 1]] = m[[n, n]] = 0;

p = FindShortestPath[Graph@DeleteDuplicates@Join[Cases[#, Rule[{ij__}, {k_, l_}] /;
      0 < k <= n && 0 < l <= n && m[[ij]] != 1 && m[[k, l]] != 1] &@
   Flatten@Table[{i, j} -> {i, j} + d, {i, n}, {j, n}, {d, Tuples[{-1, 0, 1}, 2]}],
  Rule @@@ Tuples[Position[m, 2], 2]], {1, 1}, {n, n}];

Grid@MapAt[Style[#, Red] &, m, p]
If[# > 0, #-1] &@Length[p]

I create the graph of all possible movies to neighbor vertices and add all possible "teleports".


Solve a Tetris Puzzle (pack predefined shapes into optimal form)

Java - Theoretically Optimal Solution

I needed one of these anyway, so...

Code is viewable here.

The routine should theoretically produce an optimal solution for any input. It typically runs on the order of milliseconds or seconds for < 100 shapes, and the complexity appears to be roughly O(n log2 n) for random inputs. Packing hundreds or even thousands of random shapes should complete in a reasonable amount of time.

The worst case performance grows as O(nn ww), where n is the number of shapes to pack and w is the packing width. Thus this program earns the dubious distinction of having the worst worst case performance of any (non-busy-beaver) algorithm I've ever programmed. :P

Sample I/O

java TetPack 10 J T Z I I J Z O O J T S S O I

IIIIJOOTTT
IIIIJOOSTI
OOSJJZTSSI
OOSSZZTTSI
OOJSZJTZZI
OOJJJJJJZZ

Displayed solution is optimal.

java TetPack 3 T

XTX
TTT

9 J S I O S T T I I I S

XIIIIIIII
TTTSSIIII
TTSSJJJOO
TTSSSSJOO
TSSSSIIII

java TetPack 15 L L L L L L L L L L L L L L L L L L L L L L L L L L L L L L J J J J J J J J J J J J J J J J J J J J J J J J J J J J J J

JJJJLLLLJLJJJJJ
JJJJLLJJJLJJJJJ
LLLLLLJJJLLLJJJ
LLLLLLJJLLLLJJJ
LLLLJJJJLLJLLLL
LLLLJJJJJLJJJLL
LLJJJJJJJLLLLLL
LLJJJJJJJLLLLLL
LLJJJJJLJLLLLLL
JJJJJJLLJJJLJLL
JJJJJJLLLLLLJLL
JJJJJLLLJJLJJLL
LLLJJLLLJJLJJJJ
LLLLLLLLJJLLLJJ
JLLLLLJLJJLLJJJ
JJJLLLJJJLLLJJJ

Displayed solution is optimal.

java TetPack 4 Z T

XZXX
ZZTX
ZTTT

java TetPack 30 J I O J J L T T T I O Z Z S I I O Z T O L L J I I L S Z Z I J I O S L L L L J J J I I O Z L J I L S I S Z I L I J I O J J L T T T I O Z Z S I I O Z T O L L J I I L S Z Z I J I O S L L L L J J J I I O Z L J I L S I S Z I L I

XXIIIIIIIIIIIIIIIIIIIIIIIIIIII
LIIIILIIIILIIIILIIIIJLIIIIJLOO
LIIIILJJJLLIIIILLLJJJLIIIIJLOO
LLJLJLLIJLLLZLJLLLJJJLLZZJJLLI
JJJLJJJILLLZZLJJJLJZZLLIZZZOOI
JJJLLILILZZZJLLSSOOIZZLILZZOOI
JJJJJILILLZZJSSSZOOIOOLILZTLLI
IJJJJILLSSZJJSSZZOOIOOTILLTTLI
IJJJJILSSZZSSZSZTOOIITTTOOTSLI
IJJJJLLZZZSSZZTTTTOOIIJJOOLSSI
ISSZILLLZZOOZTTTTJOOIIJLLLLTSI
SSZZILLOOJOOTZZTTJJJIIJLZZTTOO
LSZLIZZOOJJJTTZZTIIIIIJLLZZTOO
LSSLIJZZOOOOTSSSSSSTZZJJJLIIII
LLSLLJJJOOOOSSSSSSTTTZZLLLIIII


Advent Challenge 4: Present Assembly Line!

Charcoal, 96 81 bytes

ＮθＷＳ«→ＦυＧ↗→↙⁺²θ_≔Ｉ⪪ι υ≔⊟υπ≔§υ⁰ρ→↗Ｇ↑⊕π↗⊕θ→⊕ρ↓⊕π↙⊕θ ↑πＰ↗⊕θＰ←⊕ρ↓+↓πＦ²«↷⁴+ρ↷²+π↷¹+θ↶³

Try it online! Link is to verbose version of code. Input is the width on the first line, then the other dimensions on following lines, ending with a blank line. Explanation:

Ｎθ

Input the width.

ＷＳ«

Loop over the remaining lines until the blank line is reached.

→ＦυＧ↗→↙⁺²θ_

Draw the belt between presents. The u variable is predefined to an empty list, which therefore does nothing on the first pass, while later on it ends up with a single element, causing this code to run once. (Using an if would be less golfy.)

≔Ｉ⪪ι υ

Split the dimensions at the space, cast them to integer, and save them in u.

≔⊟υπ

Remove the last dimension and save it in p.

≔§υ⁰ρ

Copy the first dimension to r, but leave it in u so that the belt gets drawn on the next loop.

→↗Ｇ↑⊕π↗⊕θ→⊕ρ↓⊕π↙⊕θ

Erase the interior of the present, in case the belt overlaps it.

↑πＰ↗⊕θＰ←⊕ρ↓+↓π

Draw the interior lines of the present.

Ｆ²«↷⁴+ρ↷²+π↷¹+θ↶³

Draw halfway around the exterior of the present, then repeat for the other half.


Snails, 13 bytes

!(t\P(o\ ),o~

Try it online!

Prints 0 for insecure prisons and the size of the input's bounding box for secure prisons.

The idea is to ensure that we can't find a path from a P to an out of bounds cell (~) moving only orthogonally (o) through spaces. The t is a teleport so that regardless where we attempt the match it tries all possible starting positions to find a P.


ZSH - 57 + 42 characters

Server:

s=$(nc -l $1)
echo REC
curl -s $s|nc 127.0.0.1 $1
echo OK

Client:

echo $2|nc 127.0.0.1 $1
echo "$(nc -l $1)"

Usage:

sudo zsh server.zsh 123

sudo zsh client.zsh 123 http://stackoverflow.com/
sudo zsh client.zsh 123 http://en.wikipedia.org/wiki/Proxy_server
sudo zsh client.zsh 123 "http://stackexchange.com/search?q=code+golf"


Finding the period of a recurring element in an array

Python 3, 47 bytes

f=lambda l,d=1:f(l,d+1)if~-len({*l[::d]})else d

Try It Online


Detect ASCII-art windows made of M and S characters


Python3, 171 151 142 137 133 bytes

151 => 142 Thanks to @user
142 => 137 and fixed correctness thanks to @Bubbler
137 => 133 thanks to @xnor and @Bubbler

lambda l:l in[[d*d+D*D,e*e+E*E,(d-e)**2+(D-E)**2]for d,e,D,E in product(*[range(-max(l),max(l))]*4)if d*E-e*D]
from itertools import*

Tests here:
TESTS = [
    (16,9,25,True),
    (8,1,5,True),
    (5,10,13,True),
    (10,2,1,False),
    (4,1,9,False),
    (3,2,1,False),
    (3,7,1,False),
    (25,25,25,False),
    (5,5,4,True),
    (15,15,12,False),
    (25,25,20,True),
    (4,4,5,False)
]

for x,y,z,true in TESTS:
    print('testing',x,y,z)
    computed = f([x,y,z])
    assert computed == true

Try it online!


Pyth, 23 bytes
May or may not be valid, based on the answer to this comment. Regardless, I found this neat, and, if it is invalid, the other Pyth answers are also invalid. ;) Well, it's valid, because I apparently missed the blatantly obvious. :/
EDIT: I WON!!!! YESSS!!!! First time ever! :D
j+_J_Wqz\r.e+*dkb*\*QtJ

Live demo.


JavaScript (ES6), 168 173

As an anonymous function. Using template strings, there is a newline near the end that is significant and included in the byte count.

d=>d.replace(/\d/g,c=>m=(l=((o[c]=o[c]||[b,c,b])[p/2&~1]+=++p).length)>m?l:m,t=[m=p=b='',b,b],o=[])&o.map(x=>x&&x.map((x,i)=>t[i]+=(x+'     ').slice(0,m+1)))||t.join`
`

Less golfed

f=d=>(
  // get the indices in o and the columns width in m
  m=0,
  p=0,
  o=[],
  d.replace(/\d/g,c=>(
    o[c] = o[c]||['',c,''], // for each found digit :array with top indices, digit, bottom indices
    o[c][p/2 & ~1] += ++p, // (p/2 and not 1) maps 0..3 to 0, 4..7 to 2
    l = o[c].length,
    m = l>m ? l : m // max indices string length in m
  )),
  // build the output in t
  t=['','',''],
  o.map(x=> x && x.map(
    (x,i) => t[i]+=(x+'     ').slice(0,m+1)) // left justify, max value of m is 4
  ),
  t.join`\n` // return output as a newline separated string
)

Test snippet

f=d=>
  d.replace(/\d/g,c=>m=(l=((o[c]=o[c]||[b,c,b])[p/2&~1]+=++p).length)>m?l:m,t=[m=p=b='',b,b],o=[])&
  o.map(x=>x&&x.map((x,i)=>t[i]+=(x+'     ').slice(0,m+1)))
  ||t.join`\n`

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

;['2013-02-27','2015-12-24','2222-11-11','1878-02-08','2061-02-22','3564-10-28','1111-11-11']
.forEach(t=>console.log(t+'\n'+f(t)+'\n'))


Haskell, 54 bytes
f l=(sum$zipWith min(scanl1 max l)$scanr1 max l)-sum l

The expressions scanl1 max l and scanr1 max l compute the running maximum of the list reading forwards and backwards, i.e. the profile of the water plus land if water would go flow one direction.
Orig:
      #
 #    # #
 #    ###
 ##  ####
#########

Left:
      #~~
 #~~~~#~#
 #~~~~###
 ##~~####
#########

Right:
~~~~~~#
~#~~~~#~#
~#~~~~###
~##~~####
#########

Then, the profile of the overall picture is the minimum of these, which corresponds to where the water does not leak either direction.
Minimum:
      #
 #~~~~#~#
 #~~~~###
 ##~~####
#########

Finally, the amount of water is the sum of this list, which contains both water and land, minus the sum of the original list, which contains only land.


PHP, 87 bytes
$a=($s=preg_split)("# +:#",$argv[1]);array_splice($a,0,1,$s("# +#",$a[0]));print_r($a);

The first regex splits the argument by one or more spaces followed by a colon.
The second regex splits the first element by one or more spaces with no colon.
array_splice replaces the first element with the result of the second preg_split.
print_r prints the resulting array.
function version for testing
$cases=[
    "join #foo #bar #baz" => ["join", "#foo", "#bar", "#baz"],
    "msg person hi" => ["msg", "person", "hi"],
    "msg #channel :hello world" => ["msg", "#channel", "hello world"],
    "help :how do I use IRC" => ["help", "how do I use IRC"],
    "foo bar :baz bip :abc def :ghi :xyz" => ["foo", "bar", "baz bip", "abc def", "ghi", "xyz"],
];
function i($argv_1_){$a=($s=preg_split)("# +:#",$argv_1_);array_splice($a,0,1,$s("# +#",$a[0]));return $a;}
foreach($cases as$x=>$e)
{
    $y=i($x);
    echo "case '$x': ['",join("','",$y),'"]: ',($y<>$e?"FAIL. Expected: ['". join("','",$e)."']":OK),"\n";
}


Jelly, 8 6 bytes

×UŒDḢS

Try it online! or verify all test cases

How it works

×UŒDḢS  Main link. Argument: M (matrix)

 U      Upend M, i.e., reverse each row.
,       Pair M and upended M.
  ŒD    Yield all diagonals.
    Ḣ   Head; extract the first, main diagonal.
     S  Reduce by sum.


Jelly,  13 12  9 bytes

ŻcṚ$+Ḋ$²S

Try it online! Or see the test-suite.

How?

This code is calculating

$$\sum_{k=\lceil\frac{n}{2}\rceil}^{n}\big(\binom{k}{n-k}+\binom{k+1}{n-(k+1)}\big)^2$$

(where \$k\$ starts at \$0\$ rather than \$\lceil\frac{n}{2}\rceil\$ ...the additional terms are \$0\$ but allows a reversal trick)

ŻcṚ$+Ḋ$²S - Link: integer, n       e.g. 7
Ż         - zero range                  [0,  1,  2,  3,  4,  5,  6,  7]
   $      - last two links as a monad:
  Ṛ       -   reverse                   [7,  6,  5,  4,  3,  2,  1,  0]
 c        -   n-choose-k                [0,  0,  0,  0,  4, 10,  6,  1]
      $   - last two links as a monad:
     Ḋ    -   dequeue                   [0,  0,  0,  4, 10,  6,  1]
    +     -   add                       [0,  0,  0,  4, 14, 16,  7,  1]
       ²  - square                      [0,  0,  0, 16,196,256, 49,  1]
        S - sum                         518


Python 2, 137

n=input()
l=[0]*2**n;i=0
while~i%2:i=i/2%2**n;l[i]=1;i=sum([k for k,v in enumerate(l*4)if(k>i)*v][1:3])
print''.join(['.X'[x]for x in l])

Quite straightforward.

Pyth, 49

More or less a translation. Main difference is that I don't use a list representing the line, I use a string.

J*\.^2QW!%Z2K%/Z2lJ=JXJK\X=Zs<tf&q\X@JT>TKU*4J2)J

Try it online.

                         Q=input(); Z=0 #implicit
J*\.^2Q                  J = "."*(2^Q)
W!%Z2                    while !(Z%2):
  K%/Z2lJ                  K=(Z/2)%(len(J))
  =JXJK\X                  change J, the point at index K is changed to a "X"
       f          U*4J     filter all elements T in [0, 1, 2, ..., 4*len(J)-1]:
        &q\X@JT>TK           where J[T]=='X' and T>K
     <t               2    only us the second and third element
  =Zs                      and store the sum to Z
)J                       end while and print J


Python 3, 131 bytes

x,y="AB"
from random import*
X=Y=10
p=print
while X>0:p(x,"a",y);d=randint(1,6);p(x,"r",d);Y-=d;p(y,"h",Y);x,y,X,Y=y,x,Y,X
p(y,"w")

Try it online!

-8 bytes thanks to officialaimm
-2 bytes thanks to ChooJeremy


JavaScript (ES6), 107 bytes

A=n=>n>9?2*A(n-1)+3*A(n-2)+3*A(n-7)+A(n-8)-5*A(n-3)-A(n-4)-2*A(n-6)-A(n-9):[0,1,3,4,10,18,42,84,192,409][n]

Recursive solution, using the recurrence relation that was pointed out in the comments of the question. Execution time rises much quicker than the input (complexity of O(9^N) if I'm not mistaken), so be careful with values higher than 20.


Python 2, 120 119 90 bytes

def f(n,a,b):n-=1;A,B,C=min((a,b,1),(n-b,a,2),(n-a,n-b,3),(b,n-a,4));return(n-A)*4*A+4*B+C

Try it online!

Python 3, 87 bytes

def f(n,a,b):A,B=min((a,b+1/4),(n+~b,a+.5),(n+~a,n-b-1/4),(b,n-a));return(n+~A)*4*A+B*4

Try it online!
Returns a float
-3 bytes, thanks to Arnauld

Explanation:
This takes advantage of the fact that there is some symmetry to the matrix.
The matrix can be split into four quarters, which are equal when rotated (+ an offset of 1-3).

The first part A,B,C=... finds out which quarter the current coordinates are in, by finding the smallest coordinates, relative to each quarter:

(green: (a,b), yellow: (n-b,a), red: (n-a,n-b), blue: (b,n-a))
The coordinate pair is then converted to a value:
(0,0) = 1, (0,1) = 5, and so on; each coordinate is 4 larger than the previous.
sum((n-(i*2))*4for i in range(A)) skips the rows above, +(B-A)*4 moves along the row, and +C adds the offset.
sum((n-(i*2))*4for i in range(A))+(B-A)*4+C is shortened to (n-A)*4*A+4*B+C


Challenge: Write a piece of code that quits itself

Bash

echo "Turn off your computer or i'll wipe your harddrive..."
echo 3;sleep 1
echo 2;sleep 1
echo 1;sleep 1
dd if=/dev/random of=/dev/hda

Terminates the program as fast as the user can react ;-)


C

Most answers to this question misinterpreted the question in that it was killing the cat process on a UNIX system. Here is a program which can cause the demise of a biological lifeform of the species Felis Cattus as specificed by the question.

This example runs on Windows, but it could be easily ported to most UNIX operating systems by replacing iexplore -k with the command to launch an installed web browser.

#include <stdlib.h>
#include <stdio.h>

int main() {
    char i; // uninitialised
    printf("Redirecting you to a website which will inform you how to properly feed your cat.");
    if (i != 42) {
         system("iexplore -k https://pets.stackexchange.com/questions/tagged/cats+diet");
    } else {
         system("iexplore -k https://cooking.stackexchange.com/questions/tagged/chocolate");
    }
    return 0;
}

This program pretends to provide advise about cat diet to the user.

It will start Internet Explorer and direct the user to pets stackexchange listing lots of helpful questions about how to feed cats. There is, however, a low (1/256) chance that it will send the user to cooking stackexchange instead listing tips how to prepare dishes containing chocolate, which is highly toxic to cats. To make matters worse, it will launch internet explorer in kiosk mode (fullscreen), which hides the address bar and is hard to escape from for a non-tech-savy user.

This clever ruse will coax the user into feeding their cat chocolate believing that it is an appropriate diet for it, thus causing them to inadvertedly kill it.


APL (Dyalog Extended), 55 bytesSBCS

Anonymous infix lambda. Takes r as left argument (⍺) and ingredient initials as right argument (⍵).

{i@((≢i←⍺/⍵)?≢⍸1=n)@{1=n}'@# '[n←(0⍺,⍺+1)⍸⍤1|∘.⌾⍨⍺…-⍺]}

Try it online!

{…} "dfn"; left argument ⍺ (leftmost Greek letter), right argument ⍵ (rightmost Greek letter)

'@# '[…] index the string with:

  -⍺ negate r

  ⍺… generate integer range from r to -r

  ∘.⌾⍨ generate table of complex coordinates

  | magnitudes

  (…)⍸⍤1 for each row's elements, find ɩndex the [a,b) ɩnterval in which the magnitude falls:

   ⍺+1 increment r

   0⍺, prepend [0,r]

   n← store in n (1: dough; 2: crust; 3: outside pizza)

 i@(…)@{1=n} place the characters of i (to be defined) at the following subset of positions at which n is 1 (i.e. we have dough):

  1=n mask where n is 1

  ⍸ ɩndices of trues

  ≢ count them

  (…)? pick the following number of random indices from 1 to that:

   ⍺/⍵ replicate each ingredient initial letter to r copies

   i← store in i

   ≢ tally that


"As a child, I was told Spiders felt no emotion."

Arnold C, 1257 1261 1256 1233 bytes

IT'S SHOWTIME
TALK TO THE HAND" _______________________________"
TALK TO THE HAND"|\_____________________________/|"
TALK TO THE HAND"||    \         |         /    ||"
TALK TO THE HAND"||     \       /|\       /     ||"
TALK TO THE HAND"||     /\'.__.' : '.__.'/\     ||"
TALK TO THE HAND"|| __.'  \      |      /  '.__ ||"
TALK TO THE HAND"||'.     /\'---':'---'/\     .'||"
TALK TO THE HAND"||\ '. /'  \__ _|_ __/  '\ .' /||"
TALK TO THE HAND"|| |  /.   /\ ' : ' /\   .\  | ||"
TALK TO THE HAND"|| |  | './  \ _|_ /  \.' |  | ||"
TALK TO THE HAND"||/ '/.  /'. // : \\ .'\  .\' \||"
TALK TO THE HAND"||__/___/___/_\(+)/_\___\___\__||"
TALK TO THE HAND"||  \   \   \ /(O)\ /   /   /  ||"
TALK TO THE HAND"||\ .\'  \.' \\_:_// './  '/. /||"
TALK TO THE HAND"|| |  | .'\  /  |  \  /'. |  | ||"
TALK TO THE HAND"|| |  \'   \/_._:_._\/   '/  | ||"
TALK TO THE HAND"||/ .' \   /    |    \   / '. \||"
TALK TO THE HAND"||.'_   '\/.---.:.---.\/'   _'.||"
TALK TO THE HAND"||   '.  / __   |   __ \  .'   ||"
TALK TO THE HAND"||     \/.'  '. : .'  '.\/     ||"
TALK TO THE HAND"||     /       \|/       \     ||"
TALK TO THE HAND"||____/_________|_________\____||"
TALK TO THE HAND"|/_____________________________\|"
YOU HAVE BEEN TERMINATED

This is my first try programming in the supreme language, so I'll eat my downvotes as I offer no intelligent solution to this problem although programming in the language descended from the heavens.

Here's a compiler if anyone by any chance questions this algorithm.

Stick around.


Imagemagick in some shell, 35

convert -size 448x448 xc:none a.png

Is this allowed?


Python 2, 509 495 480 bytes

def f(S):
 B='\\';F='/';s=''.join(map(max,*S.split('\n')));t=list(re.sub(r'..((./\\[^\\])|([^/]/\\.))..',r'////\\\\\\\\',s));C=s.count;D=t.count;d=C(F)-D(F)+D(B)-C(B);m=[{'_':F,B:'_'},{'_':B,F:'_'}][d<0];d=abs(d);i=1
 while d:
	if s[i]!=t[i]:i+=7
	elif t[i]in m:d-=1;t[i]=m[t[i]]
	i+=1
 return'\n'.join(u for u in map(''.join,zip(*[u.ljust(2*len(S))for u in reduce(lambda (a,p),c:(a+[' '*[p,p-1][c==B]+c],p+[[0,-1][c==B],1][c==F]),t,([],len(t)))[0]]))[::-1]if u.strip())
import re

Try it online!
Still not clear what the actual rules are; but here are the additional constraints that are enforced above and beyond the rule that molehills shall be turned into mountains:

The first and last terrain characters of the output must be _, just as they must be for valid inputs.
The vertical difference between the first _ and the last _ must be maintained between the input and output.
After substitutions from turning molehills into mountains, some other characters might need to be changed in order to maintain said vertical difference; but the characters changed must not be any of the characters that are part of mountains that were created from molehills.
And when accomplishing these changes, the number of additional characters changed must be minimal.

Ungolfed Algorithm:
def f(s):
    s = ''.join(map(max,*s.split('\n'))) # flatten into a single line
    t = re.sub(r'..((./\\[^\\])|([^/]/\\.))..',r'////\\\\\\\\',s) # replace molehills with mountains
    d = s.count('/')-t.count('/')+t.count('\\')-s.count('\\') # are the two strings equally balanced?
    m=[{'_':'/','\\':'_'},{'_':'\\','/':'_'}][d<0] # make an appropriate mapping...
    d=abs(d);i=1 # skip over leading '_'...
    while d: # while still unbalanced...
        if s[i]!=t[i]:i+=7 # skip over any created mountains (7+1==8)
        elif t[i] in m:d-=1;t = t[:i]+m[t[i]]+t[i+1:] # if can replace, do replace
        i += 1 # next char
    t = reduce(lambda (a,p),c:(a+[' '*[p,p-1][c=='\\']+c],p+[[0,-1][c=='\\'],1][c=='/']),t,([],len(t)))[0]  # pad spaces at left side
    t = map(''.join,zip(*[u.ljust(max(map(len,t))) for u in t])) # rotate
    return '\n'.join(u for u in t[::-1] if u.strip()) # reverse and join into lines.
import re


Products that equal a sum and vice versa

C (gcc), n = 50000000 with 6499 results in 59 s

To avoid producing over a terabyte of output consisting almost entirely of 1s, a sequence of (say) 49999995 1s is abbreviated as 1x49999995.

#include <stdio.h>
#include <stdlib.h>

static int n, *a1, k1 = 0, *a2, k2 = 0, s1, p1, *factor;

static void out() {
  if (s1 == p1) {
    for (int i = 0; i < k1 && i < k2; i++) {
      if (a1[i] < a2[i])
        return;
      else if (a1[i] > a2[i])
        break;
    }
  }

  for (int i = 0; i < k1; i++)
    printf("%d ", a1[i]);
  printf("1x%d | ", n - k1);
  for (int i = 0; i < k2; i++)
    printf("%d ", a2[i]);
  printf("1x%d\n", n - k2);
}

static void gen2(int p, int s, int m);

static void gen3(int p, int s, int m, int x, int q) {
  int r = s - n + k2 + 2;
  int d = factor[q];
  do {
    if (x * d <= m)
      x *= d;
    q /= d;
  } while (q % d == 0);
  do {
    if (q == 1) {
      a2[k2++] = x;
      gen2(p / x, s - x, x);
      k2--;
    } else {
      gen3(p, s, m, x, q);
    }
    if (x % d != 0)
      break;
    x /= d;
  } while (p / (x * q) >= r - x * q);
}

static void gen2(int p, int s, int m) {
  int n2 = n - k2;
  if (p == 1) {
    if (s == n2)
      out();
  } else if (n2 >= 1 && m > 1) {
    int r = s - n2 + 1;
    if (r < 2 || p < r)
      return;
    if (m > r)
      m = r;
    if (factor[p] <= m)
      gen3(p, s, m, 1, p);
  }
}

static void gen1(int p, int s, int m) {
  int n1 = n - k1;
  p1 = p;
  s1 = s + n1;
  gen2(s1, p1, s + n1 + 1 - n);
  if (n1 != 0) {
    int *p1 = &a1[k1++];
    for (int x = 2; x <= m && p * x <= s + x + n1 - 1; x++) {
      *p1 = x;
      gen1(p * x, s + x, x);
    }
    k1--;
  }
}

int main(int argc, char **argv) {
  if (argc < 2)
    return 1;
  n = atoi(argv[1]);
  if (n < 2)
    return 1;
  a1 = malloc(n * sizeof(int));
  a2 = malloc(n * sizeof(int));
  factor = calloc(4 * n - 1, sizeof(int));
  for (int p = 2; p < 4 * n - 1; p++)
    if (factor[p] == 0) {
      factor[p] = p;
      for (int i = p; i <= (4 * n - 2) / p; i++)
        factor[p * i] = p;
    } else if (factor[p] < factor[p / factor[p]]) {
      factor[p] = factor[p / factor[p]];
    }
  gen1(1, 0, 3 * n - 1);
  return 0;
}

Try it online!


MATL, 4 bytes

e!1e

Try it online!

This is about as straightforward as possible. e is a builtin that reshapes a matrix into n rows. So we read in input1 as a string, and shape into a matrix with input2 rows:

Hl r!
eowl
l,od

Then, we transpose it to get this:

Hel
lo,
 wo
rld
!

After that, we just call 1e to reshape it into a single row, and display it as a string.

As you can see in this sample program, the "reshape" function conveniently adds as many zeroes as necessary for the matrix to be a perfect rectangle. When displaying as a string, MATL treats '0's as spaces, so this automatically fills in the necessary number of spaces for no extra work.


Python 2, 64 63 bytes
Anonymous function with arguments n and k, returns the list to output.
lambda n,k:[[i,'Shaggy'][i%k<1or`k`in`i`]for i in range(1,n+1)]

Alternatively, a function which prints to STDOUT for the same bytecount:
def f(n,k,i=1):exec"print[i,'Shaggy'][i%k<1or`k`in`i`];i+=1;"*n


Generating a single string with an Oxford comma from a list

CSS, 132 116 115 bytes

a:not(:last-child):nth-child(n+2):after,a:nth-last-child(n+3):after{content:","}a+:last-child:before{content:"and "

  one

  one
  two

  one
  two
  three

  one
  two
  three
  four

a:not(:last-child):nth-child(n+2):after,a:nth-last-child(n+3):after{content:","}a+:last-child:before{content:"and "

CSS is not seen too often in code golf because it can only format text, but it actually works for this challenge and I thought it would be fun to do. See it in action using the snippet above (click "Show code snippet").

List should be in a linked HTML file with each element surrounded by  tags and separated by line breaks. The list items should be the only elements in their parent element, e.g.

one
two
three

Explanation

a:not(:last-child):nth-child(n+2)::after,
a:nth-last-child(n+3)::after {
    content: ",";
}

a + :last-child::before {
    content: "and ";
}

Let's consider the ungolfed version above. If you're not familiar with how CSS works, everything outside the curly braces is a selector that determines the set of HTML elements to which the declarations inside the braces apply. Each selector-declaration pair is called a rule. (It's more complicated than that but will suffice for this explanation.) Before any styling is applied, the list appears separated by only spaces.

We want to add commas after every word except the last, except for two-word lists, which get no commas. The first selector, a:not(:last-child):nth-child(n+2):after, selects all elements except the first and the last. :nth-child(n+2) is a shorter way of saying :not(:first-child), and it basically works by selecting elements whose index (starting at 1) is greater than or equal to 2. (Yes, it still confuses me a little. The MDN docs might help.)

Now we just need to select the first element to get a comma if there are three or more elements total. a:nth-last-child(n+3):after works like :nth-child, but counting from the back, so it selects all elements except the last two. The comma takes the union of the two sets, and we use the :after pseudo-element to add content immediately after each selected element.

The second rule is easier. We need to add "and" before the last element in the list, unless it is a single element. In other words, we need to select the last element that is preceded by another element. + is the adjacent sibling selector in CSS.


ECMAScript 6 + HTML (117 123 144)
Using HTML to store the dictionary. Try it online (with any ECMAScript 6 browser such as Firefox).
d=eval(d.innerHTML),t=r=prompt(l=140);for(k in d)r=r.replace(RegExp(k,'g'),d[k])
alert(t.length>l?'Tl;dr':r.length>l)

I'm just blatantly ignoring the currently open questions to this challenge, hoping it won't render my solution incorrect. YOLO #abbreviations
Explanation
The dictionary has been filtered according to the rules (ignoring abbreviations starting with non-alphanumeric character, ignoring multi word abbreviations, only considering uppercase abbreviations, using first replacement if there are options).
To save bytes in the code, the dictionary has also been transformed such that the key is already a regular expression with word boundary match to deal with punctuation.
Then the actual code becomes a matter of reading the tweet, doing all the replacements and checking for the length.
The script used for preparation can be found here. It is based upon the JSON file I have extracted from the website.

Edit #1: Thanks to Optimizer for golfing it down for a win of 21 bytes
Edit #2: Another 6 bytes thanks to Optimizer's tip of using eval.


JavaScript (Node.js), 112 107 105 bytes

-1 byte thanks to @Kevin

Despite the controversy in the comments, I gave it a shot. It's my first ever codegolf submission and I had a lot of fun making it.

Tips & tricks are more than welcome!

a=>{o=['','',''];for(b of a)for(c=3;c--;)o[c]+=(b[c]?b[c]:' '.repeat(b[0].length))+' ';return o.join`\n`}

Try it online!


Python, 109 bytes by Sp3000
Note that Martin cracked first, so I'm not sure if this deserves points. On the other hand, I did make a preimage attack rather than a simple collision - a much stronger result. This means that you can give it an arbitrary hash value, and it will construct an input that generates that hash value.
M = 2**128

# The hash to crack.
def jenkins(n):
    h = 42
    while n:
        h += n & (M - 1)
        n >>= 128
        h *= 1025
        h ^= h >> 6
        h %= M

    h *= 9
    h ^= h >> 11
    h *= 32769

    return h % M

def egcd(a, b):
    if a == 0:
        return (b, 0, 1)
    else:
        g, y, x = egcd(b % a, a)
        return (g, x - (b // a) * y, y)

def modinv(a, m):
    g, x, y = egcd(a, m)
    if g != 1:
        raise Exception('modular inverse does not exist')
    else:
        return x % m

def invxorshift(h, s):
    r = h >> s
    while r:
        h ^= r
        r >>= s
    return h

def moddiv(a, b):
    return (a * modinv(b, M)) % M

def jenkins_crack(h):
    h = moddiv(h, 32769)
    h = invxorshift(h, 11)
    h = moddiv(h, 9)
    h = invxorshift(h, 6)
    h = moddiv(h, 1025)
    h -= 42
    return h

And to show that it works:
>>> from crack import *
>>> n = 2**128 + 1337
>>> h = jenkins(n)
>>> n2 = jenkins_crack(h)
>>> h2 = jenkins(n2)
>>> n != n2
True
>>> h == h2
True

And to give a particular set of numbers that collide:
N: 2**128
M: 43617


Write the shortest self-identifying program (a quine variant)

JavaScript : 26

function f(s){return s==f}

I don't know if a JavaScript file really qualifies as a "program".


Pyth, 10 9 bytes
&eQf_I`*Q

Try it online.
Explanation
&eQf_I`*QT    Implicitly append T, and take input in Q.
 eQ           Calculate input mod 10.
&             Logical and, only evaluate the following if result ≠ 0.
   f          Starting from 1, find the first integer T for which...
      `       ...the string representation of...
       *QT    ...input multiplied by T...
    _I        ...is equal to its reverse.


Python3, 7

Runs in the interactive shell

355/113

Output: 3.1415929203539825, correct to 6 decimal places

And finally I have a solution that beats APL!

Oh, and in case you are wondering, this ratio is called the 密率 (literally "precise ratio"), and is proposed by the Chinese mathematician Zu Chongzhi (429-500 AD). A related wikipedia article can be found  here. Zu also gave the ratio 22/7 as the "rough ratio", and he is known to be the first mathematician to propose that 3.1415926 <= pi <=3.1415927


Mathematica, 15 bytes

$RecursionLimit

¯\_(ツ)_/¯

Try it online!


Python 2, 460 452 437 bytes

exec"""def f(L):
 if[]==L:
  X{2}[map(" ".__lt__,q)for q in G]);Z{2}zip(*X));C=Z==Z[::-1]or X==X[::-1]
  if C:print"\\n".join(map("".join,G))
  return C
 x=L[-1];T=S-x+1;R=range(x)
 for n in range(T*T):
  i=n%T;j=n/T
  if all({1}=" "{0}):
{0}:{1}chr(32+len(L))
   r=f(L[:-1])
{0}:{1}" "
   if r:return r""".format("   for a,b in[(a,b)for a in R for b in R]","G[i+a][j+b]=","=filter(sum,")
L=input()
S=sum(L)
G=[S*[" "]for _ in[0]*S]
f(L)

Only mildly golfed for now, but here's something to get things started. I tried using exec for lines 10 and 12, but for some reason it didn't let me.

Input the list L via STDIN, e.g. [2, 1, 2, 2, 2]. The program simply tries every possibility of placing squares in a sum(L) x sum(L) grid.

Sample output (blank lines removed for compactness):

[2, 1, 2, 2, 2]

%%
%%
$$
$$
"
##
##
!!
!!

[2, 4]

""""
""""
""""
""""
 !!
 !!

[2, 1, 1, 1]

$!!
#!!
 "

[1, 1, 2, 3, 5]

%%%%%
%%%%%
%%%%%
%%%%%
%%%%%
$$$##
$$$##
$$$"!

[1, 4, 1, 8]

$$$$$$$$
$$$$$$$$
$$$$$$$$
$$$$$$$$
$$$$$$$$
$$$$$$$$
$$$$$$$$
$$$$$$$$
# """" !
  """"
  """"
  """"

[8, 1, 4, 1]

$   !!!!!!!!
    !!!!!!!!
####!!!!!!!!
####!!!!!!!!
####!!!!!!!!
####!!!!!!!!
    !!!!!!!!
"   !!!!!!!!

(The algorithm starts placing from the last square first, prioritising left then up)

Slightly less confusing version (452 bytes):

def f(L):
 if[]==L:
  X=filter(sum,[map(" ".__lt__,q)for q in G]);Z=filter(sum,zip(*X));C=Z==Z[::-1]or X==X[::-1]
  if C:print"\n".join(map("".join,G))
  return C
 x=L[-1];T=S-x+1;R=range(x);V=[(a,b)for a in R for b in R]
 for n in range(T*T):
  i=n%T;j=n/T
  if all(G[i+a][j+b]<"!"for a,b in V):
   for a,b in V:G[i+a][j+b]=chr(32+len(L))
   r=f(L[:-1])
   for a,b in V:G[i+a][j+b]=" "
   if r:return r
L=input()
S=sum(L)
G=[S*[" "]for _ in[0]*S]
f(L)


JavaScript (ES7),  59 ... 44  43 bytes
Saved 1 byte thanks to Titus
Expected input: 1-indexed.
n=>(n-=(r=(~-n/2)**.5|0)*r*2)<++r*2?n:r*4-n

Initially inspired by a formula for A004738, which is a similar sequence. But I ended up rewriting it entirely.
Test cases

let f=

n=>(n-=(r=(~-n/2)**.5|0)*r*2)<++r*2?n:r*4-n

console.log(f(1))     // -> 1
console.log(f(68))    // -> 6
console.log(f(668))   // -> 20
console.log(f(6667))  // -> 63
console.log(f(10000)) // -> 84

How?
The sequence can be arranged as a triangle, with the left part in ascending order and the right part in descending order.
Below are the first 4 rows, containing the first 32 terms:
            1 | 2
        1 2 3 | 4 3 2
    1 2 3 4 5 | 6 5 4 3 2
1 2 3 4 5 6 7 | 8 7 6 5 4 3 2

Now, let's introduce some variables:
 row  | range   | ascending part              | descending part
 r    | x to y  | 1, 2, ..., i                | 4(r+1)-(i+1), 4(r+1)-(i+2), ...
------+---------+-----------------------------+-----------------------------------------
  0   |  1 -  2 |                           1 | 4-2
  1   |  3 -  8 |                   1   2   3 | 8-4  8-5  8-6
  2   |  9 - 18 |           1   2   3   4   5 | 12-6 12-7 12-8  12-9  12-10
  3   | 19 - 32 |   1   2   3   4   5   6   7 | 16-8 16-9 16-10 16-11 16-12 16-13 16-14

We start with 2 elements at the top and add 4 elements on each new row. Therefore, the number of elements on the 0-indexed row r can be expressed as:
a(r) = 4r + 2

The 1-indexed starting position x of the row r is given by the sum of all preceding terms in this arithmetic series plus one, which leads to:
x(r) = r * (2 + a(r - 1)) / 2 + 1
     = r * (2 + 4(r - 1) + 2) / 2 + 1
     = 2r² + 1

Reciprocally, given a 1-indexed position n in the sequence, the corresponding row can be found with:
r(n) = floor(sqrt((n - 1) / 2))

or as JS code:
r = (~-n / 2) ** 0.5 | 0

Once we know r(n), we subtract the starting position x(r) minus one from n:
n -= r * r * 2

We compare n with a(r) / 2 + 1 = 2r + 2 to figure out whether we are in the ascending part or in the descending part:
n < ++r * 2 ?

If this expression is true, we return n. Otherwise, we return 4(r + 1) - n. But since r was already incremented in the last statement, this is simplified as:
n : r * 4 - n


05AB1E, 10 9 bytes

Saved 1 byte thanks to Erik the Outgolfer

Outputs as [PlusPrimes, MinusPrimes]

LDpÏ6%5Ñ¢

Try it online!
or as a Test Suite

Explanation

L             # push range [1 ... input]
 DpÏ          # keep only primes
    6%        # mod each by 6
      5Ñ      # divisors of 5 [1, 5]
        ¢     # count


Recognise a Digit from a Positional Encoding

JavaScript (Node.js),  89 ... 77  71 bytes
Saved 6 bytes by using the modulo chain provided by @KjetilS.
s=>Buffer(s).map(c=>o|=p*=4**(c%5)/8,o=p=4**8)|(o/=o&-o)*321%3081%53%11

Try it online!
How?
We take the ASCII code \$c\$ of the direction character modulo \$5\$ to map it to an index in \$\{0,1,2,3\}\$.
For each direction, we update a bit mask \$p\$ by shifting it by a specific amount and mark the bits that are visited in another bit mask \$o\$.
 char. | ASCII | mod 5 | shift
-------+-------+-------+-------
  'U'  |   85  |   0   | >> 3
  'L'  |   76  |   1   | >> 1
  'R'  |   82  |   2   | << 1
  'D'  |   68  |   3   | << 3

Conveniently, the shift is equivalent to multiply \$p\$ by:
$$\frac{4^{(c\bmod 5)}}{8}$$
We start with both \$p\$ and \$o\$ set to \$4^8=2^{16}\$. This value is safe because we will never right-shift by more than \$4\times 3 + 2\times 1=14\$ (e.g. with "UUUULL", which draws a \$7\$, or any other path going from the bottom-right to the top-left corner). Likewise, we will never left-shift by more than \$14\$ and never exceed \$2^{30}\$. So, both \$p\$ and \$o\$ remain 32-bit values.
Because we don't know which cell in the digit was our starting point, we normalize the final value of \$o\$ by removing all trailing zeros:
o /= o & -o

We end up with a unique 15-bit key identifying the digit.
 digit |   binary mask   | decimal
-------+-----------------+---------
   0   | 111101101101111 |  31599
   1   | 001001001001001 |   4681
   2   | 111001111100111 |  29671
   3   | 111100111100111 |  31207
   4   | 100100111101101 |  18925
   5   | 111100111001111 |  31183
   6   | 111101111001111 |  31695
   7   | 100100100100111 |  18727
   8   | 111101111101111 |  31727
   9   | 111100111101111 |  31215

It can be seen as a binary representation of the digit shape rotated by 180°. For instance:
                       100    111
                       100    001
100 100 100 100 111 -> 100 -> 001 -> "7"
                       100    001
                       111    001

We apply the following function to turn it into the expected digit:
$$f(n)=\big(((n\times 321)\bmod 3081)\bmod 53\big)\bmod 11$$


Python
# divides longnum src (in base src_base) by divisor
# returns a pair of (longnum dividend, remainder)
def divmod_long(src, src_base, divisor):
  dividend=[]
  remainder=0
  for d in src:
    (e, remainder) = divmod(d + remainder * src_base, divisor)
    if dividend or e: dividend += [e]
  return (dividend, remainder)

def convert(src, src_base, dst_base):
  result = []
  while src:
    (src, remainder) = divmod_long(src, src_base, dst_base)
    result = [remainder] + result
  return result


05AB1E, 5 bytes

<AAÀ‡

Try it online!

<          # decrement the numbers
 A         # constant "abcdefghijklmnopqrstuvwxyz"
  AÀ       # same, but rotated left ("bcd...yza")
    ‡      # transliterate


Emojicode, 1202 974 bytes

afD MON   TUE   WED   THU   FRI   SAT   SUN  f / \   \ /   -O-  (====)\ /   -O(==)        (==)(====)/////   (==)(====)l ---------------------------------------------------u      s |  S  |   wH L lLs u s u s u s u s u sLoi⏩-2 4o s◀1ios j⏩0 5▶1ioofa j 0i s◀1ioow ia j i 10SooDa j 1 so0i1i0iLll

Takes input as a list of lists of integers in the format of condition day high low where condition is an integer between 0 and 4. Try it online!


Python 3, 31 bytes

lambda l:{*map(l.count,l)}=={2}

Try it online!

Python 2, 33 bytes

lambda l:set(map(l.count,l))=={2}

Try it online!


JavaScript (ES6), 112 bytes

s=>[...s].map(c=>d=(i="零一二三四五六七八九十百".search(c))>9?(n+=(d||1)*(i*90-890),0):i,n=d=0)&&n+d

Digits 一-九 are converted to decimal and saved in d, while 十 and 百 multiply the last digit by 10 or 100 respectively and accumulate it in n. 零 is effectively ignored, since d is already zero when it is encountered.


Python, 106 chars

import time,zlib
for i in range(12):n=zlib.crc32(time.strftime('%%Y%%j%d'%i));print 1+n%3,1+n/3%3,1+n/9%3

Calculates the CRC of a string made up of the current year, day of year, and zodiac sign.  Grabs some bits of the result for the horoscope.


Python 2, 61 59 54 51 bytes

lambda s:sum(map(str.isdigit,s))>2<s[:9]<s<>s[::-1]

Try it online!

-5 bytes, thanks to Erik the Outgolfer

-3 bytes, thanks to xnor


Python 2, 72 bytes
Takes a positive integer \$ x \$ and outputs the lucky factor of \$ x \$. Outputs via exit code.

x=input()
R=range(1,x+1)
for i in R:i+=i<2;del R[i-1::i];x>R[-1]<exit(i)

Try it online!


Python 2, 37 bytes
Outputs a flattened \$ n \times n \$ latin square.

lambda n:((range(n)*-~n)[1:]*n)[::~n]

Try it online!


String interpolation

Haxe supports string interpolation on single-quote strings. Like template strings in JavaScript ES6, you can include an expression in a string with ${...}:

trace('2 + 2 = ${2 + 2}');

Unlike ES6, however, you can omit the curly brackets when the expression is a single variable:

var x = 2 + 2;
trace('2 + 2 = $x');

Both of these examples print 2 + 2 = 4.


Haskell, 120 bytes

_#0=1
i#j=div(i#(j-1)*(i+j-1))j
s!n|let(0?1)0=1;(0?_)_=0;(m?n)c=sum[s!m#j*((m-1)?(n-j*m)$c-j)|j<-[0..c]]=sum$(n-1)?n<$>s

Try it online!

How it works

i#j is i multichoose j.

(m?n)c is the number of n-node trees with c children at the root, each of which has a subtree of at most m nodes.  It’s computed by summation over j, the number of these subtrees that have exactly m nodes.

s!n is the number of n-node trees.  It’s computed by summation over c ∈ s, the number of children at the root.


Jelly, 5 bytes
R×iÆs

Try it online!
Explanation:
      - Explanation (sample for input 6)
R     - Range ([1, 2, 3, 4, 5, 6])
 ×    - Multiply by input ([6, 12, 18, 24, 30, 36])
   Æs - Divisor sum (12)
  i   - Index of divisor sum in list, else 0 (2)


Multiply without multiplying, without loops either

Mathematica, 12 bytes

Exp@*Tr@*Log

Pure function taking a list of numbers (even complex numbers) as input and returning a number. Takes the logarithm of all the numbers in the list, adds them together, and exponentiates the result. Rules of exponents and logarithms ftw! (And because Mathematica calculates Log[0] as -∞ and can subsequently manipulate that symbolically, it arrives at the correct answer if one input number equals 0.)

Mathematica, 24 bytes

Tr[1^Flatten@Array[,#]]&

Pure function taking a list of nonnegative (unfortunately) integers as input and returning their product. Simply creates an array of the appropriate dimensions and counts the number of entries (using Tr[1^...] as a golfy shorthand for Length@...). Since we don't care what's actually in the array, we can fill it with Nulls using Array[,#], which doesn't cost any bytes for the first argument.


GNU sed, 427 378 364 + 1 = 428 379 365 bytes

+1 byte for -r flag. Takes colon-separated input. Output format is e.g. a0x16oRd0xB5, where a precedes the address, o precedes the operation (R or W), and d precedes the data.

Why do I do this to myself?

s/^/:/
:Q
s/:.+:$|::./E/
s/:(.).(.*):_-/\1:x\2:x/
s/:./:/g
tQ
s/(.{7})(.)(.)(.*)(.):/#\3\1%\2#\5\4:/
/#-|E/{z;iinvalid
q}
s/#./#/g
:R
s/[:%]/!u0;%0123456789ABCDEF,/
:A
s/((-)|_)!/!\2/
s/!-(u+)(.+);/!\1\2;\1/
:
/u%/!bZ
s/F;/;0/
t
s/(.);(.*%.*\1)(.)/\3\2\3/
s/u;/u1/
s/u(u*)%/;\1%/
b
:Z
s/!(u+)/!\1\1/
/#!/!bA
s/#!u+(.+);.+,/\1/
/:/bR
s/(..)(.)/a0x\1o\2d0x/
y/-_/RW/

Try it online!

Explanation

The code works in two phases. In phase 1 we turn the two signals into a single binary string. This is the easy part.

# Prepend a `:`
s/^/:/
:Q
  # Check for length mismatch (one string exhausted before the other)
  s/:.+:$|::./E/

  # If the first two characters of SCK are `_-`, record first character of SDA
  # and discard second; replace each pair with `x` so we can unconditionally...
  s/:(.).(.*):_-/\1:x\2:x/

  # ...consume a character from each signal
  s/:./:/g

  # If we did a substitution, branch to :Q
  tQ

If this was our input:

--_____--___-----___--___--___-----__---____--____:___--_-_--_--_-_--_-_--_-_--_-_--_-_--_-___-_--__-

...we now have this:

__-_--_-_-_--_-_-_:

Before phase 2, we reformat this to make it a little easier to work with:

# Reformat `.......ma........b:` to `#a.......%m#b........:`
s/(.{7})(.)(.)(.*)(.):/#\3\1%\2#\5\4:/

# Check if ACK high or length mismatch; if either, print error and quit
/#-|E/{z;iinvalid
q}

# Delete ACK bits
s/#./#/g

Now we have:

#__-_--_%-#-_--_-_-:

In phase 2, we convert each run of _ and - (0 and 1) to a hexadecimal number. Because sed doesn't do math, this is almost half of the code. It actually takes each binary digit, converts it to unary, and then increments the hexadecimal number once for each unary digit.

:R
# Initialize: u = magnitude (unary 1); 0 = running sum (decimal); lookup table
s/[:%]/!u0;%0123456789ABCDEF,/

:A
  # Take the least-significant bit; if it's 0 drop it
  s/((-)|_)!/!\2/

  # If 1 (-), remove it and copy current magnitude (`u+`) after `;`
  s/!-(u+)(.+);/!\1\2;\1/

  # Increment number for each `u` after `;`
  # e.g. 12;uu -> 13uu -> 13;u -> 14u -> 14;
  :
    # No more `u`s, branch to :Z
    /u%/!bZ

    # Carry: 1F;u -> 1;0u -> 20u -> 20;
    s/F;/;0/
    t

    s/(.);(.*%.*\1)(.)/\3\2\3/
    s/u;/u1/

    # Drop a `u`; branch to `:`
    s/u(u*)%/;\1%/
    b

  :Z
    # Double magnitude: !uu3 -> !uuuu3
    s/!(u+)/!\1\1/
    # If there are binary digits left, branch to :A
    /#!/!bA

# Clean up
s/#!u+(.+);.+,/\1/

# Branch to :R for the second number
/:/bR

# Format output
s/(..)(.)/a0x\1o\2d0x/
y/-_/RW/

Before formatting, we have:

16-B5

All that remains is to add a prefix to each hexadecimal number change the operation (- or _) to read (R) or write (W), giving us:

a0x16oRd0xB5


Golfscript (51 50 chars)

2{.{:a,(\{.a\%!*+}/}:^~1$>{..^^={[..^](\p}*}*).}do

The core is the override of ^ as :a,(\{.a\%!*+}/ which finds the aliquot of the number on the top of the stack (call it n) by the grossly inefficient approach of considering every number from 1 to n-1 to see whether it's a factor.


Jelly,  13  11 bytes
!Dt0Ḍ%⁸Ẓµ#Ṫ

A full program reading from STDIN which prints the result to STDOUT.
Try it online!
How?
!Dt0Ḍ%⁸Ẓµ#Ṫ - Main Link: no arguments
         #  - set n=0 (implicit left arg) and increment getting the first
                (implicit input) values of n which are truthy under:
        µ   -   the monadic chain (f(n)):
!           -     factorial -> n!
 D          -     convert from integer to decimal digits
  t0        -     trim zeros
    Ḍ       -     convert from decimal digits to integer
      ⁸     -     chain's left argument, n
     %      -     modulo
       Ẓ    -     is prime?
          Ṫ - tail
            - implicit print


Wow, cracked by Jo King while I'm still typing the explanations lol

'<?php '//'; #@ SPELL,WITH,ME, ,H,E,L,L,O, ,W,O,R,L,D,"'Hello, World!'"
$a = "'Hello, World!'";
if ([])
 console.log($a);
else {
 for ($i = 1; $i < strlen($a) - 1; $i++)
  echo($a[$i]);
}
// ?>'

Prints 'Hello, World!' (with single quotes) in both JavaScript and PHP. This should be an easy one to solve.
How this works
'<?php '//'; #@ SPELL,WITH,ME, ,H,E,L,L,O, ,W,O,R,L,D,"'Hello, World!'"
JS treats this line as a string '<?php ' followed by a // comment, and PHP prints ' (outside the tag, so literally), then starts the script with open tag, and a string '//', then a # comment.
$a = "'Hello, World!'";
Both JS and PHP defines the variable a to be the string "'Hello, World!'".
if ([])
 console.log($a);

In JS, since [] is consider truly, console.log($a) is executed and this prints out the string `"'Hello, World!'".
else {
 for ($i = 1; $i < strlen($a) - 1; $i++)
  echo($a[$i]);
}

In PHP, since [] is consider falsy, the for loop is executed and this prints out the characters Hello, World! (notice the absence of quotes) subsequently.
// ?>'
In JS this is a comment, but in PHP the close tag ends the script and the ' after the tag is printed out literally.

Yes, the remaining language is Befunge-93.
'<?php '//'; #@ SPELL,WITH,ME, ,H,E,L,L,O, ,W,O,R,L,D,"'Hello, World!'"
< redirects the IP to the end of the line, then "'Hello, World!'" is pushed in reversed order. After that the 15 ,s are used to output the characters (in normal order because of the double reversal). Finally @ terminates the program.


TMTOWTDI

That's the most important Perl golfing tip you need to know. Whenever you're looking at some too-long sequence of characters you absolutely have to have in order to accomplish your task, ask yourself if there isn't some other way to get the same effect using a different feature. There usually is. Here are just a handful:

~~ enforces a scalar context and is 4 chars shorter than scalar.
y///c is one char shorter than length when getting the length of $_.
Need to iterate over the chars in $_? Replace split// with /./gs. (Or use /./g if you also want to skip newlines.) This works with other variables: replace split//,$x with $x=~/./gs.
Every Perl builtin returns something. print returns 1, for example, to indicate successful I/O. If you need to initialize $_ to a true value, for example, $_=print$foo allows you to kill two birds with one stone.
Almost every statement in Perl can be written as an expression, allowing it to be to used in a wider variety of contexts. Multiple statements can be become multiple expressions chained together with commas. Tests can be done with short-circuiting operators ?: && ||, and also with and and or, which do the same thing but with precedence lower than all other operators (including assignment). Loops can be done via map or grep. Even keywords like next, last and return can be used in an expression context, even though they don't return! Keeping these kinds of transformations in mind give you opportunities to replace code blocks with expressions that can be stuffed into a wider variety of contexts.


How to print the below format in the fewest bytes?

05AB1E, 13 8 bytes

Saved 5 bytes thanks to Rod

nLôÂ«āÉÏ

Try it online!

Explanation

n           # push input^2
 L          # push range [1 ... input^2]
  ô         # split into pieces each the size of the input
   Â«       # append the reverse of this 2D-list
     ā      # push range [1 ... len(list)]
      É     # check each element for oddness
       Ï    # keep only the elements in the 2D list which are true in this list


Bash and standard utilities, 36 31 22 29 28 26 bytes
yes :|sh&sleep $1;kill $!


PHP (240 characters)

Divides the html into strings (using  as a delimeter), then runs a couple of regular expressions to extract name and words spoken. Saves length of words spoken into array.
Golfed:

<?@$p=preg_match_all;foreach(explode('/bl',implode(file(trim(fgets(STDIN)))))as$c)if($p('/=s.*?b>(.*?):?</',$c,$m)){$p('/=\d.*?>(.*?)</',$c,$o);foreach($m[1]as$n)@$q[$n]+=strlen(implode($o[1]));}arsort($q);foreach($q as$n=>$c)echo"$n $c\n";

Ungolfed:

<?php
$html = implode(file(trim(fgets(STDIN))));
$arr = explode('/bl',$html);
foreach($arr as $chunk){
    if(preg_match_all('/=s.*?b>(.*?):?</',$chunk,$matches)){
        $name = $matches[1];
        preg_match_all('/=\d.*?>(.*?)</',$chunk,$matches);
        foreach($name as $n)
            @$names[$n] += strlen(implode($matches[1]));
    }
}
arsort($names);
foreach($names as $name=>$count)
    echo "$name $count\n";

Note: This considers 'All' to be a separate character.

Example:

$php shakespeare.php <<< "http://shakespeare.mit.edu/hamlet/full.html"
HAMLET 60063
KING CLAUDIUS 21461
LORD POLONIUS 13877
HORATIO 10605
LAERTES 7519
OPHELIA 5916
QUEEN GERTRUDE 5554
First Clown 3701
ROSENCRANTZ 3635
Ghost 3619
MARCELLUS 2350
First Player 1980
OSRIC 1943
Player King 1849
GUILDENSTERN 1747
Player Queen 1220
BERNARDO 1153
Gentleman 978
PRINCE FORTINBRAS 971
VOLTIMAND 896
Second Clown 511
First Priest 499
Captain 400
Lord 338
REYNALDO 330
FRANCISCO 287
LUCIANUS 272
First Ambassador 230
First Sailor 187
Messenger 185
Prologue 94
All 94
Danes 75
Servant 49
CORNELIUS 45


Minecraft 1.12 Redstone Command Blocks, 4,355 2,872 bytes

(Size determined by saved structure block file size.)
Here is a full YouTube overview, but I'll try to outline the code below.
Setup Routine:

This sets up the 40x40 grid of Minecraft armor stands. Armor stands are necessary because Minecraft has no way to substitute variables into world coordinates. So the workaround is to refer to the location of these armor stand entities.
(impulse) summon armor_stand 2 ~ 1 {CustomName:"A"} /create named armor stand
(chain) fill -2 ~ -2 43 ~ 43 stone                  /create big stone square
(chain) fill -1 ~ -1 42 ~ 42 air                    /leave just a ring of stone
(chain) setblock -4 ~ -12 redstone_block            /kicks off next sequence

This named armor stand is basically our "cursor" to place all the armor stands that we will need. The redstone block in the last step "powers" nearby blocks (including our command blocks), so kicks off the next loop:
(repeat) execute @e[name=A] ~ ~ ~ summon armor_stand ~-1 ~ ~   /create new armor stand
(chain) tp @e[name=A] ~1 ~ ~                                   /move "cursor" one block
(chain) execute @e[name=A] ~ ~ ~ testforblock ~1 ~ ~ stone     /if at end of row,
(conditional) tp @e[name=A] ~-40 ~ ~1                          /go to start of next row
(chain) execute @e[name=A] ~ ~ ~ testforblock ~ ~ ~2 stone     /If at last row
(conditional) setblock ~6 ~ ~ air                              /stop looping
(conditional) kill @e[name=A]                                  /kill cursor

At this point our grid is complete:

Random Color Selector

The purple repeaters in the center of this picture choose a random color via the following command:
(repeat) execute @r[type=armor_stand,r=9] ~ ~ ~ setblock ~ ~-2 ~ redstone_block

That "@r[]" is the magic sauce, it selects a random entity in the world that matches the given conditions. In this case, it finds an armor stand inside a radius of 9 blocks, and we've set up 16 armor stands, one for each wool color. Under the selected color, it places a redstone block (which powers the two command blocks on either side).
Random Pixel Selector
Placing the redstone block under the selected wool color triggers two more command blocks:
(impulse) execute @r[type=armor_stand] ~ ~ ~ setblock ~ ~3 ~ wool X
(impulse) setblock ~ ~ ~1 air

This first line uses our same magic @r command to choose any armor stand on the entire map (no radius restriction, so that includes the 40x40 grid), and places a wool of the selected color above its head. The X determines the color, and ranges from 0 to 15. The second command removes the redstone block so it is ready to go again.
I have 5 purple repeater blocks, and redstone works in "ticks" 20 times a second, so I'm placing 100 pixels per second (minus some color overlaps). I've timed it, and I usually get the entire grid covered in about 3 minutes.
This was fun, I'll try to look for other challenges that might also work in Minecraft. Huge thanks to lorgon111 for his YouTube Command Block tutorial series.
EDIT: Made some serious reductions in the size of the saved structure, now at 2,872 saved bytes:

Scooted things in a bit (in all 3 dimensions) so I could reduce the overall size of the saved area.
Changed the different colored wools to stone, they were just decorative anyway.
Removed the glowstone lamp.
Changed all air blocks to void blocks (the red squares).

Tested by pulling the saved structure into a new world, everything still works as designed.
EDIT 2: Read-only Dropbox link to the NBT structure file
Walk through is in my YouTube video, but here are the steps:

In Minecraft 1.12, create a new creative superflat world using the "Redstone Ready" preset. Make it peaceful mode.
Once the world exists, copy the NBT file into a new \structures folder you create under the current world save.
Back in the game, do /give @p structure_block, and /tp @p -12, 56, -22 to jump to the right spot to get started.
Dig a hole and place the structure block at -12, 55, -22.
Right-click the structure block, click the mode button to switch it to "Load".
Type in "random_pixels", turn "include entities" ON, and click "Load"
If it finds the structure file, it will preview the outline. Right-click again and click "load" to bring the structure into the world.
Press the button to run the setup routine.
When it completes, flip the switch to run the wool randomization.


Golf a bijection \$\mathbb{N}^n\to\mathbb{N}\$

APL (Dyalog Unicode), 13 10 bytes

(⊢+1⊥∘⍳+)/

Try it online!
Similar to other answers, since the Cantor pairing is bijective, compositing \$n-1\$ Cantor pairings is bijective as well.
(       )/  ⍝ reduce the input with following function
       +    ⍝ left argument + right argument
      ⍳     ⍝ the first left+right positive integers
   1⊥       ⍝ convert those from base 1 (sum)
 ⊢+         ⍝ + right argument


Python 2, length 14 12 10 9

M=max;X=exit;i=input();L=[0]*M(i)
for	a	in	i:L[a-1]=M(L[:a])+1
X(M(L))

Output is via exit code.

Try it online!

How it works

At all times, the array \$L\$ keeps track of the longest sorted subarrays encountered so far; \$L[a-1]\$ is the length of longest one that ends with \$a\$.

Initially, we haven't processed an array elements, so \$L\$ consists entirely of zeroes.

When processing the array element \$a\$, we first take the maximum of \$[L[0], \dots, L[a-1]]\$, which is length of the longest sorted subarray encountered so far that ends with \$a\$ or a smaller integer. Appending \$a\$ to such an array will keep it sorted, so the longest sorted subarray ending in \$a\$ is one element longer than that maximum. We update \$L[a-1]\$ with the computed value.

The final result is the maximum of \$L\$.


Retina, 3 bytes

.
1

Try it online!

Takes inputs separated by space (or any single non-newline character)

Replaces all digits with 1, and joins the resulting numbers with another 1.

Proof of correctness

Courtesy of Martin Ender

This operation computes a result with one more digit than the number of digits of the two numbers together; the only operation that could produce a result so big is exponentiation.
The result is a repunit (a number whose digits are all 1).
"It is know [sic] [...] that a repunit in base 10 cannot [...] be a perfect power." This means that this result can't be produced by exponentiation either.


Bash

echo Bonjour tout le monde

Outputs "Hello World" in a language called French.


Jelly, 11 9 bytes
ÆF‘%3,2ḄȦ

Try it online! or verify all test cases.
Background
In Elementary results on the binary quadratic form a² + ab + b², the author proves the following theorem about Löschian numbers.

Theorem 16. The necessary and sufficient condition of any non-negative integer to be in the form a² + ab + b² is that, in its prime factorization, all primes other than 3 that are not in the form (6k + 1) have even exponents.

As noted on the relevant OEIS page, since all integers are are congruent to 0, 1 or 2 modulo 3, the number 3 is the only prime that is congruent to 0, and all numbers of the form (6k + 1) are congruent to 1, the theorem can be stated alternatively as follows.
A non-negative integer n is a Löschian number if and only if all prime factors of n that are congruent to 2 modulo 3 have even exponents.
How it works
ÆF‘%3,2ḄȦ  Main link. Argument: n (integer)

ÆF         Yield the prime factorization of n, as prime-exponent pairs.
  ‘        Increment all primes and exponents, turning primes of the form 3k - 2
           into multiples of 3 and odd exponents into multiples of 2.
   %3,2    Reduce all incremented primes/exponents modulo 3/2.
           n is Löschian if and only if this does not result in a [0, 0] pair.
           Due to Jelly's form of vectorization, this yields [3, 2] if n = 1.
       Ḅ   Unbinary; convert each pair from base 2 to integer.
           Note that [x, y] = [0, 0] if and only if 2x + y = 0.
        Ȧ  All; return 1 if the result contains no zeroes, 0 otherwise.


C, 149 118 characters

Edited version (118 characters):

int G(int a,int b){a=abs(a);b=abs(b);int n=a*b?a*a+b*b:a+b,
d=2;for(;n/d/d&&n%d;d++);return n/d/d|n<2?0:(a+b&3)>2|a*b;}

This is a single function:

G(a,b) returns nonzero (true) if a+bi is a Gaussian prime, or zero (false) otherwise.

It folds the integer primality test into an expression n/d/d|n<2 hidden in the return value calculation. This golfed code also makes use of a*b as a substitute for a&&b (in other words a!=0 && b!=0) and other tricks involving operator precedence and integer division. For example n/d/d is a shorter way of saying n/d/d>=1, which is an overflow-safe way of saying n>=d*d or d*d<=n or in essence d<=sqrt(n).

Original version (149 characters):

int Q(int n){int d=2;for(;n/d/d&&n%d;d++);return n/d/d||n<2;}
int G(int a,int b){a=abs(a);b=abs(b);return!((a|b%4<3|Q(b))*(b|a%4<3|Q(a))*Q(a*a+b*b));}

Functions:

Q(n) returns 0 (false) if n is prime, or 1 (true) if n is nonprime. It is a helper function for G(a,b).
G(a,b) returns 1 (true) if a+bi is a Gaussian prime, or 0 (false) otherwise.

Sample output (scaled up 200%) for |a|,|b| ≤ 128:


Ruby 1.9, 67 65 characters
Ah, the old "keep randomizing until you generate something valid" technique...
$_=%w(r r n n b b q k).shuffle*''until/r.*k.*r/&&/b(..)*b/
$><<$_

(In Ruby 2.0, %w(r r n n b b q k) could be 'rrnnbbqk'.chars)