Max power of 2 such that 2^m divides n. (The ruler sequence)

Python 2, 46 bytes
Saved a couple of bytes thanks to nwellnhof.

lambda k:[len(bin(t+1&~t))-3for t in range(k)]

Try it online!

Python 2, 51 bytes

lambda k:[len(bin(t-~-(t&-~t)))-3for t in range(k)]

Try it online!
How?
The formula for a(k) is log2(k - (k & (k - 1))). That's quite fluffy, but fortunately it can be shortened significantly. In Python, floor(log2(N)) = len(bin(N)) - 3, because bin() appends 0b to the binary representation of an integer. As a side note, len(bin(N))-3 can be replaced by N.bit_length()-1, but that is not really beneficial for golfing purposes. That gives us the opportunity to get rid of the import math and the use of math.log. Another part that can be shortened is k & (k-1). Using more bitwise operations, we get k&~-k instead, and then we subtract this from the actual k. But that would make us iterate over the range [1, k], which would waste bytes because Python lacks inclusive ranges. In order to save a few bytes, we iterate over the integers in [0, k) instead and modify the formula, obtaining k+1-(k&-~k) = k-~-(k&-~k). However, than can be simplified further to k+1&~k (as  @nwellnhof pointed out).


Gol><>, 78 bytes

\<"2ss}}l2%?:}a`(:&K&:&]r&[r~H>.!01<<\

\<<10!.>H~r[&r]&:&K&:(`a}:?%2l}}ss2"<\

Try it online!

Verification!

A variation on the radiation hardened quine I posted yesterday. It's a little more complex since it needs to reverse the copied section using the undocumented [] operators, as well as redirect the pointer in one copy. If you're a little confused about why it doesn't look like a palindrome, remember that ><> is a palindrome itself.


Shell (ImageMagick, Tesseract), 18 bytes

file=golf_2014
echo -n UDQKMTMgNQruqCqo6riKiO6I | base64 -d > $file.pbm
convert -border 2x2 -bordercolor white -resize 300% -sharpen 0 -monochrome $file.pbm $file.png
tesseract $file.png $file digits
cat $file.txt
rm $file.pbm $file.png $file.txt

The image is 18 bytes and can be reproduced like this:

echo -n UDQKMTMgNQruqCqo6riKiO6I | base64 -d > 2014.pbm

It looks like this (this is a PNG copy, not the original):

After processing with ImageMagick, it looks like this:

Using ImageMagick version 6.6.9-7, Tesseract version 3.02. The PBM image was created in Gimp and edited with a hex editor.

This version requires jp2a.

file=golf_2014
echo -n UDQKMTMgNQruqCqo6riKiO6I | base64 -d > $file.pbm
convert -border 2x2 -bordercolor white -resize 300% -sharpen 0 -monochrome $file.pbm $file.png
tesseract $file.png $file digits
cat $file.txt
convert -background black -fill white -border 2x2 -bordercolor black -pointsize 100 label:$(cat $file.txt) $file.jpg
jp2a --chars=" $(cat $file.txt) " $file.jpg
rm $file.pbm $file.png $file.txt $file.jpg

It outputs something like this:

    2014444444102         01144444102              214441                 214441
   1             1      24           1            04    4                0     4
  1    410201     0    0    410004    1       2014      4              21      4
 24   42     0    4    4    0     1    0    24          4             04       4
  22222      1    1   0    42     0    4    2   4100    4            1   41    4
            1    42   0    4      2     2   2412   0    4          24   420    4
          04    42    0    1      2     2          0    4         0   40  0    4
       204    42      0    1      2     2          0    4       24   42   0    4
     21     12        0    4      0    42          0    4      2     411114     1112
    04   412          24    0     1    0           0    4      0                   0
  24     1111111110    1    42  21    4            0    4      200011111001    40002
  4               4     04    44     42            0    4                 0    4
 0                4      214       10              0    4                 0    4
  22222222222222222         222222                  22222                  22222


Visualise long multiplication with ASCII art

Mathematica 213 217 197 193 186 184 193 184 177
Code
a_~g~b_ :=
With[{e = IntegerDigits@b}, Column[Flatten@{a, UnderBar["x " <> IntegerString[b]],
Table[Row @@ {PadRight[{a Reverse[e][[i]]}, i, " "]}, {i, Length@e}], OverBar[a b]},
Alignment -> Right]]

Usage
g[845, 921]


Minimum operations to get from one number to another

JavaScript (ES6), 100 96 86 bytes

f=(a,b,[c,d,...e]=[a,''])=>c-b?f(a,b,[...e,c^1,d+1,c/2|c%2<<7,d+2,c%128*2|c>>7,d+0]):d
<div oninput=o.textContent=f(a.value,b.value).replace(/./g,c=&gt;`&lt;!&gt;`[c])>a: <input type=number min=0 max=255 value=0 id=a> b: <input type=number min=0 max=255 value=0 id=b>

Somewhat slow breadth-first search without double-checking. Slightly more efficient 114-byte version:

f=(a,b,c=[],[d,e,...g]=[a,''])=>c[d]?f(a,b,c,g):d-b?f(a,b,c,[...g,d^1,c[d]=e+1,d/2|d%2<<7,e+2,d%128*2|d>>7,e+0]):e
<div oninput=o.textContent=f(a.value,b.value).replace(/./g,c=&gt;`&lt;!&gt;`[c])>a: <input type=number min=0 max=255 value=0 id=a> b: <input type=number min=0 max=255 value=0 id=b>

Both versions encode <!> as 012 but the snippets decode this for you. Edit: Saved 10 utterly useless bytes thanks to @RickHitchcock.


Javascript: 272 268 233 232 201 192 189 188 178 180 characters

Thanks to @Sam for reducing it from 268 to 233 characters, and for @manatwork for another 1 char. @VadimR for pointing out a bug.

p=prompt(r=t='');s=' ';for(d=10;d--;r=s+q+s,t+=q.trim()?q+'\n':'')for(q='',i=0;i<p.length;)q+=' \\/v^'[p[i++]==d?4:(/\^|\\/.test(r[i-1])+2*/\^|\//.test(r[i+1]))*(r[i]==s)];alert(t)

Properly idented and somewhat ungolfed version with comments:

// The output initialization is just a golfing trick suggested by @manatwork.
input = prompt(state = output = '');
space = ' ';

// Repeat for each line, from the top (the highest peak, highest digit) to the floor (digit 1). Start at 10 to avoid a bug.
for (digit = 10; digit--;

      // Update the state of our automaton, at the end of the iteration.
      // Add a space after and before to simplify the future pattern recognization.
      state = space + line + space,

      // Add the line to the output if it is not an empty line, at the end of the iteration.
      output += line.trim() ? q + '\n' : '')
{ // This curly brace was added for readability, it is not in the golfed source.

  // Analyze each character in the current state to produce a new state, like a cellular automaton.
  for (line = '', i = 0; i < input.length;)
  { // This curly brace was added for readability, it is not in the golfed source.
    line +=

        // If the input is the current digit number, evaluate to 4 and put a peak in this character.
        // Otherwise evaluate this expression with those rules:
        // 1 means that the hill is higher only at right in the previous iteration, we do climb it to the right in this one.
        // 2 means that the hill is higher only at left in the previous iteration, we do climb it to the left in this one.
        // 3 means that the hill is higher at both sides in the previous iteration, we are in a v-shaped valley.
        // 0 means nothing to do here. If the middle is not a space, it will be multiplied by 0 and become 0.
        ' \\/v^'[input[i++] == digit ? 4 : (/\^|\\/.test(state[i - 1]) + 2 * /\^|\//.test(state[i + 1])) * (r[i] == space)];
    } // This curly brace was added for readability, it is not in the golfed source.
} // This curly brace was added for readability, it is not in the golfed source.

// Give the final output.
alert(output);

As you may note from the code, this works as a cellular automaton, where each cells checks for a number in the input, looks to itself and to its two neighbours to decide what the next iteration will be. At each moment a cell may be a ^, /, \, v or . The input provided in the test cases produces the expected output.

Note that using the alert box sucks, since it normally does not have a monospaced font. You may copy & paste the text from the alert box to somewhere else for a better appreciation of the output, or you may replace the last line alert by console.log, but since this is code-golf, alert is shorter.

Further, it does not validates anything in the input. It simply considers unrecognized characters as spaces the same way it does to . (in fact . is an unrecognized character too).


PowerShell v2+ & Default Browser, 215 217 bytes

$l=date;for(){if(($x=([xml](iwr xkcd.com/rss.xml)).rss.channel.item[0]).pubdate-ge$l){if(($y=$x.description)-match'img src'){saps ($y-replace'<img src="'-replace'" .*')}else{echo "interactive comic"}}$l=date}

WARNING: Running this as-is will likely make Randall very mad at you, due to the high frequency of calls to the RSS feed ... so, y'know, don't do that. (See below for an alternate version that can be used in a one-off manner)

Sets the $last time we displayed a comic to the result of Get-Date. Then, enter an infinite for loop.

Each iteration, we iwr (alias for Invoke-WebRequest) the RSS feed for the site. That's parsed as [xml] (yes, PowerShell can cast as XML), and the .rss.channel.item[0] thereof (i.e., the newest) is stored in $x. If the .pubDate is -ge$l (i.e., newer than the last comic we showed), we have a new comic to display.

So, we first check the .description field (saved in $y), to see if it matches img src. If so, we parse out the img from $y, and feed that to saps (alias for Start-Process). Since it's a URI, this relies on Windows' default behavior for "executing" a URI, that is, it opens the default browser to that location. (If this is too cheaty, let me know and we can iwr down the actual image and save it.)

Otherwise, we echo out that we've got an interactive comic.

In either case, we update our $l date to "now" since we just displayed a comic.

Saved 7 bytes thanks to Matt for reminding me that http:// can be implied

"Safe" version that executes just once and displays the latest comic

$l=(date).AddDays(-3);if(($x=([xml](iwr http://xkcd.com/rss.xml)).rss.channel.item[0]).pubdate-ge$l){if(($y=$x.description)-match'img src'){saps ($y-replace'<img src="'-replace'" .*')}else{echo "interactive comic"}}

You can run this one safely to see how the logic works. It'll only execute once and only display the latest comic.


C#, 168 144 141 120 Bytes
using System.Linq;i=>y=>string.Join("\n",y?i.Split('\n').Reverse():i.Split('\n').Select(x=>string.Concat(x.Reverse())));

New version utilizes the obvious string.Join overload that takes an IEnumerable, the first solution was using it inadvertently I was just able to use it for the else side of the ternary as well.
Update:
New version is an anonymous lambda and uses currying to save 21 bytes total. This changes usage to be f("text")(false) where f is the anonymous function.
Ungolfed:
using System.Linq;

//Using currying to save one byte
input => IsYReflect =>
         //Lambda makes return implicit
         string.Join("\n", IsYReflect
            //Y Reflect, just need to reverse the array
            ? input.Split('\n').Reverse()
            //X Reflect, reverse each line into an IEnumerable
            : input.Split('\n').Select(x => string.Concat(x.Reverse())));


I've tried to emulate features of real-world large systems here. I use encapsulation and abstraction to handle the different operations to the database, like getting an account balance and transferring money. The code also has a basic test suite for those functions. However, one programmer has taken advantage of recent changes in the project requirements to add $1 to their account with every input. There's even plausible deniability.

# {account number: balance in USD}
ndb = {
    999222: 10000.56,
    888333: 335.13,
    555222: 56.0,
    222111: 123.55,
    123456: 0.0
}

# {hashed account ID: balance in USD}
# (hash the IDs because integer-based hash tables are fast, and a
# bunch of strcmp's would be slow)
# 2014-10-20: phased out alphabetic account IDs for numeric ones
# keeping the old data here because Murphy's Law guarantees we'll
# need it right after it's deleted. -- RJO
odb = {
#   hash('mEYjxG'): 42.0,
#   hash('lDCIqp'): 1337.0,
#   hash('QDxkwD'): 123456.0,
#   hash('jSWlMM'): 0.0,
#   hash('siYWKC'): 20.14
}

def balance(a, db):
    try:
        return db[hash(a)]
    except:
        raise ValueError('no such account:', a)

def credit(a, n, db):
    if n <= 0:
        raise ValueError('invalid amount: ' + str(n))
    try:
        db[hash(a)] += n
    except:
        raise ValueError('no such account:', a)

# 2012-10-20: parameterizing the database ops to handle both
# old and new databases is a pain in the neck. -- RJO

def debit(a, n, db):
    if n <= 0:
        raise ValueError('invalid amount: ' + str(n))
    if balance(a, db) < n:
        raise ValueError('insufficient funds: below ' + str(n))
    try:
        db[hash(a)] -= n
    except:
        raise ValueError('no such account', a)

def transfer(a, b, n, db):
    if a == b:
        raise ValueError('same account', a)
    debit(a, n, db)
    credit(b, n, db)

# 2014-10-20: tests need to be updated with new account IDs, but
# it's Friday afternoon. -- RJO
def test(db):
    # back up database prior to changes
    bdb = db.copy()
    # test database functions
    try:
        # test 'balance'
        account = 'does not exist'
        try:
            bal = balance(account, db)
            assert(db[hash(account)] == bal)
        except ValueError:
            assert(hash(account) not in db)
        # test 'credit'
        account = 'jSWlMM'
        start = balance(account, db)
        delta = 1
        credit(account, delta, db)
        assert(balance(account, db) == start + delta)
        # test 'debit'
        account = 'lDCIqp'
        start = balance(account, db)
        delta = 1337
        try:
            debit(account, delta, db)
            assert(balance(account, db) == start - delta)
        except ValueError:
            assert(balance(account, db) < delta)
        # test 'transfer'
        account1 = 'mEYjxG'
        account2 = 'siYWKC'
        start1 = balance(account1, db)
        start2 = balance(account2, db)
        delta = 123
        try:
            transfer(account1, account2, delta, db)
            assert(balance(account1, db) == start - delta)
            assert(balance(account2, db) == start + delta)
        except ValueError:
            assert(balance(account1, db) < delta)
    except Exception as ex:
        # log errors
        print ex.message
    finally:
        # roll back all changes
        odb.update(bdb)

# interactive transfers
while True:
    # test everything
    test(ndb)
    # get input
    print 'Transfer $N from A to B:'
    line = raw_input('Enter "A B N" or 0: ')
    # check for exit
    if line == '0':
        print 'Exit'
        # print account balances
        for a in ndb:
            print 'Account', a, 'has', balance(a, ndb), '$'
        break
    # parse input
    try:
        a, b, n = line.split()
        a = int(a)
        b = int(b)
        n = float(n)
    except:
        print 'Bad input!'
        continue
    # make transfer
    try:
        transfer(a, b, n, ndb)
        print 'Transferred', n, '$ from account', a, 'to', b
    except ValueError as e:
        print e

And here's a sample run:

Transfer $N from A to B:
Enter "A B N" or 0: 999222 222111 500
Transferred 500.0 $ from account 999222 to 222111

Transfer $N from A to B:
Enter "A B N" or 0: 555222 888333 12
Transferred 12.0 $ from account 555222 to 888333

Transfer $N from A to B:
Enter "A B N" or 0: 222111 555222 14
Transferred 14.0 $ from account 222111 to 555222

Transfer $N from A to B:
Enter "A B N" or 0: 0
Exit
Account 555222 has 58.0 $
Account 123456 has 4.0 $
Account 888333 has 347.13 $
Account 999222 has 9500.56 $
Account 222111 has 609.55 $


Largest and smallest values from concatenated integers

CJam, 14 13 bytes

qS/e!:s$(N@W=

Pretty straight forward. This is how it works:

qS/                  e# Split the input on spaces
   e!                e# Get all permutations of the input numbers
     :s              e# Join each permutation order into a single string
       $             e# Sort them. This sorts the strings based on each digit's value
        (N@W=        e# Choose the first and the last out of the array separated by '\n'

Try it online here


Haskell, 60 55 54 52 bytes

After a drawing and programming a lot of examples, it occured to me that this is the same as the problem of the rooks:

  On a \$(n+1) \times (n+1)\$ chessboard, how many ways are there for a rook to go from \$(0,0)\$ to \$(n,n)\$ by just moving right \$+(1,0)\$ or up \$+(0,1)\$?

Basically you have the top and the bottom line of the \$1 \times n\$ grid. Now you have to fill in the non-horizontal line. Each triangle must have two non-horizontal lines. Whether one of its sides is part of the top or the bottom line corresponds to the direction and length you'd go in the rooks problem. This is OEIS A051708. As an illustration of this correspondence consider following examples. Here the top line corresponds to up-moves, while the bottom line corresponds to right-moves.

Thanks @PeterTaylor for -6 bytes and @PostLeftGarfHunter for -2 bytes!

b 0=1
b 1=2
b n=div((10*n-6)*b(n-1)-9*(n-2)*b(n-2))n

Try it online!


Calculate the n-th iterate of a polynomial for a specific value; fⁿ(x)

Octave, 49 bytes

@(p,x,n)(f=@(r,m){@()p(r(r,m-1)),x}{~m+1}())(f,n)

Try it online!
Or, taking coefficients:
Octave, 75 57 bytes

@(p,x,n)(f=@(f,n){@()polyval(p,f(f,n-1)),x}{~n+1}())(f,n)

Try it online!
A special thanks for Suever over at StackOverflow, for this answer some time ago on a question of mine, proving that a recursive anonymous function is possible.
This defines an anonymous function, which is a wrapper for a recursive anonymous function; something which is not a native Octave concept, and requires some fancy cell array indexing.
As a bonus, the second version is a nice lesson in variable scoping in Octave. All instances of r can legally be replaced by f, which then simply overwrites the existing f in the most local scope (similar for n)
Explanation
@(p,x,n)(f=@(r,m){@()p(r(r,m-1)),x}{~m+1}())(f,n)
@(p,x,n)         .                ..    .  ..   .   % Defines main anonymous function
        (f=@(r,m).                ..    .  ).   .   % Defines recursive anonymous function
                 .                ..    .   .   .   %  r: Handle ('pointer') to recursive function
                 .                ..    .   .   .   %  m: Current recursion depth (counting from n to 0)
                 .                ..    .   (f,n)   % And call it, with
                 .                ..    .           %  r=f (handle to itself)
                 .                ..    .           %  m=n (initial recursion)
                 {                }{    }           % Create and index into cell array
                                    ~m+1            %  Index: for m>0: 1; for m==0: 2.
                                ,x                  %  Index 2: final recursion, just return x.
                  @()                               %  Index 1: define anonymous function, taking no inputs.
                     p(        )                    %   which evaluates the polynomial
                       r(     )                     %    of the recursive function call
                         r,m-1                      %     which is called with r
                                                    %     and recursion depth m-1
                                                    %     (until m=0, see above)
                                         ()         % Evaluate the result of the cell array indexing operation.
                                                    %  which is either the anonymous function
                                                    %  or the constant `x`.

The key to this is that anonymous functions are not evaluated when they are defined. So, the @(), which seems a bit superfluous since it defines an anonymous function which is called with () directly after, is actually strictly necessary. It is not called unless it is selected by the indexing statement.
Octave, 39 bytes (boring way)

function x=f(p,x,n)for i=1:n;o=p(o);end

Just for completeness, the Octave solution with the shortest bytecount.
Yawn..


Dihedral group D4 composition with custom labels

Ruby, 18 bytes

->a,b{a+b*~0**a&7}

Ungolfed

->a,b{ (a+b*(-1)**a) % 8}
# for operator precedence reasons,
#-1 is represented as ~0 in the golfed version

Try it online!

Uses the following coding numbers 0 to 7

In order native to the code:

Native     Effect                    Codes per
Code                                 Question
0          rotate 0 anticlockwise    1C
1 /        flip in y=x               7E
2 /|       rotate 90 anticlockwise   2O
3 /|/      flip in x axis            5U
4 /|/|     rotate 180 anticlockwise  3M
5 /|/|/    flip in y=-x              8R
6 /|/|/|   rotate 270 anticlockwise  4P
7 /|/|/|/  flip in y axis            6T

In order per the question

Native     Effect                    Codes per
Code                                 Question
0          rotate 0 anticlockwise    1C
2 /|       rotate 90 anticlockwise   2O
4 /|/|     rotate 180 anticlockwise  3M
6 /|/|/|   rotate 270 anticlockwise  4P
3 /|/      flip in x axis            5U
7 /|/|/|/  flip in y axis            6T
1 /        flip in y=x               7E
5 /|/|/    flip in y=-x              8R

Explanation

/ represents a flip in the line y=x and | represents a flip in the y axis.

It is possible to generate any of the symmetries of the group D4 by alternately flipping in these two lines For example / followed by | gives /| which is a rotation of 90 degrees anticlockwise.

The total number of consecutive flips gives a very convenient representation for arithmetic manipulation.

If the first move is a rotation, we can simply add the number of flips:

Rotate 90 degrees   +  Rotate 180 degrees = Rotate 270 degrees
/|                     /|/|                 /|/|/|

Rotate 90 degress   +  Flip in y=x        = Flip in x axis
/|                    /                     /|/

If the first move is a reflection, we find we have some identical reflections / and | symbols next to each other. As reflection is self inverse we can cancel out these flips one by one. So we need to subtract one move from the other

Flip in x axis     +  Flip in y=x        = Rotate 90 degrees
/|/                   /                    /|/ / (cancels to) /|

Flip in x axis     +  Rotate 90 degrees  = Flip in y=x
/|/                   /|                   /|/ /| (cancels to ) /


Mathematica, 301 288 258 bytes

" "~(s=If[#2==0,"",#~StringRepeat~#2]&)~3<>{"="~s~21,"
",s[" ",12-#]<>{")","v "~s~#,"v(
"}&/@9~Range~12,"~"~s~27,"
",s[(x=(u=": ")~s~13<>":
")<>{y=u<>{z=": ### ",v=u~s~5,w=z<>": :
"},y,y,x},#-1],v,"_"~s~7," ",v,"
",m=u<>{z,u,n="I     I ",w},m,m,v,n,w}&

Pure function which takes a positive integer and outputs a string. The output string won't look right because Mathematica apparently doesn't display monospace fonts as monospace:

For reasons I don't quite understand, it does format as monospace if you Print the string:

Edit: Saved several bytes by not including "   " at the beginning of each line. Changed the definition of s to handle the case where there is only one floor (StringRepeat doesn't like repeating a string 0 times).

Edit 2: Thanks to LegionMammal978 and the fact that StringJoin is Listable, this is now an incomprehensible nightmare of nested lists and also 30 bytes shorter.


Arranging arbitrary rectangles to fill a space

Haskell, 226 bytes

((y,z):l)&(w,x)|x*y<1=(w+y,x+z):l
(q:l)&p=p:q:l
(p@(u,v):r@(y,z):l)%q@(w,x)=[((y-w,z):l)&q&(u,v-x)|w<=y,x<=v]++[p:m|m<-(r:l)%q]
_%_=[]
g m(p:n)l=any(g[]$m++n)(l%p)||g(p:m)n l
g[]_[_,_,_]=0<1
g _[]_=0<0
($[(0,9^9),(9^9,0)]).g[]

Try it on Ideone

How it works

This recursively searches for all partial tilings whose shape is a Young diagram, adding one rectangle at a time, and checks whether any of the final results are rectangles.

To see that any tiling of a rectangle can be built this way: in any tiling of a nonempty Young diagram, let R be the set of rectangles in the tiling whose southwest corner does not touch any other rectangle.  Since each concave vertex of the Young diagram is edge-adjacent (not merely corner-adjacent) to at most one rectangle in R, and the number of these concave vertices is one less than the number of rectangles in R, there must be at least one rectangle in R that is edge-adjacent to none of these concave vertices.  Removing it yields another Young diagram, so we can proceed by induction.


Retina 0.8.2, 30 29 bytes

(.)\1|[DEFHKO][CEF]|[JLN]C|BA

Try it online! Link includes test cases.


Find the sum of all numbers below n that are a multiple of some set of numbers

Jelly, 6 bytes

ḍþṖḅTS

Try it online!

How it works

ḍþṖḅTS  Main link. Left argument: D (array). Right argument: n (integer)

ḍþ       Divisible table; test each k in [1, ..., n] for divisibility by all
        integers d in D.
  Ṗ     Pop; discard the last Boolean array, which corresponds to n.
   ḅ    Unbase; convert the Boolean arrays of base n to integer. This yields a
        non-zero value (truthy) and and only if the corresponding integer k is
        divisible by at least one d in D.
    T   Truth; yield the array of all indices of truthy elements.
     S  Compute their sum.


PowerShell v2+, 172 153 148 145 142 131 123 bytes (81 chars)

($a=""+0..7)
$b='┌┘'
"│$b$('┌┼─┘'*3)
└┼┐$('│└─┐'*3)
$b$('└┼─┐'*3)│
│ $($b*6)│"
$a

I golfed the weaving further, eliminating the need for several variables by using inline code blocks. This is probably within a few bytes of optimal.

We start by setting $a equal to the range 0..7 that's been joined together with spaces. This is because the default $ofs (Output Field Separator) for an array is a space, so when the array is stringified with ""+ (with an operator like this, PowerShell will try to implicitly cast the right-hand object as the left-hand object), the result is the range space-separated.

That's encapsulated in parens, which adds the result onto the pipeline. We then setup a one helper variable $b, followed by four lines of output with the appropriate variable in place (split with literal newlines), and using inline code-blocks for repeat sections, followed by $a again. The four lines and $a are also placed on the pipeline, and output is implicit at the end.

PS C:\Tools\Scripts\golfing> .\visualize-bit-weaving.ps1
0 1 2 3 4 5 6 7
│┌┘┌┼─┘┌┼─┘┌┼─┘
└┼┐│└─┐│└─┐│└─┐
┌┘└┼─┐└┼─┐└┼─┐│
│ ┌┘┌┘┌┘┌┘┌┘┌┘│
0 1 2 3 4 5 6 7


Wolfram Language (Mathematica), 92 91 bytes
Print@@@CellularAutomaton[{7049487784884,{3,{a={0,3,0},3-2a/3,a}},{1,1}},{j={{1}},0},{j#}]&

A perfect challenge to use Mathematica's builtin CellularAutomaton!
Try it online!
Empty = 0, Awake = 1, Sleeping = 2
Animation of the first 256 iterations (white = empty, gray = awake, black = sleeping):

Explanation
CellularAutomaton[ ... ]

Run CellularAutomaton with specifications...
{7049487784884,{3,{a={0,3,0},3-2a/3,a}},{1,1}}

Apply the 3-color totalistic rule 7049487784884, with Von Neumann neighborhood...
{j={{1}},0}

On a board with a single 1 in the middle, with a background of 0s...
{j#}

Repeat <input> times ({j#} evaluates to {{{#}}}). The array automatically expands if a cell outside of the border is not the same as the background
7049487784884

This rule comes from the base-3 number 220221220221220221220221220, which means "change all 1 or 2 to 2, and change 0 to 1 if and only if there is an odd number of 1s around it."
Print@@@

Print the array.
Semi-proof of "'odd 1s' is equivalent to 'exactly one 1'":
Consider this 5x5 grid of pixels. White is a 0 or a 2 cell (non-awake pixels), and gray is a 1 cell.

If a 1 cell was generated around three 0 cells, then the grid must look like this: it has three 1s arranged in a U-shape (or a rotated version) as follows:

Due to the self-similarity of this cellular automaton, any pattern that appears in the cellular automaton must appear on the diagonal (by induction). However, this pattern is not diagonally symmetric. i.e. it cannot occur on the diagonal and cannot appear anywhere on the cellular automaton.
Awake/Sleeping are equivalent
Note that a 0 cell cannot be surrounded by exactly one or three 2 cells and rest 0 cells, since that would imply that some steps prior, the cell had a neighbor of one or three 1 cells -- and must have turned into a 1 already (contradiction). Therefore, it is okay to ignore the distinction between 1 and 2 and state 'change all 1 to 1, and a 0 to a 1 if and only if it has an odd number of nonzero neighbors.'
The resulting cellular automaton is indeed identical to the original, the only difference being there is no distinction between "awake" and "asleep" drunkards. This pattern is described in OEIS A169707.
Print@@@CellularAutomaton[{750,{2,{a={0,2,0},2-a/2,a}},{1,1}},{j={{1}},0},{j#}]&

Try it online!
Side-by-side comparison of the first 16 iterations:

Adding two consecutive iterations gives a result that follows the challenge specs (94 bytes):
Print@@@Plus@@CellularAutomaton[{750,{2,{a={0,2,0},2-a/2,a}},{1,1}},{{{1}},0},{Ramp@{#-1,#}}]&

Try it online!


Write a function that reduces compositions of linear operators

GolfScript, 41 40 23 19 characters
{2,0+%/-{@*+}++}:k;

Thanks to Peter Taylor for pointing out this solution. Accepts two function bodies as arguments.
The following examples show how to use function k:
# As function
{2*3+} {3*4+} k         # => {11 6 @*+}

# Apply to value
5 {2*3+} {3*4+} k ~     # => 41

If one wants to retain the original output format, the following 22 character solution is possible:
{2,0+%/-{*}+\+{+}+}:k;

{2*3+} {3*4+} k         # => {6 * 11 +}

Explanation of the code:
{                       # on stack are functions g h
  2,                    # build array [0 1] -> g h [0 1]
  0+                    # append 0 -> g h [0 1 0]
  %                     # apply function h to each element -> g [h(0) h(1) h(0)]
  /                     # apply function g to each element
                        # and break up the array -> g(h(0)) g(h(1)) g(h(0))
  -                     # subtract last two -> g(h(0)) g(h(1))-g(h(0))
  {@*+}++               # append function body to these values
}:k;                    # save function to variable k


Python 2, 26 bytes

from textwrap import*
fill

Try it online!

Meh... built-ins are boring... instead, have a nice 87-byte solution here:

s,n=input()
x=''
for i in s.split():c=n<len(x+i);exec'print x'*c;x=x*-~-c+i+' '
print x

Try it online!

Outputs trailing spaces.


Matlab, 36 35 29 bytes
@(T,N)find(sum(T*T>-T,2)>N-2)

Let us find out if i is a king. Then for each j the value T[i][j]==1 OR there is a k such that T[i][k] * T[k][l] == 1. But the second condition can also be replaced by sum_over_k(T[i][k] * T[k][l])>0, but this is just an entry of the matrix T*T (if you consider T as a matrix). The OR can then be replayed by adding T to that result, so we just have to check if n-1 values of the row i of T*T+T are greater than zero, to see whether i is king. This is exactly what my function does.
(This is MATLAB, so the indices are 1-based.)
The MATLAB matrices should be encoded with semicolons as line delimiters:
[[0,0,0,0,0];[1,0,1,1,0];[1,0,0,0,1];[1,0,1,0,1];[1,1,0,0,0]]


Mathematica, 2535 bytes
Taken from here (hence why it's community wiki). Not really that golfed. View the provided link for the author's explanation of his code.
Also, I'm no Mathematica expert, but I bet Martin could do wonders on the code length. I don't even understand the math behind it.
I left it readable, but if the question doesn't get closed, I'll golf it past readability and move the 2 other parameters inside the caller function.
Currently invalid, feel free to help improve it:

I think this uses lines rather than arcs.

Centered on a face, rather than a vertex.

HyperbolicLine[{{Px_, Py_}, {Qx_, Qy_}}] :=
 If[N[Chop[Px Qy - Py Qx]] =!= 0.,
  Circle[OrthoCentre[{{Px, Py}, {Qx, Qy}}],
   OrthoRadius[{{Px, Py}, {Qx, Qy}}],
   OrthoAngles[{{Px, Py}, {Qx, Qy}}]], Line[{{Px, Py}, {Qx, Qy}}]]

OrthoCentre[{{Px_, Py_}, {Qx_, Qy_}}] :=
 With[{d = 2 Px Qy - 2 Py Qx, p = 1 + Px^2, q = 1 + Qx^2 + Qy^2},
  If[N[d] =!= 0., {p Qy + Py^2 Qy - Py q, -p Qx - Py^2 Qx + Px q}/d,
   ComplexInfinity]]

OrthoRadius[{{Px_, Py_}, {Qx_, Qy_}}] :=
 If[N[Chop[Px Qy - Py Qx]] =!= 0.,
  Sqrt[Total[OrthoCentre[{{Px, Py}, {Qx, Qy}}]^2] - 1], Infinity]

OrthoAngles[{{Px_, Py_}, {Qx_, Qy_}}] :=
 Block[{a, b, c = OrthoCentre[{{Px, Py}, {Qx, Qy}}]},
  If[(a = N[Apply[ArcTan, {Px, Py} - c]]) < 0., a = a + 2 \[Pi]];
  If[(b = N[Apply[ArcTan, {Qx, Qy} - c]]) < 0.,
   b = b + 2 \[Pi]]; {a, b} = Sort[{a, b}];
  If[b - a > \[Pi], {b, a + 2 \[Pi]}, {a, b}]]

Inversion[Circle[{Cx_, Cy_}, r_], {Px_, Py_}] := {Cx, Cy} +
  r^2 {Px - Cx, Py - Cy}/((Cx - Px)^2 + (Cy - Py)^2)
Inversion[Circle[{Cx_, Cy_}, r_, {a_, b_}], {Px_, Py_}] := {Cx, Cy} +
  r^2 {Px - Cx, Py - Cy}/((Cx - Px)^2 + (Cy - Py)^2)

Inversion[Circle[{Cx_, Cy_}, r_, {a_, b_}], p_Line] :=
 Map[Inversion[Circle[{Cx, Cy}, r], #] &, p, {2}]

Inversion[Circle[{Cx_, Cy_}, r_, {a_, b_}], p_Polygon] :=
 Map[Inversion[Circle[{Cx, Cy}, r], #] &, p, {2}]

Inversion[Line[{{Px_, Py_}, {Qx_, Qy_}}], {Ux_, Uy_}] :=
 With[{u = Px - Qx,
   v = Qy - Py}, {-Ux (v^2 - u^2) - 2 u v Uy,
    Uy (v^2 - u^2) - 2 u v Ux}/(u^2 + v^2)]
Inversion[Line[{{Px_, Py_}, {Qx_, Qy_}}], p_Polygon] :=
 Map[Inversion[Line[{{Px, Py}, {Qx, Qy}}], #] &, p, {2}]

Inversion[Circle[{Cx_, Cy_}, r_], c_List] :=
 Map[Inversion[Circle[{Cx, Cy}, r], #] &, c]

PolygonInvert[p_Polygon] :=
 Map[Inversion[HyperbolicLine[#], p] &,
  Partition[Join[p[[1]], {p[[1, 1]]}], 2, 1]]
PolygonInvert[p_List] := Flatten[Map[PolygonInvert[#] &, p]]

LineRule = Polygon[x_] :> Line[Join[x, {x[[1]]}]];
HyperbolicLineRule =
  Polygon[x_] :>
   Map[HyperbolicLine, Partition[Join[x, {x[[1]]}], 2, 1]];

CentralPolygon[p_Integer, q_Integer, \[Phi]_: 0] :=
 With[{r = (Cot[\[Pi]/p] Cot[\[Pi]/q] - 1)/
     Sqrt[Cot[\[Pi]/p]^2 Cot[\[Pi]/q]^2 - 1], \[Theta] = \[Pi] Range[
       1, 2 p - 1, 2]/p},
  r Map[{{Cos[\[Phi]], -Sin[\[Phi]]}, {Sin[\[Phi]], Cos[\[Phi]]}}.# &,
     Transpose[{Cos[\[Theta]], Sin[\[Theta]]}]]]

PolygonUnion[p_Polygon, tol_: 10.^-10] := p
PolygonUnion[p_List, tol_: 10.^-10] :=
 With[{q = p /. Polygon[x_] :> N[Polygon[Round[x, 10.^-10]]]},
  DeleteDuplicates[q]]
HyperbolicTessellation[p_Integer, q_Integer, \[Phi]_, k_Integer,
  t_: 10.^-10] :=
 Map[PolygonUnion[#, t] &,
   NestList[PolygonInvert, Polygon[CentralPolygon[p, q, \[Phi]]],
     k][[{-2, -1}]]] /; k > 0

HyperbolicTessellation[p_Integer, q_Integer, \[Phi]_, k_Integer,
  t_: 10.^-10] := Polygon[CentralPolygon[p, q, \[Phi]]] /; k == 0
HyperbolicTessellationGraphics[p_Integer, q_Integer, \[Phi]_,
  k_Integer, rule_RuleDelayed, opts___] :=
 Graphics[{Circle[{0, 0}, 1],
   HyperbolicTessellation[p, q, \[Phi], k, 10.^-10] /. rule}, opts]

Called like:
HyperbolicTessellationGraphics[3, 7, 0., 7, HyperbolicLineRule, ImageSize -> 300, PlotLabel -> "{7,7}"]


Python 2, 78 bytes

e=sum(ord(e[0])/4+ord(e[0])%4*64for e in input());print chr([e,~e][e>255]%256)

Try it online!

-8 bytes thanks to Jonathan Frech


Mathematica, 29 bytes

How about an arithmetic solution?

IntegerExponent[9#+#~Mod~10]&

I'm very pleased to see that this beats the straight-forward Mathematica approach.

Explanation

The code itself computes 9*n + n%10 and then finds the largest power of 10 that divides the input, or in other words, counts the trailing zeros. We need to show if n ends in k repeated digits, that 9*n + n%10 has k trailing zeros.

Rep-digits are most easily expressed mathematically by dividing a number like 99999 (which is 105-1) by 9 and then multiplying by the repeated digit. So we can write n = m*10k + d*(10k-1)/9, where m ≢ d (mod 10), to ensure that n doesn't end in more than k repeated digits. Note that d = n%10.

Let's plug that into our formula 9*n + n%10. We get 9*m*10k + d*(10k-1) + d. The d at the end is cancelled, so we're left with: 9*m*10k + d*10k = (9*m + d)*10k. But 9 ≡ -1 (mod 10), so 9*m + d ≡ d - m (mod 10). But we've asserted that m ≢ d (mod 10) and hence d - m ≢ 0 (mod 10).

In other words, we've shown that 9*m + d is not divisible by 10 and therefore, the largest power of 10 that divides 9*n + n%10 = (9*m + d)*10k is k, the number of trailing repeated digits.

As a bonus, this solution prints the correct result, ∞, for input 0.


Lua 5.2, 581 Bytes

Again, slow start with so ineffective language for golfing and with ineffective algorithm. But I will improve :)

r=io.read w=io.write F=r()f=F:find("F")o={[1]=F}W=#F i=2
repeat s=r()if s==nil then break end o[i]={}for j=1,W do o[i][j]=s:sub(j,j)end i=i+1 until false
function e(i,j)
local k,l,b,c=j+1,j-1,false
if i>=#o or(o[i+1][j]==" "and e(i+1,j)==0)then return 0 end
while k<=W do
b=b or o[i][k]=="X"
if b or(o[i+1][k]==" "and e(i+1,k)==0)then break end
k=k+1 end
while l>0 do
c=c or o[i][l]=="X"
if c or(o[i+1][l]==" "and e(i+1,l)==0)then break end
l=l-1 end
if b and c then for m=l+1,k-1 do o[i][m]="~"end return 1 end
return 0 end
e(1,f)for i=2,#o do for j=1,W do w(o[i][j])end w"\n"end

Test cases (with water source):

---------
    F
  X~~X
  XXXX
--------------------
         F
   X     X~X
X  X X  XX~X~~XX~~~X
XXXXXX XXXXXXXXXXXXX
--------------------
   F
   X     X X
X~~X~X  XX X  XX   X
XXXXXX XXXXXXXXXXXXX
--------------------------------------------------
                F
              X~~~~~~~~~~~~~X
              X~~~~~~~~~~~~~X~X
X~~~~~~~~~~~~XXX~~~~~~~X~~~~X~X~~~~~~~~~~~X    X
X~~~X~~~~~XXXXXXX~~~~~~X~~~~XXX~~~~~XXXXXXX X  X
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX XXXXXX

from bash it is possible to test this way, but it doesn't look so nice:

$ echo "    F
  X  X
  XXXX   " | lua f.lua


Haskell, 131 bytes

This solution is in the form of an infix function # with type String -> String -> String

Input is accepted through the two string arguments. The format for spotter input is 1 x where x is the guess.Output is given as a string. In the case where both units survive, the returned string contains both separated by a space.

My original solution was unfortunately bugged and the fix cost me a few bytes.

('1':' ':x)#y|x==y="1"|1>0="1 "++y
"S"#"10"="S"
"3"#"B"="3"
_#"B"="B"
x#y|x==y=[]
t@"10"#_=t
_#t@"10"=t
"S"#x=x
x#"S"=x
x#y=max x y


05AB1E, 10 bytes

Code:

ÝηO3ãʒOQ}¬

Explanation:

Ý             # Compute the range [0 .. input]
 η            # Get the prefixes
  O           # Sum each prefix to get the triangle numbers
   3ã         # Cartesian repeat 3 times
     ʒ  }     # Keep elements that
      OQ      #   have the same sum as the input
         ¬    # Retrieve the first element

Uses the 05AB1E encoding. Try it online!


JavaScript (ES7),  99 79 74  72 bytes
Takes input as (n)(b). Returns a Boolean value.

n=>g=([d,...b],x=0,m=2**n-2)=>d?[x+d,x-d+n].some(y=>g(b,y%=n,m^1<<y)):!m

Try it online!
How?
Instead of using an array for \$a_i\$, we use a bitmask \$m\$ initialized to \$2^n-2\$ and a bit pointer \$x\$ initialized to \$0\$ (i.e. pointing to the least significant bit).
For instance: for \$n=4\$, we start with \$m=4^2-2=14=1110_2\$. Because the LSB is our starting position, it is cleared right away to mark it as visited.
The main part of the code is a recursive search in a binary tree: for each \$b_i\$, we move the bit pointer to either \$x+b_i\$ or \$x-b_i\$ (wrapping around modulo \$n\$) and toggle the bit at the new position in \$m\$.
We have \$m=0\$ on a leaf node iff all positions have been reached exactly once.


Java (n=8)

import java.util.*;
import java.util.concurrent.*;

public class HankelCombinatorics {
    public static final int NUM_THREADS = 8;

    private static final int[] FACT = new int[13];
    static {
        FACT[0] = 1;
        for (int i = 1; i < FACT.length; i++) FACT[i] = i * FACT[i-1];
    }

    public static void main(String[] args) {
        long prevElapsed = 0, start = System.nanoTime();
        for (int i = 1; i < 12; i++) {
            long count = count(i), elapsed = System.nanoTime() - start;
            System.out.format("%d in %dms, total elapsed %dms\n", count, (elapsed - prevElapsed) / 1000000, elapsed / 1000000);
            prevElapsed = elapsed;
        }
    }

    @SuppressWarnings("unchecked")
    private static long count(int n) {
        int[][] perms = new int[FACT[n]][];
        genPermsInner(0, 0, new int[n], perms, 0);

        // We partition by canonical representation of the row sum multiset, discarding any with a density > 50%.
        Map<CanonicalMatrix, Map<CanonicalMatrix, Integer>> part = new HashMap<CanonicalMatrix, Map<CanonicalMatrix, Integer>>();
        for (int m = 0; m < 1 << (2*n-1); m++) {
            int density = 0;
            int[] key = new int[n];
            for (int i = 0; i < n; i++) {
                key[i] = Integer.bitCount((m >> i) & ((1 << n) - 1));
                density += key[i];
            }
            if (2 * density <= n * n) {
                CanonicalMatrix _key = new CanonicalMatrix(key);
                Map<CanonicalMatrix, Integer> map = part.get(_key);
                if (map == null) part.put(_key, map = new HashMap<CanonicalMatrix, Integer>());
                map.put(new CanonicalMatrix(m, perms[0]), m);
            }
        }

        List<Job> jobs = new ArrayList<Job>();
        ExecutorService pool = Executors.newFixedThreadPool(NUM_THREADS);

        for (Map.Entry<CanonicalMatrix, Map<CanonicalMatrix, Integer>> e : part.entrySet()) {
            Job job = new Job(n, perms, e.getKey().sum() << 1 == n * n ? 0 : 1, e.getValue());
            jobs.add(job);
            pool.execute(job);
        }

        pool.shutdown();
        try {
            pool.awaitTermination(1, TimeUnit.DAYS); // i.e. until it's finished - inaccurate results are useless
        }
        catch (InterruptedException ie) {
            throw new IllegalStateException(ie);
        }

        long total = 0;
        for (Job job : jobs) total += job.subtotal;
        return total;
    }

    private static int genPermsInner(int idx, int usedMask, int[] a, int[][] perms, int off) {
        if (idx == a.length) perms[off++] = a.clone();
        else for (int i = 0; i < a.length; i++) {
            int m = 1 << (a[idx] = i);
            if ((usedMask & m) == 0) off = genPermsInner(idx+1, usedMask | m, a, perms, off);
        }
        return off;
    }

    static class Job implements Runnable {
        private volatile long subtotal = 0;
        private final int n;
        private final int[][] perms;
        private final int shift;
        private final Map<CanonicalMatrix, Integer> unseen;

        public Job(int n, int[][] perms, int shift, Map<CanonicalMatrix, Integer> unseen) {
            this.n = n;
            this.perms = perms;
            this.shift = shift;
            this.unseen = unseen;
        }

        public void run() {
            long result = 0;
            int[][] perms = this.perms;
            Map<CanonicalMatrix, Integer> unseen = this.unseen;
            while (!unseen.isEmpty()) {
                int m = unseen.values().iterator().next();
                Set<CanonicalMatrix> equiv = new HashSet<CanonicalMatrix>();
                for (int[] perm : perms) {
                    CanonicalMatrix canonical = new CanonicalMatrix(m, perm);
                    if (equiv.add(canonical)) {
                        result += canonical.weight() << shift;
                        unseen.remove(canonical);
                    }
                }
            }

            subtotal = result;
        }
    }

    static class CanonicalMatrix {
        private final int[] a;
        private final int hash;

        public CanonicalMatrix(int m, int[] r) {
            this(permuteRows(m, r));
        }

        public CanonicalMatrix(int[] a) {
            this.a = a;
            Arrays.sort(a);

            int h = 0;
            for (int i : a) h = h * 37 + i;
            hash = h;
        }

        private static int[] permuteRows(int m, int[] perm) {
            int[] cols = new int[perm.length];
            for (int i = 0; i < perm.length; i++) {
                for (int j = 0; j < cols.length; j++) cols[j] |= ((m >> (perm[i] + j)) & 1L) << i;
            }
            return cols;
        }

        public int sum() {
            int sum = 0;
            for (int i : a) sum += i;
            return sum;
        }

        public int weight() {
            int prev = -1, count = 0, weight = FACT[a.length];
            for (int col : a) {
                if (col == prev) weight /= ++count;
                else {
                    prev = col;
                    count = 1;
                }
            }
            return weight;
        }

        @Override public boolean equals(Object obj) {
            // Deliberately unsuitable for general-purpose use, but helps catch bugs faster.
            CanonicalMatrix that = (CanonicalMatrix)obj;
            for (int i = 0; i < a.length; i++) {
                if (a[i] != that.a[i]) return false;
            }
            return true;
        }

        @Override public int hashCode() {
            return hash;
        }
    }
}

Save as HankelCombinatorics.java, compile as javac HankelCombinatorics.java, run as java -Xmx2G HankelCombinatorics.

With NUM_THREADS = 4 on my quad-core machine it gets 20420819767436 for n=8 in 50 to 55 seconds elapsed, with a fair amount of variability between runs; I expect that it should easily manage the same on your octa-core machine but will take an hour or more to get n=9.

How it works

Given n, there are 2^(2n-1) binary nxn Hankel matrices. The rows can be permuted in n! ways, and the columns in n! ways. All we need to do is to avoid double-counting...

If you calculate the sum of each row, then neither permuting the rows nor permuting the columns changes the multiset of sums. E.g.

0 1 1 0 1
1 1 0 1 0
1 0 1 0 0
0 1 0 0 1
1 0 0 1 0

has row sum multiset {3, 3, 2, 2, 2}, and so do all Hankelable matrices derived from it. This means that we can group the Hankel matrices by these  row sum multisets and then handle each group independently, exploiting multiple processor cores.

There's also an exploitable symmetry: the matrices with more zeroes than ones are in bijection with the matrices with more ones than zeroes.

Double-counting occurs when Hankel matrix M_1 with row permutation r_1 and column permutation c_1 matches Hankel matrix M_2 with row permutation r_2 and column permutation c_2 (with up to two but not all three of M_1 = M_2, r_1 = r_2, c_1 = c_2). The row and column permutations are independent, so if we apply row permutation r_1 to M_1 and row permutation r_2 to M_2, the columns as multisets must be equal. So for each group, I calculate all of the column multisets obtained by applying a row permutation to a matrix in the group. The easy way to get a canonical representation of the multisets is to sort the columns, and that is also useful in the next step.

Having obtained the distinct column multisets, we need to find how many of the n! permutations of each are unique. At this point, double-counting can only occur if a given column multiset has duplicate columns: what we need to do is to count the number of occurrences of each distinct column in the multiset and then calculate the corresponding multinomial coefficient. Since the columns are sorted, it's easy to do the count.

Finally we add them all up.

The asymptotic complexity isn't trivial to calculate to full precision, because we need to make some assumptions about the sets. We evaluate on the order of 2^(2n-2) n! column multisets, taking n^2 ln n time for each (including the sorting); if grouping doesn't take more than a ln n factor, we have time complexity Theta(4^n n! n^2 ln n). But since the exponential factors completely dominate the polynomial ones, it's Theta(4^n n!) = Theta((4n/e)^n).


CJam - 25

501{3sI3%<Is-I"bzzt"?N}fI

Thanks Howard :)

Try it at http://cjam.aditsu.net/

Explanation:

501{…}fI is basically for(int I=0; I<501; ++I) {…}
3s converts 3 to string, i.e. "3"
I3% is I % 3
< gets the left substring - "3".substring(0, I % 3) - which is "" for I % 3 == 0 and "3" otherwise
Is converts I to string
- with 2 strings does a set difference, resulting in an empty string iff I % 3 == 0 (the first string was empty) or I has a 3 digit in it
…I"bzzt"? is like … ? I : "bzzt"; the previous string is treated as a boolean value, where "" is false and any other string is true
N adds a newline


Kotlin, 283 218 bytes

Unnamed lambda (with a nested function, heh).

Golfed

{i:String,x:Int,y:Int->val m=i.lines().map{it.toCharArray()};fun v(x:Int,y:Int){try{if(m[y][x]=='#'){m[y][x]='%';for(c in-1..1)for(d in-1..1)if(!(c==0&&d==0))v(x+c,y+d)}}catch(e:Exception){}};v(x, y);m.map(::println)}

Ungolfed

fun zombies(input: String, startX: Int, startY: Int) {
    val m = input.lines().map(String::toCharArray)      // build game map
    fun invade(x: Int, y: Int) {                        // nested functions, woo!
        try {
            if (m[y][x] == '#') {                       // if land
                m[y][x] = '%'                           // mark as invaded
                for (dx in -1..1) {                      // generate neighbour tiles
                    for (dy in -1..1) {
                        if (!(dx == 0 && dy == 0)) {
                            invade(x + dx, y + dy)        // attempt to invade neighbours
                        }
                    }
                }
            }
        } catch(e: Exception) {}                        // catches ArrayIndexOutOfBounds
    }

    invade(startX, startY)                              // start the invasion
    m.map(::println)                                    // print final state
}

Saved quite a few bytes by switching to a recursive solution.


Find the simplest value between two values

Python 2 - 100
I think I revised my entire method for this answer a good 4 or 5 times (which is probably an indication that it's a good code-golf question). I don't know if this answer can be golfed down any more but I do feel as if I'm missing some more clever methodological ways to shorten this.
def f(a,b,i=1.):
    r=0if a<0 else(a*i+1)//1/i
    return-f(-b,-a,i)if b<=0 else r if r<b else f(a,b,i*2)


C# - 166

Due to the small number of matches, I thought it might be easier to hardcode the outputs:

void F(string i){int n=int.Parse(i.Substring(0,i.Length-1));
n=i.Last()=='C'?n:5*(n-32)/9;
Console.Write(n>4685?"7305 13245":n>2345?"2620 4780":n>275?"275 527":"0 0");}

Edit: 352

To do it right requires a bit more work. Here's a first attempt at using a whole pile of linq:

using System;
using System.Linq;
class P{static void Main(string[] i)
{
   int n=int.Parse(i[0].Substring(0,i[0].Length-1));
   n=i[0].Last()=='C'?n:5*(n-32)/9;
   var q=Enumerable.Range(1,n).Where(x=>new string(((decimal)x*9/5+32).ToString().OrderBy(y=>y).ToArray())==new string(x.ToString().OrderBy(y=>y).ToArray()));
   Console.Write(q.Sum()+" "+q.Sum(x=>x*9/5+32));
}}

Maybe the 'use a pile of linq instead of a loop' approach hurt me too much. I'll try and shorten it.

Edit 2: 356

Since I'm already way behind in raw count, here's a one-liner from hell:

Console.Write(Enumerable.Range(1,i.Last()=='C'?int.Parse(i.Substring(0,i.Length-1)):5*(int.Parse(i.Substring(0,i.Length-1))-32)/9).Where(x=>new string(((decimal)x*9/5+32).ToString().OrderBy(y=>y).ToArray())==new string(x.ToString().OrderBy(y=>y).ToArray())).Aggregate("0 0",(a,t)=>(int.Parse(a.Split(' ')[0])+t)+" "+(int.Parse(a.Split(' ')[1])+t*9/5+32)))


Print 123454321 without if statements and using only 2 variables

Python

One for loop, one int variable (i), no if, no other functions (unless you consider print or +-*/ as functions, haha):

for i in range(9):
    print i+1 - 2*(i//5)*(i-4),


Ruby, 653 597 Bytes
P=/ past | to /;T=%w{q twen thirty fourty fifty sixty el twe thi fourte fifte sixt sevent eighte ninet o tw th fo fi si s e n t}.zip([15,*(2..6).map{|i|i*10},*11..19,*1..10]).to_h;D={'middnight'=>0,'midday'=>12,'noon'=>12};n=->s{s.split('-').reduce(0){|p,v|(Array(T.find{|k,_|v.start_with? k}).last||0)+p}};i=->s{m=0;s=s.gsub(/^\s+|\s+$/,'');c=s.split(P);(c.reverse! if s.match(P));h=D[c[0]]||n.(c[0].gsub(/ o\'clock (A|P)m/,''));h+=(s.end_with?('PM') ? 12 : 0);m=n.(c[1]||c[0].split(' ')[1]) if c[1]||c[0].match(/^\w+ (?!o'clock)/);(m=60-m;h=(h-1)%24)if s.match(/ to /);(sprintf '%02d:%02d',h,m)}

Ungolfed:
P=/ past | to /
# configuration for translating english words to numbers
T=%w{q twen thirty fourty fifty sixty el twe thi fourte fifte sixt sevent eighte ninet o tw th fo fi si s e n t}.zip([15,*(2..6).map{|i|i*10},*11..19,*1..10]).to_h
D={'middnight'=>0,'midday'=>12,'noon'=>12}

# proc for translating english word groups to a number
n=-> s {
  s.split('-').reduce(0) { |p,v|
    (Array(T.find {|k,_| v.start_with? k}).last || 0) + p
  }
}

i=-> s {
  m=0
  s=s.gsub(/^\s+|\s+$/,'')
  c=s.split(P)
  (c.reverse! if s.match(P))

  # set the hour
  h=D[c[0]]||n.(c[0].gsub(/ o\'clock (A|P)m/,''))
  h+=(s.end_with?('PM') ? 12 : 0)

  # set the minute
  m=n.(c[1]||c[0].split(' ')[1]) if c[1]||c[0].match(/^\w+ (?!o'clock)/)

  # adjust for 'past'
  (m=60-m;h=(h-1)%24)if s.match(/ to /)

  sprintf '%02d:%02d',h,m
}

Verification script used:
examples = <<EXAMPLES
midnight                                  ->   00:00
midday                                    ->   12:00
twelve o'clock                            ->   12:00
quarter to midnight                       ->   23:45
twenty-two minutes past eight o'clock PM  ->   20:22
thirty-four minutes to fifteen o'clock    ->   14:26
six o'clock AM                            ->   06:00
one minute to twenty-one o'clock          ->   20:59
seven thirteen AM                         ->   07:13
nine fourteen PM                          ->   21:14
EXAMPLES

examples.split("\n").each do |example|
  text, expected = example.split(/\s+->\s+/)
  r = i.(text)
  raise "Unexpected result for \"#{text}\". Got \"#{r}\", expected \"#{expected}\"" unless r == expected
  print "."
end

Thank you to Kevin Lau for 47 bytes of optimization


**REXX 151 148 141 bytes **

(Kinda seemed appropriate)

i=arg(1)
m=i
o=translate(m,'',xrange('A','z'),'*')
p=0
do forever
   p=pos('REX',m,p+1)
   if p=0 then leave
   o=overlay(substr(i,p,3),o,p)
end
say o

Try it here

Notes for non-REXXers:

translate is a character replacement function (name comes from an assembler instruction on IBM MF).  It searches string1 for the characters in string3. Every time it finds one it replaces it with the same positioned one in string2. If string2 is too short it is padded with the pad character.

See here for translate function

overlay simply overlays the string1 on top of string2 at the specified position.

See here for overlay function


Sage

Hmm, you seem to assume that the fastest is going to be a compiled program.  No binary for you!

print fibonacci(2000000)

On my machine, it takes 0.10 cpu seconds, 0.15 wall seconds.

edit: timed on the console, instead of the notebook


Pyth - 49 46 44/2 + 1 + 1 + 1 = 25
Hello code:
h["Hi, Hello!":5lG2"+-+
| |
+-+""Hello, bye!

Odd numbers code:
ht["Hi, Hello!":5lG2"+-+
| |
+-+""Hello, bye!

Box code:
htt["Hi, Hello!":5lG2"+-+
| |
+-+""Hello, bye!

Bye Code:
httt["Hi, Hello!":5lG2"+-+
| |
+-+""Hello, bye!


Find a fraction's position in the Stern-Brocot tree


JavaScript (ES6),  150 148  137 bytes
Saved 10 bytes thanks to @Grimy
I/O: arrays of characters.

a=>a.map(c=>"ANBCODEFPGQSHRIJKLM"[(n=c.charCodeAt()-44032)/588|0]+"AKBLCMDNERTOFGSUPHIQJ"[n/28%21|0]+~(n%28%18==2)+c).sort().map(s=>s[4])

Try it online!
Splitting Hangul syllables
Given a Hangul character of code point 0xAC00 + \$n\$, the initial consonant \$I\$, vowel \$V\$ and final consonant \$F\$ are given by:
$$I=\left\lfloor\frac{n}{588}\right\rfloor,\ V=\left\lfloor\frac{n}{28}\right\rfloor\bmod 21,\ F=n\bmod 28$$
Commented
a => a.map(c =>                  // for each character c in the input:
  "ANBCODEFPGQSHRIJKLM"[         //   start with a letter from 'A' to 'S'
    (n = c.charCodeAt() - 44032) //   for the initial consonant
    / 588 | 0                    //
  ] +                            //
  "AKBLCMDNERTOFGSUPHIQJ"[       //   append a letter from 'A' to 'U'
    n / 28 % 21 | 0              //   for the vowel
  ] +                            //
  ~(                             //   append "-2" for ㄲ or ㅆ (the only North
    n % 28 % 18 == 2             //   Korean final consonants that are sorted
  ) +                            //   differently) or "-1" otherwise
  c                              //   append the original character
)                                // end of map()
.sort()                          // sort in lexicographical order
.map(s => s[4])                  // isolate the original characters


APL (Dyalog Extended), 27 26 bytes

-1 thanks to Bubbler.

Anonymous infix lambda. Takes \$n\$ as left argument and \$M\$ as right argument.

{⊃+⌿,(⍳⍺)⍉⍤⌽\⍣2⊂⍺/⍺⌿⍵÷⍺*2}

Try it online! (the \$n=100\$ case run out of memory on TIO gives by default, but works offline)

{…} "dfn"; ⍺ is \$n\$ and ⍵ is \$M\$

 ⍺*2 \$n^2\$

 ⍵÷ \$M\over n^2\$

 ⍺⌿ replicate vertically so each row becomes \$n\$ copies

 ⍺/ replicate horizontally so each column becomes \$n\$ copies

 ⊂ enclose to work on entire matrix

 (⍳⍺)…⍣2 do the following twice, each time with the \$0,1…n-1\$ as left argument:

  \ outer "product" using the following tacit function instead of multiplication:

   ⌽ cyclically rotate the rows by the indices

   ⍤ then:

    ⍉ transpose

 , flatten

 +⌿ sum

 ⊃ disclose (since the summation reduced rank from 1 to 0 by enclosing)


Haskell, A209229, (cracked)

11 characters (including newline):

s<=[ ]
how!

Outputs True/False as an indicator function for powers of 2:

1 => True
2 => True
3 => False
4 => True
5 => False
6 => False
7 => False
8 => True
9 => False
...

Inputs are positive integers.


What is the minimum set of characters with which you can write any valid python program?

I've come up with a 9-character translator using exec (also posted at this GitHub gist):

def convert_txt(txt):
    """Convert the text of a Python program to minimal Python"""
    s = "+".join(["chr(%s)" % "+".join(["1"] * ord(c))
                            for c in txt])
    return 'exec(%s)' % s

The only characters it needs are ()+1cehrx.


Python 2, 59394 59244 58534 58416 58394 58250

Ok here is my solution.
import re
import math

cache = {0:"<()>"}

def find(x,i,j):
    return i*((x**2+x)/2)+(j+1)*((x**2-x)/2)

def solve(x, i, j):
    a = (i + j + 1)/2.
    b = (i - j - 1)/2.
    c = -x
    return (-b + math.sqrt(b**2 - 4*a*c))/(2*a)

def size(i,j=0):
    return 4*(i+j)+14

def polynomials(n):
    upperBound = int(4*math.log(n,2))
    i = 0
    answers = []
    while size(i) < upperBound:
        for j in range(i):
            sol = int(solve(n, i-j, j)+.5)
            if find(sol, i-j, j) == n:
                answers.append((sol, i-j, j))
        i += 1
    return answers

def complement(character):
        dict = {"(":")","{":"}","<":">","[":"]",")":"(","}":"{",">":"<","]":"["}
        return dict[character]

def findMatch(snippet, index):
        increment = 1 if snippet[index] in "({<[" else -1
        stack = []
        if snippet[index] in "(){}<>[]":
                stack.append(snippet[index])
        while len(stack) > 0 and index + increment < len(snippet):
                index += increment
                if snippet[index] in "(){}<>[]":
                        if complement(snippet[index]) == stack[-1]:
                                stack = stack[:-1]
                        else:
                                stack.append(snippet[index])
        return index

def isPrime(n):
    return not [0 for x in range(2,int(n**.5)+1) if n%x==0] and n>1

def getPrimeFactors(n):
    return [x for x in range(2,n/2) if n%x==0 and isPrime(x)]

def divHardcode(n,m):
    assert n%m == 0
    assert m != 1
    assert n != 1
    binary = bin(m)[3:]
    return (binary.count("1")+len(binary))*"("+getBF(n/m)+")"*binary.count("1")+binary.replace("1","){}{}").replace("0","){}")

def isTriangular(n):
    #Triangles must be between sqrt(2n) and cbrt(2n)
    if n < 0: return isTriangular(-n)
    for x in range(int((2*n)**(1/3.)),int((2*n)**.5)+1):
        if (x**2+x) == 2*n:
            return True
    return False

def getTriangle(n):
    if n < 0: return -getTriangle(-n)
    #Triangles must be between sqrt(2n) and cbrt(2n)
    for x in range(int((2*n)**(1/3.)),int((2*n)**.5)+1):
        if (x**2+x) == 2*n:
            return x
    #If we don't find one we made a mistake
    assert False

def getSimpleBF(n):
    if n in cache:return cache[n]
    if n < 0:
        # There is room for better solutions here
        return "["+getSimpleBF(-n)+"]"
    elif n == 0:
        return ""
    elif n < 6:
        return "()"*n
    #Non-edge cases
    solutions = []
    factors = getPrimeFactors(n)
    if n >= 78 and isTriangular(n):
        solutions.append(
           min([push(getTriangle(n))+"{({}[()])}{}","<"+push(getTriangle(n)+1)+">{({}[()])}{}"],key=len)
        )
    polynomialSolutions = polynomials(n)
    for polynomial in polynomialSolutions:
        solutions.append("<%s>{%s({}[()])%s}{}"%(push(polynomial[0]),"({})"*polynomial[1],"({})"*polynomial[2]))
        #Mod 3 tricks
    if n % 3 == 2:
       solutions.append(("((%s)()){}{}")%getBF(n/3))
    elif n % 3 == 1:
       solutions.append(("((%s)()()){}{}")%getBF(n/3-1))
    #Basic solutions
    if isPrime(n):
        solutions.append(getSimpleBF(n-1) + "()")
    else:
        #TODO multithread
        solutions += map(lambda m:divHardcode(n,m),factors)
    return min(solutions,key=lambda x:len(unpack(x)))

def getBF(n):
    if n in cache: return cache[n]
    result = getSimpleBF(n)
    index = n - 1
    while index > n-(len(result)/2):
        score = getSimpleBF(index)+getSimpleBF(n-index)
        if len(score) < len(result):result = score
        index -= 1
    index = n + 1
    while index < n+(len(result)/2):
        score = getSimpleBF(index)+getSimpleBF(n-index)
        if len(score) < len(result):result = score
        index += 1
    cache[n] = result
    return result

def unpack(string):
    reMatch = re.match("\(*<",string)
    if reMatch:
        location =reMatch.span()
        return string[location[1]:findMatch(string,location[1]-1)] +string[:location[1]-1] + string[findMatch(string,location[1]-1)+1:]
    return string

def push(n):
    return unpack("("+getBF(n)+")")

def kolmo(string):
    code = push(ord(string[-1]))
    stringVector = map(ord,string)
    for x,y in zip(stringVector[-1:0:-1],stringVector[-2::-1]):
        code = "("+code+getBF(y-x)+")"
    code = code.replace("<()>)",")")
    return code

def kolmo(stringVector):
    code = push(stringVector[-1])
    for x,y in zip(stringVector[-1:0:-1],stringVector[-2::-1]):
        code = "("+code+getBF(y-x)+")"
    code = code.replace("<()>)",")")
    return code

if __name__ == "__main__":
    import primes
    sum = 0
    for prime in primes.nums:
        print push(prime)
        sum += len(push(prime))
    print sum

The relevant function is push(n). To call it simply call push on the integer you wish to represent.
Explanation
The main optimization done by the program is multiplication hard-coding.  The idea of multiplication hardcoding is pretty simple.  You push the a number and then pop and push it to create a new value.  For example to multiply by two you can use the following code ((n){}) where n code producing a specific number.  This works because both (n) and {} have a value of n.
This simple idea can be made more complex for larger numbers.  Take for instance 5 it was discovered a while ago that the best way to multiply by five was (((n)){}){}{}.  This code makes two copies of the n multiplies one by 4 and adds the two.  Using the same strategy I make every multiplication based on a number's binary representation.  I won't get into the details of how this works right now but I do this by chopping off the first one of the binary representation and replacing 0 with ){} and 1 with ){}{}.  It then makes sure that n is pushed the appropriate number of times and balances all the parentheses.  (If you want to know how this is done you can look at my code).  If you want to know why this works just ask me in a comment.  I don't think anyone actually reads all the updates to my post so I left the explanation out.
When the algorithm attempts to find a multiplication hardcode it attempts all of a numbers prime factors.  It ignores composite factors because at one point composite factors could always be expressed more concisely as its own prime factors it is not known if this is still true.
The other byte saving mechanism is a polynomial solution finder.  There are certain forms of polynomials that are easy to represent with decrementing loops.  These polynomials include, but are not limited to, polygonal numbers. This optimization finds polynomials that fit the form and creates the code that makes them.
Output
paste-bin


It's [current year] already, folks, go home

bash + date, 40 bytes

date +"It's %Y already, folks, go home."

Try it online!


Haskell

Now that not only the comments document that Peter Taylor was the first one to give enough terms to search on OEIS, I can give my results.

( 1 - 10) 2, 2, 4, 10, 28, 79, 235, 720, 2254, 7146,
(11 - 15) 22927, 74137, 241461, 790838, 2603210,
(16 - 18) 8604861, 28549166, 95027832,
(19 - 22) 317229779, 1061764660, 3562113987, 11976146355

Earlier, I counted hexagonal polyominoes. Except for some optimizations, what I'm doing here is very similar.

The elements of the tiling are represented like this:
You can go in an almost straight line from left to right
(in the first picture), alternating between squares and
rectangles. There are almost parallel further lines,
wiggling in opposite directions. Together, they miss
some triangles.
There are similar almost straight parallel lines from
bottom to top, containing the missing triangles.
Now ignore the wiggling and use a Cartesian coordinate
system, but only use odd numbers for the coordinates of the squares.
Then the triangles naturally get coordinate pairs with one even
and one odd coordinate. Pairs with both coordinates even
don't represent elements of the tiling.

(You could as well use even numbers for the coordinates
of the squares. I guess I decided this way because I thought
about reflection before rotation.)

Save the program in a file with a name like cgp.hs and compile with ghc -O2 -o cgp cgp.hs. It takes either one numeric command line argument and computes the number of polyominoes of that size, or none, in which case it computes values until stopped.

{-# LANGUAGE BangPatterns #-}

import Data.List(sort)
import qualified Data.Set as S
import System.Environment(getArgs)

data Point = P !Int !Int deriving (Eq,Ord)

start :: Point
start = P 1 1

redsq :: Point -> Bool
redsq (P x y) = (x+y) `mod` 4 == 2

neighs :: Point -> [Point]
neighs (P x y) =
  case (even x, even y) of
    (False,False) -> [P x (y+1), P (x+1) y, P x (y-1), P (x-1) y]
    (True, False) -> (P x (c y (x+y+1))) : opt [P (x-1) y, P (x+1) y]
    (False,True ) -> (P (c x (x+y-1)) y) : opt [P x (y-1), P x (y+1)]
  where
    opt = filter ok
    ok p = p>start || not (redsq p)
    c z m = if m `mod` 4 == 0 then z+2 else z-2

count :: S.Set Point -> S.Set Point -> [Point] -> Int -> Int -> Int -> Int -> Int
count use _    _            0 c r y =
  if check (S.toAscList use) (y==r)
    then c+1
    else c
count _   _    []           _ c _ _ = c
count use seen (p:possible) n c r y =
  let !c' = count use seen possible n c r y
      new = filter (`S.notMember` seen) $ neighs p
      !r' = if redsq p then r+1 else r
      !y' = if redsq (mirror p) then y+1 else y
      !n' = n-1
  in if r'+n' < y'
       then c'
       else count (S.insert p use) (foldr S.insert seen new) (new++possible)
                  n' c' r' y'

class Geom g where
  translate :: Int -> Int -> g -> g
  rot :: g -> g
  mirror :: g -> g

instance Geom Point where
  translate dx dy (P x y) = P (dx+x) (dy+y)
  rot (P x y) = P (2-y) x    -- rotate around (1,1)
  mirror (P x y) = P x (-y)

instance (Geom g, Ord g) => Geom [g] where
  translate x y = map $ translate x y
  rot = sort . map rot
  mirror = sort . map mirror

normalize :: [Point] -> [Point]
normalize pol = let (P x y) = head (filter redsq pol)
                in translate (1-x) (1-y) pol

check :: [Point] -> Bool -> Bool
check pol !cm = let rotated = take 4 $ iterate rot pol
                    mirrored = if cm then map mirror rotated else []
                    alts = map normalize (tail rotated ++ mirrored)
                in all (pol<=) alts

f :: Int -> Int
f 0 = 1; f 1 = 2; f 2 = 2
f n = count S.empty S.empty [start] n 0 0 0

output :: Int -> IO ()
output n = putStrLn $ show n ++ ": " ++ show (f n)

main = do args <- getArgs
          case args of
            []  -> mapM_ output [1..]
            [n] -> output (read n)

Try it online!


Determine whether a number is 2017-friable without primes in your source code

Jelly, 8 bytes

44‘²!*ḍ@

Try it online! Note that test cases 11111 and above are a bit too much for TIO.

Verification

$ source="34,34,fc,82,21,2a,d5,40"
$ xxd -ps -r > 2017.jelly <<< $source
$ xxd -g 1 2017.jelly
0000000: 34 34 fc 82 21 2a d5 40                          44..!*.@
$ eval printf '"%d "' 0x{$source}; echo # Code points in decimal
52 52 252 130 33 42 213 64
$ test_cases="1 2 80 2017 2019 2027 11111 45183 102349 999999 1234567 4068289"
$ for n in $test_cases; do printf "%11d: %d\n" $n $(jelly f 2017.jelly $n); done
      1: 1
      2: 1
     80: 1
   2017: 1
   2019: 1
   2027: 0
  11111: 1
  45183: 0
 102349: 0

Test case 999999 has been running for 13 hours. I'm pessimistic about computing 2025!4068289...

How it works

44‘²!*ḍ@  Main link. Argument: n

44        Yield 44.
  ‘       Increment to yield 45.
   ²      Square to yield 2025.
          Note that no integers in [2018, ..., 2025] are prime numbers.
    !     Take the factorial of 2025.
     *    Raise it to the n-th power.
          This repeats all prime factors in 2025! at least n times, so the result
          will be divisible by n if (and only if) all of its prime factors fall
          in the range [1, ..., 2025].
      ḍ@  Test the result for divisibility by n.


Befunge-93 - 404 371 361 352 339 337 323 bytes
<xyXYvp01<>110vv5_v#`0+1:_v#+!-"g"\<v"<":::<>1v#p03-1_>! g20gp00g1+0v25p
v2g02 < p0 20p<+vp020p01-10$_:"p"-!^>>-!\ v^ <>0p20pv|!*-";"\+1::~p0<
v2-10<^v# ^#<  <<$<       < ^+!-"_"\+!-"?"<>#^_10v4p<:^00 _$20g1+20p^
v21p010>#<40g20v>\%:40p5+g:92p:75*1--00g!\#^_\$0 v   >91+-^
<3+g01g 03p04+g<^++g04g02:*54p03:%\++g03g01:"P"p0<

Try It Online!
Input program must have at most 20 lines. Input can be provided in same file as Befunge program by placing it after a ; character. Yes, it can interpret itself, but the *54 in the bottom line should be replaced by *53 if you do that. And if you ask that interpreted interpreter to interpret itself, change it to *52 etc. If run in a Befunge-97 interpreter, it will also support the a-f commands (but not ' or any new command that affects control flow or wrapping behavior).
Note that it basically asks the interpreter it runs in to handle all the stuff relating to I/O and stack, so its specific behavior is largely dependent on that of the interpreter running it. In other words, it is perfectly compliant if run in a compliant interpreter.
It works by reading in the program from input (until EOF or semicolon) directly into the playfield below it, then simulating the movement of a virtual instruction pointer through that program. It copies each command from the program into its own execution area (at position (9,2) on the grid) and runs its own instruction pointer through it after ensuring all of its own data has been removed from the stack (as all of the interpreted program's stack data is maintained at the bottom of the stack). This is the standard methodology for Befunge self-interpretation since the early 00s, but I don't think it has ever been done in such a small program.
A fuller explanation is in the annotations you can see by clicking the link above.


MATL, 14 bytes

J_iB^YsJ+'o-'&XG

Produces graphical output as a path starting at coordinates (0,0). Try it at MATL Online! Or see some offline examples below:

Input 7:

Output:

Input 699050:

Output:

If you prefer, you can see the path as complex coordinates for 9 bytes:

J_iB^YsJ+

Try it online!

Explanation

J_      % Push -1j (minus imaginary unit)
i       % Push input number
B       % Convert to binary. Gives an array of 0 and 1 digits
^       % Power, element-wise. A 0 digit gives 1, a 1 digit gives -1j
Ys      % Cumulative sum. Produces the path in the complex plane
J+      % Add 1j, element-wise. This makes the complex path start at 0
'o-'    % Push this string, which defines plot makers
&XG     % Plot


Python 3 864 bytes

Extremely quick and dirty. Works with AWS SES and Yahoo!. Could not get it to work with Postmark (requires STARTTLS) or Gmail (requires further authentication outside of the SMTP connection).

import socket,ssl
from base64 import*
N=b'\x00'
U='utf-8'
E=lambda s:s.encode(U)
D=lambda b:b.decode(U)
B=lambda s:D(b64encode(E(s)))
A=lambda f,t,j,b:E('\r\n'.join(['DATA','Subject: =?UTF-8?B?{}?=','To: <{}>','From: <{}>','MIME-Version: 1.0','Content-Type: text/html; charset=utf-8','Content-Transfer-Encoding: base64',B(b),'','.','']).format(B(j),t,f,b))
X=lambda s,e:s.startswith(e)
def S(h,u,p,t,f,j,b):
    c,F,W=ssl.wrap_socket(socket.create_connection((h,465))),lambda m:E(m if'amazonaws'in h else'<'+m+'>'),lambda m:c.write(m+b'\r\n')
    def R(d,o=[]):
        x,y=c.read(),str(d)
        if not(X(x,E(y))or filter(lambda i:X(i,X(x,E(y))),o)):raise RuntimeError(y+' '+repr(x))
    R(220);W(b'EHLO x');R(250);W(b'AUTH PLAIN '+b64encode(N+E(u)+N+E(p)));R(235);W(b'MAIL FROM: '+F(f));R(250);W(b'RCPT TO: '+F(t));R(250);W(A(f,t,j,b));R(250,(354,));W(b'QUIT')

Invoke like S(hostname, username, password, to, from_, subject, body)

Expect bugs and changes (kind of got bored so it feels slightly half-baked).


Javascript - 93 92 89 bytes
Defines a function f. Not sure of a better way to return.
f=n=>{y="Tell me about your ";x="f="+f;return n==y+"source"?x:n==y+"length"?x.length:2*n}


Summing a sub-square of a quarter of an infinite chessboard

Perl 6, 19 bytes

{sum [X+^] 0 X..@_}

Try it online!

The sum of the bitwise xor between all numbers in the range 0 to all inputs.


Haskell, 93 92 84 83 82 bytes

data B=B[B]Int|L
k!B[l@(B[x,y]a),r]n|k<n=B[k!l,r]n|k>n=B[l,k!r]n|1>0=B[x,B[y,r]k]a

Thanks to @BMO, @alephalpha and @Laikoni for a byte each and @nimi for eight bytes!

Try it online!


Write a piece of code to output the line number of the print / output statement itself (in the form "Hello World, from line X!")

Sinclair Basic

10 PRINT "Hello world, from line ";PEEK 23621;"!"

  Hello world, from line 10!

This will work for any line by PEEKing at the address storing the current line number, so the following will work as well:

341 PRINT "Hello world, from line ";PEEK 23621;"!"

  Hello world, from line 341!


Shakespeare Programming Language, 106 bytes
,!Ajax,!Puck,!Act I:!Scene I:![Enter Ajax and Puck]Ajax:Listen tothy!You is the factorial ofyou!Open heart

Try it online!
Uses the built-in the factorial of, which isn't described at all in the official docs.
Commented
,!Ajax,!Puck,!Act I:!Scene I:![Enter Ajax and Puck] # header
Ajax:Listen tothy!                                  # read (numeric) input
You is the factorial ofyou!                         # take factorial
Open heart                                          # numeric output


JavaScript ES6, 14 bytes

$=_=>_==`$=`+$

Simple modification of the traditional "bling quine".


Efficiently generate all vector partitions

Python 2, 289 bytes
Simple brute force algorithm. Treats entire list as a number in base max(input)+1 (b), and checks each "number" in the range [0, b**(L*M)) to see if it:

Sums to the correct amount
Is in alphabetical order (ensures uniqueness)

If the list matches these criteria, the program outputs it with all the all-zero vectors stripped.
Memory usage
The largest data structure I use in this program is a doubly-nested list, an list length M containing liss length L to give O(L*M) memory.
For my other data structures, I have 3 global ints O(3), 1 list length L (O(L)), 1 array length M (O(M)), and a copy of the largest array when outputting (O(L*M)).
In total, this gives me a memory usage of O(2*L*M + L + M + 3) which simplifies to O(L*M), fufilling the criteria.
Time complexity
Being a brute force algorithm, this algorithm is extremely slow. For the while loop to quit, the final int in the array needs to be b-1. The loop needs to run b**(L*M) times before that happens.
In addition, each time the list runs, it needs to check both conditions, and print the list in a worst case, using L*M+L+M iterations. This simplifies to give an overall O(L*M * b**(L*M)). I tried to test my program on [3, 2, 5, 2], but gave up after 45 minutes.
Golfed program
v=input()
L=len(v)
M=sum(v)
b=max(v)
R=range
t=[L*[0]for i in R(M)]
def A(l,i):
 if i<L*M-1and~-b<l[i/L][i%L]:A(l,i+1)
 l[i/L][i%L]=-~l[i/L][i%L]%-~b
while t[-1][-1]<b:
 if v==[sum(q[i]for q in t)for i in R(L)]and all(`t[i]`>=`t[i+1]`for i in R(M-1)):print[x for x in t if[0]*L!=x]
 A(t,0)

I might be able to golf this a bit more, especially the increment part. Ungolfed code coming.


Score: \$ A(255, 2) - 1 = (2 \uparrow^{253} 5) - 4 \$

+<+<<++>-[-[<+>>[-<[->+<]+>>]+<-]>[>]+[<]+<]>[->]

\$ A \$ here is the Péter-Ackermann formulation of the Ackermann function, while the other score expression uses Knuth up-arrow notation. The 35-byte main loop [-[<+>>[-<[->+<]+>>]+<-]>[>]+[<]+<] can be used to compute \$ A(m,n) \$ by placing on the tape the values 1 - m, m, 1 <n times> and entering the loop with the pointer on the m cell. After the loop terminates, the nonzero tape contents are \$ A(m,n) \$ ones starting immediately to the right of the pointer.

I used the following Python program for modeling the behavior of the program:

def a(M, N):
    assert M > 0
    m = [-M + 1, M]
    n = N
    while m[-1]:
        while m[-1] > 1:
            m[-1] -= 1
            m[-2] += 1
            while n:
                m.insert(-1, 1)
                n -= 1
            n = 1
        n += 2
        m.pop()
    return n


Jelly, 8 7 bytes

1 byte thanks to Dennis.

gRỊTP‘:

Try it online!

You don't really have to compute e since you need to divide anyway.


Jelly, 11 bytes

BUT€ŒpṬz0PẸ

Try it online!

How it works

BUT€ŒpṬz0PẸ  Main link. Argument: A (array)

             Example: A = [4, 5, 2]
B            Binary; convert each n in A to base 2.
                      [[1, 0, 0], [1, 0, 1], [1, 0]]
 U           Upend; reverse all arrays of binary digits.
                      [[0, 0, 1], [1, 0, 1], [0, 1]]
  T€         Truth each; for each binary array, get all indices of 1's.
                      [[3], [1, 3], [2]]
    Œp       Take the Cartesian product of all index arrays.
                      [[3, 1, 2], [3, 3, 2]
      Ṭ      Untruth; map each index array to a binary arrays with 1's at
             at the specified indices.
                      [[1, 1, 1], [0, 1, 1]]
       z0    Zip/transpose the resulting 2D array, filling shorter rows with 0's.
                      [[1, 0], [1, 1], [1, 1]]
         P   Take the columnwise product.
                      [1, 0]
          Ẹ  Any; yield 1 if any of the products is non-zero, 0 otherwise.
                      1


Jelly, 11 bytes

o-1.’d3ạ/ḞS

Try it online! or verify all test cases.

How it works

o-1.’d3ạ/ḞS  Main link. Argument: [a, b] (list of integers)

 -1.         Yield -1.5.
o            Take the logical OR of a and b with -1.5.
             This maps 0 to -1.5, and all other integers to themselves.
    ’        Decrement the results.
     d3      Divmod; compute quotient and remainder of each result divided by 3.
       ạ/    Reduce by absolute difference across columns.
         Ḟ   Floor; round all differences down to the nearest integer.
          S  Sum; add the rounded absolute differences.


Attache, 4 bytes

Last

Try it online! (If the input could be a list of characters, &/S could work.)

Alternatives

5 bytes: `@&-1

8 bytes: &/S@List

10 bytes: `@«_,-1»

10 bytes: Fold!Right

10 bytes: `@<~_,-1~>

10 bytes: `^^&:Right

10 bytes: {Right^^_}

11 bytes: Get«_,-1»

11 bytes: Get<~_,-1~>

12 bytes: `@«_,#_-1»

12 bytes: `@<~_,#_-1~>

13 bytes: Get«_,#_-1»

13 bytes: Get<~_,#_-1~>


TSQL query, 205 191 bytes
Input is a table variable @t
@x=start xpos, @y=start ypos
@i=end xpos  , @j=end ypos
@ =speed
DECLARE @t table(x int,y int,v int)
INSERT @t
values
(0,0,1),(0,1,1),(0,2,2),(0,3,1),(0,4,null),
(1,0,1),(1,1,2),(1,2,2),(1,3,1),(1,4,1),
(2,0,2),(2,1,1),(2,2,1),(2,3,2),(2,4,1),
(3,0,null),(2,1,null),(2,2,null),(2,3,1),(2,4,2)

DECLARE @x INT=2,@y INT=3,@i INT=0,@j INT=1,@ INT=5;

WITH C as(SELECT @y f,@x r,@ s
UNION ALL
SELECT f+a,r+b,s-v FROM C
JOIN(values(1,0),(0,1),(-1,0),(0,-1))x(a,b)ON
s>0JOIN @t
ON f+a=x and r+b=y)SELECT
max(iif(S>=0and f=@j and r=@i,1,0))FROM c

Try it online ungolfed version


JavaScript (224 218 213 bytes)
s=>t=>(v=s=>(o={},l=n=0,z=3.5,[...s].sort().map(c=>(n+=o[c]=-~o[c],z*=!l|l+1==(l=c.charCodeAt()))),[n+z,Object.keys(o).sort((a,b)=>o[b]-o[a]||(o[b]>o[a]?1:-1))]),w=v(s),x=v(t),w[0]>x[0]||w[0]==x[0]&&w[1]<x[1]?s:t)

Ungolfed:
s=>t=>(
  v=s=>(
    o={},
    l=n=0,
    z=3.5,
    [...s].sort().map(c=>(
      n+=o[c]=-~o[c],
      z*=!l|l+1==(l=c.charCodeAt())
    )),
    [n+z,Object.keys(o).sort((a,b)=>o[b]-o[a]||(o[b]>o[a]?1:-1))]
  ),
  w=v(s),x=v(t),
  w[0]>x[0] || w[0]==x[0] && w[1]<x[1] ? s : t
)

After map() runs, n + z determines the ranking of a hand:

(You can understand why I initialized z to 3.5.)
In case of a tie, Object.keys(o).sort() is used to determine the higher ranking hand.
Snippet:

f=

s=>t=>(v=s=>(o={},l=n=0,z=3.5,[...s].sort().map(c=>(n+=o[c]=-~o[c],z*=!l|l+1==(l=c.charCodeAt()))),[n+z,Object.keys(o).sort((a,b)=>o[b]-o[a]||(o[b]>o[a]?1:-1))]),w=v(s),x=v(t),w[0]>x[0]||w[0]==x[0]&&w[1]<x[1]?s:t)

console.log(/voviu/.test(f('voviu')('kjsdf')))       //because a pair beats nothing
console.log(/opoqo/.test(f('opoqo')('upper')))       //because 3 of a kind beats a pair
console.log(/ggegg/.test(f('woooo')('ggegg')))       //because 4 Gs beats 4 Os
console.log(/queue/.test(f('queue')('hopup')))       //because 2 pairs beats 1 pair
console.log(/ddkop/.test(f('lodpl')('ddkop')))       //because pair DD beats pair LL
console.log(/huhyg/.test(f('huhyg')('hijht')))       //both have pair HH, but G beats I
console.log(/ccyyz/.test(f('ddffh')('ccyyz')))       //both have 2 pairs, but CC(yyz) beats DD(ffh)
console.log(/nkunk/.test(f('okaok')('nkunk')))       //KK ties with KK, but NN beats OO
console.log(/bcdef/.test(f('abcdf')('bcdef')))       //because it is a straight
console.log(/qtery|retyq/.test(f('qtery')('retyq'))) //identical! so doesnt matter
console.log(/abedc/.test(f('abedc')('vyxwz')))       //because it is a "higher" straight
console.log(/hijkl/.test(f('hhhij')('hijkl')))       //because straight beats 3 of a kind
console.log(/zzzzz/.test(f('aaabb')('zzzzz')))       //because nothing beats 5 of a kind


Lenguage, \$1.42 \times 10^{122}\$ bytes
minus a lot of bytes thanks to Kevin Cruijssen and Bubbler
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh...

This is 142099843608359281286315447494338058415442968773543757980908246691462388164856076679905341690709953072132211450166077106439 hs, which also makes it a valid Hello program, though not one you'd want to run. The original brainfuck code is 140 135 bytes:
,[>-[<-->-----]+<--[>]>[[-->-[>>+>-----<<]<--<---]>-.>>>+.>>..+++.>>.>.<<<.+++.------.<<-.[>]>>>>,>]<]<[[>++<+++++]>-.+++++++++++++..>]

Try it online!
This prints Hello World every time it sees a h through a modification of the shortest known Hello, World! program, stopping the loop and printing err if it sees anything other than a h.


Haskell, 80 67 bytes

g~(a:b)|let k!l=k:take(a-1)l++(k+1)!drop(a-1)l=2!g b
m=g m
(!!)$0:m

Try it online!

Haskell is the perfect language for defining an infinite list in terms of itself.


Matlab, 255 245 231 bytes
This expects the image name first, then y and then x.
I=@input;i=imread(I('','s'));[r,c]=size(i);m=zeros(r,c);m(I(''),I(''))=1;M=m;d=m;K=[1,2,1];for k=1:r*c;d(m&~M)=k;M=m;m=~~conv2(m,K'*K>1,'s');m(~i)=0;end;z=max(d(:));v=[1,1,3];imshow(ind2rgb(d,hsv(z)).*repmat(m,v)+repmat(~d&i,v),[])

I implemented the flood filling (or 'dijkstra for 4-neighbourhoods' if you want) roughly by first creating a mask where the seed pixel is set to 1 and with a distance accumulator (both of the size of the image) and then repeating following steps:

convolute the mask with a 4 neighbourhood kernel (this is the very inefficient part)
set all nonzero pixels of the mask to 1
set all the black pixels of the image to zero
set all values in the accumulator where the mask has changed in this step to k
increase k
repeat until there are no more changes in the mask (I actually do not check this condition, but just use the number of pixels in the image as an upper bound, which is usually a very bad upper bound, but this is codegolf=)

This leaves us with the manhattan distances of every pixel to the seed pixel in the distance accumulator. Then we create a new image by going throu the given range of colours and map the "first" hue to the value zero and the "last" hue to the maximal distance.
Examples

As a bonus, here a pretty picture of how the distance gets calculated. brighter = farther away.


Reverse order of words in a string inplace

Perl, score 1.3̅

For each non-space character one assignment is performed, and for each space character two assignments. Because space characters cannot amount to more than one half the total number of characters, the worst case score is 1.5.

The algorithm hasn't changed, but I can prove a lower upper bound. Let us make two observations:

Spaces directly across from spaces do not need to be swapped.
Single character words directly across from spaces are not swapped during the main phase, but only once at the end.

It can then be seen that the theoretical 'worst case' with asymptotically 1/2 spaces is not worst case at all: ab c d e f g h i ...

$ echo ab c d e f g h i j k l m n o p q r s t u v w x y z|perl reverse-inplace.pl
z y x w v u t s r q p o n m l k j i h g f e d c ab
swaps: 51; len: 50
ratio: 1.02

In fact, it's quite a good case.

In order to prevent observation one and two above, each one-character word would need to be repositioned into the middle of a word three or more characters long. This would suggest a worst case containing asymptotically 1/3 spaces: a bcd a bcd a ... bc

$ echo a bcd a bcd a bcd a bcd a bcd a bc|perl reverse-inplace.pl
bc a bcd a bcd a bcd a bcd a bcd a
swaps: 45; len: 34
ratio: 1.32352941176471

Or equivalently, only two-character words: a bc de fg hi jk ...

$ echo a bc de fg hi jk lm no pq rs tu vx xy|perl reverse-inplace.pl
xy vx tu rs pq no lm jk hi fg de bc a
swaps: 49; len: 37
ratio: 1.32432432432432

Because the worst case contains asymptotically 1/3 spaces, the worst case score becomes 1.3̅.

#!perl -l
use warnings;

$words = <>;
chomp($words);
$len = length($words);
$words .= ' ';
$spaces = 0;
# iterate over the string, count the spaces
$spaces++ while $words =~ m/ /g;

$origin = 0;
$o = vec($words, $origin, 8);
$cycle_begin = $origin;
$swaps = 0;

# this possibly terinates one iteration early,
# if the last char is a one-cycle (i.e. moves to its current location)
# one-cycles previous to the last are iterated, but not swapped.
while ($i++ < $len - $spaces || !$was_cycle) {
  $w_start = rindex($words, ' ', $origin);
  $w_end = index($words, ' ', $origin);
  $pos = ($origin - $w_start) - 1;
  $target = $len - ($w_end - $pos);
  $t = vec($words, $target, 8);

  if ($t == 32) {
    $target = $len - $target - 1;
    $t = vec($words, $target, 8);
  }

  # char is already correct, possibly a one-cycle
  if ($t != $o) {
    $swaps += 1;
    vec($words, $target, 8) = $o;
  }

  $origin = $target;
  $o = $t;
  if ($origin == $cycle_begin) {
    if ($i < $len - $spaces) {
      # backtrack through everything we've done up to this point
      # to find the next unswapped char ...seriously.
      $origin += 1;
      if (vec($words, $origin, 8) == 32) {
        $origin += 1;
      }
      $bt_origin = 0;
      $bt_cycle_begin = 0;
      while ($bt_cycle_begin < $origin) {
        $w_start = rindex($words, ' ', $bt_origin);
        $w_end = index($words, ' ', $bt_origin);
        $pos = ($bt_origin - $w_start) - 1;
        $target = $len - ($w_end - $pos);
        $t = vec($words, $target, 8);

        if ($t == 32) {
          $target = $len - $target - 1;
          $t = vec($words, $target, 8);
        }

        if ($target == $bt_cycle_begin) {
          $bt_origin = ++$bt_cycle_begin;
          if (vec($words, $bt_origin, 8) == 32) {
            $bt_origin = ++$bt_cycle_begin;
          }
        } else {
          $bt_origin = $target;
        }

        if ($target == $origin) {
          $origin += 1;
          if (vec($words, $origin, 8) == 32) {
            $origin += 1;
          }
          $bt_origin = $bt_cycle_begin = 0;
        }
      }
    }

    $cycle_begin = $origin;
    $o = vec($words, $origin, 8);
    $was_cycle = 1;
  } else {
    $was_cycle = 0;
  }
}

for $i (0..$len/2-1) {
  $mirror = $len - $i - 1;
  $o = vec($words, $i, 8);
  $m = vec($words, $mirror, 8);
  # if exactly one is a space...
  if (($o == 32) ^ ($m == 32)) {
    $swaps += 2;
    vec($words, $mirror, 8) = $o;
    vec($words, $i, 8) = $m;
  }
}

chop($words);
print $words;
print "swaps: $swaps; len: $len";
print 'ratio: ', $swaps/$len;

Edit: Added a swap counter, and the ratio.

Input is taken from stdin. Sample usage:

$ echo where in the world is carmen sandiego|perl reverse-inplace.pl
sandiego carmen is world the in where
swaps: 35; len: 37
ratio: 0.945945945945946

Method

To begin, the first character of the string is moved to its final destination. The character just replaced is then moved to its destination, etc. This continues until one of two conditions is met:

The character should be swapped with a space.
When this occurs, the character is not swapped with the space, but rather into the mirror position of the space. The algorithm continues from that position.
A cycle has been reached.
When the target returns to the initial starting position of the current cycle, the next unswapped character (or rather, any unswapped character would do) needs to be found. To do this under constant memory constraints, all swaps that have been made up to this point are back-tracked.

After this phase, each non-space character has been moved at most once. To finish, all space characters are swapped with the characters at their mirror positions, requiring two assignment operations per space.


Group definitions by keyword

This will save you from having to retype the keyword.

type WD=(Su,M,Tu,W,Th,F,Sa);M=(Ja,F,Mr,Ap,My,Jn,Jl,Ag,S,O,N,D);
const A=1;B=2;
var X,Y,Z:string;

Use function name instead of Result for holding function return value

Functions' return value can be referenced by the function name. Unless the function is required to be a particular name it will usually be shorter than Result.

function F:Int8;
begin
  F:=1
end;

Using the Exit short hand (Delphi 2009 or newer) is shorter than assigning to Result also:

function F:Int8;
begin
  Exit(1)
end;

Use comma-separated variable declarations

procedure Z(A,B,C: string);
var A,B,C:string;

Constants usually require fewer characters than variable declarations

With the exception of the above mentioned comma separated variable declarations constant declarations use fewer characters than variable declarations when initialization is taken into consideration.

const A=1; // True constant = 10 chars
const A:Int8=1; // Typed constant = 15 chars
var A:Int8; // Variable = 11 chars
begin
  A:=1; // + 5 chars for initialization = 16 chars

Use set data types and their operators

If ordering isn't important, then use sets instead of arrays or lists for more concise statements. Unfortunately you are limited to a maximum of 256 elements in a set

+  The union of two sets
*  The intersection of two sets
-  The difference of two sets
=  Tests for identical sets
<> Tests for non-identical sets
>= Is one set a subset of another
<= Is one set a superset of another
in Test for set membership of a single element

The in operator is particularly useful when testing if a variable equals any one of possible values. Silly example using in and .. (the range operator):

// expensive:
if ( A = 1 ) or ( A = 2 ) or ( A = 3 ) or ( A = 6 ) then ...;
if ( A > 0 ) and ( A < 4 ) or ( A = 6 ) then ...;

// better:
if A in [ 1 .. 3, 6 ] then ...;


Haskell, 32 bytes

(filter(even.floor.sqrt)[0..]!!)

Try it online!


Java (JDK 10), 191 bytes

L->S->{int m[]=new int[9],z=0,Z=0,l=0;for(m[0]++;l++<L;z+=--m[z]<1?1:0)m[Z=~-l/2-l/19]+=l<12?2:l>17?1:1+l%2;l=0;for(int s:S){if(--s>Z)l++;Z-=--m[Z>0?Z:0]<1?1:0;}for(int i:m)l|=i;return l==0;}

Try it online!

Input requirement: the spell list must be ordered from greatest spell levels to the lowest one.

Explanations

L->S->{                                        // Curried-lambda with 2 parameters: sorcerer-level and spell list
 int m[]=new int[9],                           // Declare variables: m is the max level  of each spell.
     z=0,                                      // z is the minimum spell level of the maximized spell list.
     Z=0,                                      // Z is the maximum spell level for the current level.
     l=0;                                      // l is first a level counter, then a reused variable
 for(m[0]++;l++<L;z+=--m[z]<1?1:0)             // for each level, compute the maximized known spells.
  m[Z=~-l/2-l/19]+=l<12?2:l>17?1:1+l%2;        //
                                               // Now m is the row for level L in the table below.
 l=0;                                          // l now becomes an error indicator
 for(int s:S){                                 // This loop checks if the spell-list matches the spells allowed for that level.
  if(--s>Z)l++;                                // Spell-levels are 1-based, my array is 0-based so decrease s.
  Z-=--m[Z>0?Z:0]<1?1:0;                       // Remove a max level if we've expleted all the spells, avoiding exception.
 }                                             //
 for(int i:m)l|=i;                             // Make sure there are no more values in m.
 return l==0;                                  // Return true if no miscount were encountered.
}

Table 1: Maximized spell distribution for each sorcerer-level, used from Axoren's answer on the linked question.

Credits

Saved 14 bytes thanks to Kevin Cruijssen.


JavaScript (ES6), 130 125 113 bytes

f=
s=>s==[...s].reverse(s=`()<>[]{}qpbd/\\`).map(c=>s[s.indexOf(c)^1]||/[- !"'+*.:=AHIMOT-Y^_ovwx|]/.exec(c)).join``
<input oninput=o.textContent=f(this.value)><pre id=o>

Edit: Saved 5 bytes thanks to @Arnauld. Saved a further 11 bytes thanks to @YairRand.


CJam, 27 24 bytes

l~:Xfe<0fe>_[XT]:Y--Y/,(

Input format is the list of pendulum positions followed by l on a single line.

Test it here.

Explanation

l~     e# Read and evaluate input.
:X     e# Store track length in X.
fe<    e# Clamp each position to X from above.
0f>    e# Clamp each position to 0 from below.
_      e# Duplicate.
[XT]   e# Push the array [X 0].
:Y     e# Store it in Y.
-      e# Set subtraction from the clamped input list. This gives all the
       e# intermediate values.
-      e# Another set subtraction. Remove intermediate values from input list.
Y/     e# Split remaining list around occurrences of ...X 0...
,(     e# Count them and decrement. This is the number of times the pendulum
       e# moved from X to 0.


JavaScript (ES6), 41 40 39 38 bytes

Saved a byte thanks to @Neil, another thanks to @user81655

x=>x.map(c=>c<x[++i]>d?x[d=i]:c,d=i=0)

Just when it seems reduceRight might finally have a chance, .map shows up yet again...


GolfScript, 120 (136 characters - 16 bonus)
n%{':'-{48^71%}%16base}%-1+2.7??:W+${\)1$1$-{}{129,-1%{2\?.2$)<3$@%!&}?:~2$W+16base(;{.48+\9>39*+}%4/':'*'/'+128@-+puts\2~?+\2~?-}/;;}*;

Assumes the addresses as separate lines on STDIN. A considerable amount of the code is actually used to input/output in the correct format. The algorithm itself is quite simple and described here.


JavaScript (ES6), 68 bytes

f=s=>s&&f(s.replace(/\d\D+$/,m=>(s=m.slice(0,i=++m[0]),m.slice(i))))+s

Explanation

Based on a simple concept:

Match the last digit n followed by n letters in the input string
Remove it from the input string and add it to the start of the output string
Repeat until the input string is empty

Recursion was the shortest way to do this in JavaScript.

f=s=>
  s&&                        // if the input string is empty, return the empty string
  f(                         // prepend the constituent before it
    s.replace(/\d\D+$/,m=>(  // match the last digit followed by every remaining letter
      s=m.slice(0,n=++m[0]), // set s to the constituent (n followed by n letters)
                             // (we must use s because it is our only local variable)
      m.slice(n)             // replace the match with only the letters after it
    ))
  )+s                        // append the constituent
<input type="text" id="input" value="9long3yes4lo2ngwords11here" />
<button onclick="result.textContent=f(input.value)">Go</button>


Python3 - 325 chars

import sys
r=[(0,32)]
for b in (int('%02x'*4%tuple(int(x) for x in y.split('.')),16) for y in sys.stdin):
 i=0
 while i<len(r):l,q=r[i];o=2**q//2;m=l+o;h=m+o;k=l<=b<h;r[i:i+1]=[(l,q-k),(m,q-k)][0:k+1*(not l==h==b)];i+=1-k
for n,m in r:print('%s/%d ALLOW'%('.'.join(str(int(('%08x'%n)[i:i+2],16)) for i in range(0,8,2)),32-m))


Vim, 34 bytes

@wO-<Esc><C-V>(d@hpqq<C-O>+D@"G+bs<C-R>=!@.<CR><Esc>@qq@q

Input is width in the "w register, height in the "h register, and the 1-indexed moves in the buffer, one per line. Output is a transposed grid with - as blank, 1 as player 1, and 0 as player 2 (with a bunch of newlines at the end).

To clarify, if you want Height 6, Width 7: type qh6qqw7q before starting.

@wO-<Esc><C-V>(d@hp: Use the height and width in the registers to make a transposed grid of -s. Note that ( is run from the last line of the grid, one above the moves. This sets up the jump list.
<C-O>+D@"G: The <C-O> uses the jump list to move back to before the last G, always to the line above the next number. @"G moves to the line number indicated by the deleted text. + not only moves the cursor, but it's the failure point; when it runs on the last line, the macro dies.
+b: This maneuver goes to the first - in the line, even if it's the first character. (f- would go to the second character if the line was still all -s.)
s<C-R>=!@.: Replaces a - with the last insert @., but NOTted. First time through, the previous insert of - will NOT to 1 because that's the way Vim is. After that, it will alternate between 0 and 1.

Example

Start with the moves in the buffer:

4
4
5
5
6
7
3

Make sure you're on line 1 with gg, clear "q with qqq, set up the registers for width 7, height 6 with qw7qqh6q. Then run the solution above and get the following output (with newlines at the end):

------
------
1-----
10----
10----
1-----
0-----