CJam, 30 29 bytes

0l~_,m!{_2$=(@@2$+3$\t}*,(])&

Uses 0-based inputs and prints the index of the terminal node if the terminal node is ever reached.

This is super inefficient. You wouldn't want to test this on inputs with more than 10 nodes. The test link below uses 2\# instead of m! which isn't quite enough for all possible inputs, but it passes all test cases in a few seconds (and one would have try fairly hard to find a test case that doesn't pass).

Try it online!

Explanation

This doesn't have any loop or terminal detection. Instead we simply iterate the system often enough that we know we've hit a loop, recording the history, and then we check whether we've reached the terminal node at any point.

If we don't visit the terminal node, we only modify the states of N-1 nodes (if N is the total number of nodes). Each of the nodes has two different states, and the train can be on any one of those nodes (thanks to ais523 for pointing this out), so there are 2(N-1)*(N-1) different states we can visit before entering a loop or reaching the terminal node. Since we start from one of these states we know that after 2(N-1)*(N-1) transitions, we've either entered a loop or reached the terminal node.

That's a fairly lengthy expression. However, N! is almost never less than 2(N-1)*(N-1). In fact, the only N for which that's the case is 3, where the number of possible states is 8 and N! gives only 6. That said, it's not necessarily the case that it's possible to reach all theoretical states in any of the possible inputs. It's fairly easy to check this exhaustively: the neighbours of the last node are always irrelevant, so we can simply consider all inputs of the form [[a b] [c d] [0 0]] where at least one of abcd contains 2 (otherwise, the terminal state is guaranteed to be unreachable). There are only 65 of these states, and I ran them through a slightly modified program, which finds the first transition after which the terminal state is reached (or -1 if it's unreachable). As it turns out, it's impossible to construct an input which requires more than 6 transitions to reach the terminal state, just what we need. Hence, I'm using N! as the upper bound of iterations.

0      e# Push a zero. This is the initial node index of the train.
l~     e# Read and evaluate the input.
_,m!   e# Compute the factorial of N.
{      e# Run this block N! times.
  _    e#   Copy the list of LR pairs.
  2$=  e#   Copy the current node index and extract the corresponding pair.
  (    e#   Pull off the first neighbour - this is where the train moves next.
  @@   e#   Pull list of pairs and the list with the other neighbour on top.
  2$+  e#   Copy the first neighbour and append it. This effectively, reverses
       e#   the pair so that next time the other destination from the current
       e#   node is picked.
  3$   e#   Copy the current node again.
  \    e#   Swap it with the reversed pair.
  t    e#   Write the reversed pair back into the full list of pairs.
       e#   In summary, one iteration extracts the first neighbour of the
       e#   current node and leaves it on the stack, and swaps the neighbours
       e#   of that node for future visits.
}*     e# At the end, we've got all the reachable nodes on the stack, and
       e# the list of all pairs still on top.
,(     e# Compute N-1 from the list of pairs.
])     e# Wrap everything in a list and remove N-1 from it.
&      e# Compute the set intersection all reachable nodes with N-1.


Finding "sub-palindromes" 2: subsequences.

Haskell (119)
import Data.List
main=interact f
f a=show.nub.filter(\x->(not$isInfixOf a x)&&x==reverse x&&length x>1)$subsequences a

Isn't too difficult with a builtin subsequences and nub... :)


JavaScript ES6, 91 93 104 133 148

Edit2 2 bytes saved thx user81655

Edit Using more strings and less arrays

Test running the snippet below in an EcmaScript 6 compliant browser

f=s=>[...s].map(c=>l+=c<')'||-(o[l]=(o[l]||'')+c,c<'a'),o=[],l=0)&&(o+'').match(/\w+/g)||[]

// Less golfed

u=s=>{
  o=[]; l=0;
  [...s].map(c=>{
    if (c>'(') // letters or close bracket
      o[l]=(o[l]||'')+c, // add letter or close bracket to current level string
      l-=c<'a' // if close bracket, decrement level
    else
      ++l // open bracket, increment level
  })
  o = o+'' // collapse array to comma separated string
  return o.match(/\w+/g)||[] // fetch non empty strings into an array
}

// TEST
console.log=x=>O.innerHTML+=x+'\n'

;[ 'a(b)c(d)e'                    // ['ace', 'b', 'd']
 , 'a(b(c)d)e'                    // ['ae', 'bd', 'c']
 , 'a((((b))))'                   // ['a', 'b']
 , 'a()b'                         // ['ab']
 , ''                             // []
 , 'a'                            // ['a']
 , '(((a(b)c(d)e)f)g)h'           // ['h', 'g', 'f', 'ace', 'b', 'd']
 , 'ab(c(((d)ef()g)h()(i)j)kl)()' // ['ab', 'ckl', 'hj', 'efg', 'i', 'd']
].forEach(t=>console.log(t +" -> " + f(t)))


Python 3, 264 Bytes
I'm not good at code golf so I'm confident this won't be the best Python 3 answer. This uses recursion and an ordered dict with all the words for each length.
from collections import*
def f(i):
 d = defaultdict(list)
 for l in i: x = "".join(c for c in l if c.isalnum());d[len(x)].append(x)
 n = (sorted(["".join(d[z]) for z in d.keys()], key=len))
 if n == i:return "\n".join(n)
 return f(n)
print(f(eval(input())))

Takes input from stdin as a list, for example, test it with this list:
['A', 'small', 'one', 'that', 'contains', 'equal', 'length', 'strings', 'for', 'the', 'special', 'rule']

Will output:
A
length
oneforthe
smallequal
stringsspecial
thatrulecontains


Jelly, 15 bytes

LḶµ+.×þ÷L-*Ḟ³æ.

Try it online!

This uses the identity that cos(pi * x) = real(e^(i * pi * x)) = real((-1)^x)

Explanation

LḶµ+.×þ÷L-*Ḟ³æ.  Input: array A
L                Length
 Ḷ               Lowered range - [0, 1, ..., len(A)-1]
  µ              Begin a new monadic chain
   +.            Add 0.5
     ×þ          Outer product using multiplication
       ÷         Divide by
        L        Length
         -*      Compute (-1)^x
           Ḟ     Real part
             æ.  Dot product with
            ³    The first argument (A)


Take advantage of implicit endings!

In V, every single command will be implicitly finished if you don't actually finish out the command. For example, if the program ends in insert mode, the <esc> will be filled in automatically. Usually, this doesn't make any difference. However, if you have a count before the i, you have to actually hit <esc> at the end for the text to be inserted multiple times. So you can do 2i2i for a quine, whereas in vim you would need 2i2i<esc>, which is no longer a quine.

This also applies to ex commands, and psuedo ex-commands such as compressed regexes. So where vim needs

:foo<cr>

V can do

:foo

if it's at the end of the program.

But here is where it gets really cool: The implicit ending applies several layers deep. For example, consider this command:

òçfoo/óa

This translates to:

ò           " Recursively:
 çfoo/      "   On every line matching 'foo'
      óa    "     Remove the first 'a'

Without implicit endings, the ó needs a <cr>, the ç needs a <cr>, and the ò needs another ò. But none of these are needed with implicit endings! The interpreter will fill in the needed ò, the recursive command will fill in the <cr> that ç needs, and the ç command will fill in the <cr> that ó needs. This saves us 3 bytes.


Python 3, 109 bytes

from datetime import*
i=input()
z=date(*map(int,i.split())).toordinal()-727806
print([i,'1993 09 %d'%z][z>9])

Try it online!

-59 bytes thanks to notjagan
-3 bytes thanks to Mr. Xcoder
-2 bytes thanks to officialaimm
-12 bytes thanks to Jonathan Allan


Haskell, 37 34 bytes

s#l@(c:d)|s>=c=(s-c)#l+s#d
s#_=0^s

Usage example: 26 # [1,5,10,25] -> 13.

Simple recursive approach: try both the next number in the list (as long as it is less or equal to the amount) and skip it. If subtracting the number leads to an amount of zero, take a 1 else (or if the list runs out of elements) take a 0. Sum those 1s and 0s.

Edit: @Damien: saved 3 bytes by pointing to a shorter base case for the recursion (which also can be found in @xnors answer).


Python 3.8 (pre-release), 65 bytes

lambda s,i,t:[s[(n:=[-t,t][i=='l']):]+s[:n],s[::(-1)**t]][i=='R']

Try it online!

Abuses the de-facto ternary statement [a,b][condition].

If i=='R':

Return the string, read with step (-1)**t. This is -1 (reversed) for odd t and 1 (not reversed) for even t.

Else:

Let n be [-t,t][i=='l']. This is t when left-shifting and -t otherwise (right-shifting).
Return the string, spliced accordingly: s[n:] + s[:n]. Thanks to Python's negative indexing, this works like a charm for both cases.


Charcoal,  52 ... 45  42 bytes (270 votes)

A list of states that optimizes the compression with Brotli.

”}∧J⟧´⪫3⎚>↘≡ＶＮb7>¹l↙⁵Þ7/…ξ⌕↑τc<y\MΦＧＣ＆⸿Dρ~

Try it online!

Output

Texas
Pennsylvania
Georgia
Illinois
Washington
Indiana
California
Arizona
Michigan
Virginia
Florida
New York

Node.js script

The initial list was found with the following Node.js script that shuffles the 30 most efficient states, extracts the shortest leading sub-list with a score greater than or equal to 270, joins it with \r and invokes the Brotli compressor on the resulting string.

It was optimized some more by shuffling the most promising sub-list to find an order offering the best compression.

let states = [ ['Alabama', 9], ['Alaska', 3], ['Arizona', 11], ... ];

states =
  states.map(a => [a[0], a[1], a[1] / a[0].length])
  .sort((a, b) => b[2] - a[2])
  .slice(0, 30);

const zlib = require('zlib');

let bestLen = 1 / 0, bestScore = 1 / 0,
    list, score, str, pack;

while(1) {
  for(let i = states.length - 1; i > 0; i--) {
    let j = Math.floor(Math.random() * (i + 1));
    [ states[i], states[j] ] = [ states[j], states[i] ];
  }

  for(
    let n = 1;
    (score = (list = states.slice(0, n)).reduce((p, c) => p + c[1], 0)) < 270;
    n++
  ) {}

  str = list.map(s => s[0]).join('\r');
  pack = zlib.brotliCompressSync(Buffer(str));

  if(pack.length < bestLen || (pack.length == bestLen && score <= bestScore)) {
    bestLen = pack.length;
    bestScore = score;
    console.log(bestLen, bestScore, str.split('\r').join('\\r'));
  }
}


Calculate the sine of a float (in radians)…

Python 83 69

Based on Bhaskara I's sine approximation formula

Implementation

def f(x):p=3.14;x,s=x%p,(4,-4,4)[int(x/p)];return s/(12.34/x/(p-x)-1)

Ungolfed

def apxsine(radian):
    pi = 3.14 # Approximate to 2 decimal places
    sign = (4,-4,4)[radian % pi]
    return sign / (12.34/radian/(pi - radian) - 1))

Deduction

Demo

>>> from math import pi, sin
>>> any(round(abs(f(e) - sin(e)), 2) for e in (e/180.*pi for e in range(0,360)))
False

JUst realized that if I would have opted for Euler's formula route, the code would be shorter (49 characters). But then it uses Complex numbers and am not sure if the call to the real method would be valid in the current question context.

f=lambda x:((2.72**(x*1j)-2.72**(-x*1j))/2j).real


Jelly, 78 bytes
“'ĖøÆḳƙ’ḃ7ṣ6+\+3r/ċ€×“½½½½©ÐÇı‘
“ŀỊẋ8ƒ³ẈRɼƈñqẋẏȧɱḌ<ṄỴḳ⁾ÆʋeẒĊ'@ƬØƓƝ}ḟ¬»ỴW€ẋ"ÇẎX

A monadic link accepting an integer (in [4,11]) which returns a list of characters.
Try it online!
How?
Creates the heat ranges of the planets as a list of lists and counts the occurrences of the input heat in those lists to get a list of zeros and ones representing which planet types are possible, then multiplies by the likelihood numbers of the eight planet types to get the distribution. The distribution is used to repeat the planet type names, and finally a uniform random choice is made.
“'ĖøÆḳƙ’ḃ7ṣ6+\+3r/ċ€×“½½½½©ÐÇı‘ - Link 1, getDistribution: integer
“'ĖøÆḳƙ’                        - base 250 integer = 39824688429662
        ḃ7                      - to bijective-base 7 = [1,1,2,4,7,1,4,4,6,2,2,2,2,1,5,3,3]
          ṣ6                    - split at sixes = [[1,1,2,4,7,1,4,4][2,2,2,2,1,5,3,3]]
             \                  - cumulative reduce with:
            +                   -   addition = [[1,1,2,4,7,1,4,4][3,3,4,6,8,6,7,7]]
              +3                - add three = [[4,4,5,7,10,4,7,7],[6,6,7,9,11,9,10,10]]
                 /              - reduce with:
                r               -   inclusive range = [[4,5,6],[4,5,6],[5,6,7],[7,8,9],[10,11],[4,5,6,7,8,9],[7,8,9,10],[7,8,9,10]]
                  ċ€            - count (input) in €ach e.g. for 5: [1, 1, 1, 0,0, 1, 0, 0]
                     “½½½½©ÐÇı‘ - list of code-page indices        [10,10,10,10,6,15,14,25]
                    ×           - multiply                         [10,10,10, 0,0,15, 0, 0]

“ ... »ỴW€ẋ"ÇẎX - Main link: integer
“ ... »         - compressed string = "Ice\nIce Giant\nGaia class\nDense Atmosphere\nLava\nGas Giant\nIron\nDesert"
       Ỵ        - split at new lines = ["Ice","Ice Giant","Gaia class","Dense Atmosphere","Lava","Gas Giant","Iron","Desert"]
        W€      - wrap €ach in a list
            Ç   - call last link (1) as a monad e.g. for 5: [10,10,10,0,0,15,0,0]
           "    - zip with:
          ẋ     -   repeat e.g. for 5:  [["Ice","Ice","Ice","Ice","Ice","Ice","Ice","Ice","Ice","Ice"],["Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant"],["Gaia class","Gaia class","Gaia class","Gaia class","Gaia class","Gaia class","Gaia class","Gaia class","Gaia class","Gaia class"],["Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant"]]
             Ẏ  - tighten               ["Ice","Ice","Ice","Ice","Ice","Ice","Ice","Ice","Ice","Ice","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Ice Giant","Gaia class","Gaia class","Gaia class","Gaia class","Gaia class","Gaia class","Gaia class","Gaia class","Gaia class","Gaia class","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant","Gas Giant"]
              X - a random choice from that list


Snails, 40 39 bytes
\#{z|=(ul.ul.`,l~a~)(l.a3|.a|d.ea5}.,\#

\#    ,, match '#'
{
  z |  ,, Either turn in any octinilear direction, or do all the other stuff before the }
  =(   ,, If this assertion succeeds, the starting cell is an "upwards-pointing triangle"
    ul.ul.`,  ,, Go one cell up or left twice, any number of times.
              ,, This should have been one byte shorter with ul.`2 , or ul.`2+? but
              ,, the parsing of ` is buggy.
    l~a~   ,, Check that we are on the top-left cell by matching out-of-bounds to the left and then northeast
  )
  ( l.a3 |  ,, Move leftward once, then set direction to northwest; or
    .a   |  ,, Move right (the initial direction) once, then set direction to northeast; or
    d.ea5   ,, Move down once, then set direction to either northwest or northeast
}
.,    ,, Match any number of arbitrary chars (moving in the current direction)
\#    ,, match '#'


R, 287 286 273 269 bytes

function(C,x='',`[`=gsub,`!`=intToUtf8,`?`=utf8ToInt){for(k in el(strsplit(C,'\\|'))){B=eval(parse(t='^.'['','(?<=.)>$'['readLines(,1)','[@#](.+)'['"\\1"',k],,T]]));x=switch((?substr(k,1,1))%%13-2,strrep(x,B),paste0(x,B),,B['',x,f=T],!rev(?x),print(x),,!sample(?x))};x}

Try it online!

-1 thanks to @Kirill L.
-4 thanks to @Giuseppe

Unrolled code and explanation :

function(C){                                      # C is the string manipulation expression
  x = ''                                          # initialize x = ''
  tokens = el(strsplit(C,'\\|'))                  # split C by pipe '|'
  for(k in tokens){                               # for each token k
    arg2 = k
    arg2 = gsub('[@#](.+)','"\\1"',k)             # replace @X or #X with "X" (in quotes)
    arg2 = gsub('(?<=.)>$','"readLines(,1)"',
                 arg2,perl=T)                     # replace > with readLines(,1)
    arg2 = gsub('^.','',arg2)                     # remove the first character
    B = eval(parse(t=arg2))                       # evaluate the string : this will be our
                                                  # second argument B
    A = substr(k,1,1)                             # take the first character :
                                                  # i.e. the main command (+,-,! etc)
    x = switch(A,                                 # switch on the main command, execute the
            '+'=paste0(x,B),                      # corresponding expression and
            '!'=intToUtf8(rev(utf8ToInt(x))),     # store the result into x
            '*'=strrep(x,B),                      # Note: in the actual code we switch on
            '-'=B['',x,f=T],                      # the utf8 value MOD 13-2 of the command
            '$'=intToUtf8(sample(utf8ToInt(x))),
            '<'=print(x)
        )
    }
    x                                             # return x (and print it implicitly)
}


Foo → gs2 → M → Jelly → Retina → Aeolbonn → Par → Actually → Sprects → sed → Universal Lambda → Lines → /// → m4: 19/13 ≈ 1.4615 points

"“GḋÞḊCøẉYỴ⁴ñ<ȯƥ»Ṿ¦

All answers are given in the Jelly code page. ¶ represents a newline.

Mechanism

  Language      Code
 ——————————————————————————————————————
  Foo           "“GḋÞḊCøẉYỴ⁴ñ<ȯƥ»Ṿ¦
  gs2           “GḋÞḊCøẉYỴ⁴ñ<ȯƥ»Ṿ¦
  M             “GḋÞḊCøẉYỴ⁴ñ<ȯƥ»Ṿ
  Jelly         “¶:`".c Rube Goldberg#\/”
  Retina        ¶:`".c Rube Goldberg#\/
  Aeolbonn      :`".c Rube Goldberg#\/
  Par           `".c Rube Goldberg#\/
  Actually      ".c Rube Goldberg#\/
  Sprects       .c Rube Goldberg#\/
  sed           c Rube Goldberg#\/
  U.Lambda       Rube Goldberg#\/
  Lines         Rube Goldberg#\/
  ///           Rube Goldberg#/
  m4            Rube Goldberg#

EDIT: Oops, there was an error in the Pyth program. I replaced Pyth and GolfScript by Par.

EDIT 2: Added GNU m4.

EDIT 3: Added Foo and M.


Use functions before consumed by operators

When calculating the Catalan number, I used this trick in my Jellyfish answer:

p
%C+
 &
>+i

The > function is taking + as argument, while the & takes the same + as functional argument.

As a result, the + that the > gets is unary, while the & makes + binary to be used by C.


Haskell, 45 42 bytes

y#(e:s)=[e|any(==e)y,all(/=e)s]++y#s
_#x=x

Try it online!

Edit: -2 bytes thanks to @Ørjan Johansen, -1 byte thanks to @dfeuer.


Minimum number of platforms required for a railway station

Python, 62 bytes

lambda l:max(sum(a-b^b-h^h-a<1for a,b in l)for h in range(24))

Try it online!
Golfing Surculose Sputum's solution. The new part is a-b^b-h^h-a<1 to check whether the time h lies in the interval from a to b taken cyclically, that is, their sorted ordering is a cyclic permutation of [a,h,b]. To do this, we check whether an odd number of the differences a-b, b-h,h-a are negative. I first did this with multiplication (a-b)^(b-h)^(h-a)<1. But, xor (^) lets us do the same and cuts parens with better precedence.


C (gcc) on *nix, 73 71 bytes

i;main(c,v)int**v;{for(c=open(v[1],0);read(c,&i,1);printf("%02X ",i));}

Try it online! Test suite

-2 bytes thanks to Johan du Toit

This relies on O_RDONLY == 0 and on int_one == 1 where int int_one; *(char*)&int_one = 1;.


Python 3, 35 bytes

lambda n:int((n**.5-.75)**.5+.5)**4

Try it online!

How it works

The value n at which the output switches from (k − 1)4 to k4 satisfies √(√n − 3/4) + 1/2 = k, or n = ((k − 1/2)2 + 3/4)2 = (k2 − k + 1)2 = ((k − 1)4 + k4 + 1)/2, which is exactly the first integer that’s closer to k4.

(Works for all n ≤ 4504699340341245 = (81924 + 81934 − 7)/2 > 252, after which floating-point roundoff starts to break it, even though it works mathematically for all n.)


C, 139 137 chars, 67 tokens

i,n;                                                      // 2 tokens
main(c){                                                  // 2 tokens
        while(~(c=getchar()))                             // 5 tokens
                n=strchr("([{}])",c)?                     // 11 tokens
                        n=c%4!=1,                         // 7 tokens
                        i+=n*4-2,                         // 7 tokens
                        printf("\n%*s%c"+n,n?1:i,"",c)    // 15 tokens
                :                                         // 1 token
                        !printf("\n%*s%3$c"+!n*4,i,"",c); // 17 tokens
}

Logic:

Read until EOF (detect it because ~EOF==0).
If parenthesis, check open/close (for c in ")]}", c%4==1), update indentation (i), print with some whitespace.
If not, print the character, possibly prefixed by newline and indentation (n is true after parenthesis).


Magician, Java

public class Magician{
    public static void main(String[] args){
        System.out.println(720);
    }
}

The number 720 is magical.

This is was meant to test the controller and is not a serious entry.


Are they connected by a Brussels choice?

Retina, 38 bytes
L$w`0|[1-9]\d*
$`$.(*2*)$'
m`^(.+),\1$

Try it online! Link includes test cases. Outputs 0 for Falsey, non-zero for Truthy. Explanation:
L$w`0|[1-9]\d*

Match all integer substrings of both inputs, including 0 but not integers beginning with 0.
$`$.(*2*)$'

List the result of doubling that substring only.
m`^(.+),\1$

Check to see whether this produces any pairs of equal integers.


Desmos, 22 bytes

r=\sqrt{\sin 2\theta }

Try it here! Desmos is a graphing tool. This plots the polar equation:

which draws a lemniscate shape.


JavaScript (Node.js),  191 ... 166  164 bytes

Saved 2 bytes thanks to @grimy.

Returns the \$N\$th term.

n=>(g=(x,y)=>n--?g(Buffer('QPNP1O?O@242Q3C3').map(m=c=>g[i=4*((x+=c%6-2)*x>(y+=c%7-2)*y?x:y)**2,i-=(x>y||-1)*(i**.5+x+y)]|i>m||(H=x,V=y,m=i))&&H,V,g[m]=1):m+1)(1,2)

Try it online! or See a formatted version

How?

Spiral indices

In order to convert the coordinates \$(x,y)\$ into the spiral index \$I\$, we first compute the layer \$L\$ with:

$$L=\max(|x|,|y|)$$

Which gives:

$$\begin{array}{c|ccccccc}
&-3&-2&-1&0&+1&+2&+3\\
\hline
-3&3&3&3&3&3&3&3\\
-2&3&2&2&2&2&2&3\\
-1&3&2&1&1&1&2&3\\
0&3&2&1&0&1&2&3\\
+1&3&2&1&1&1&2&3\\
+2&3&2&2&2&2&2&3\\
+3&3&3&3&3&3&3&3
\end{array}$$

We then compute the position \$P\$ in the layer with:

$$P=\begin{cases}
2L+x+y&\text{if }x>y\\
-(2L+x+y)&\text{if }x\le y
\end{cases}$$

Which gives:

$$\begin{array}{c|ccccccc}
&-3&-2&-1&0&+1&+2&+3\\
\hline
-3&0&1&2&3&4&5&6\\
-2&-1&0&1&2&3&4&7\\
-1&-2&-1&0&1&2&5&8\\
0&-3&-2&-1&0&3&6&9\\
+1&-4&-3&-2&-3&-4&7&10\\
+2&-5&-4&-5&-6&-7&-8&11\\
+3&-6&-7&-8&-9&-10&-11&-12
\end{array}$$

The final index \$I\$ is given by:

$$I=4L^2-P$$

NB: The above formula gives a 0-indexed spiral.

In the JS code, we actually compute \$4L^2\$ right away with:

i = 4 * (x * x > y * y ? x : y) ** 2

And then subtract \$P\$ with:

i -= (x > y || -1) * (i ** 0.5 + x + y)

Moves of the wildebeest

Given the current position \$(x,y)\$, the 16 possible target squares of the wildebeest are tested in the following order:

$$\begin{array}{c|cccccccc}
&-3&-2&-1&x&+1&+2&+3\\
\hline
-3&\cdot&\cdot&9&\cdot&11&\cdot&\cdot\\
-2&\cdot&\cdot&8&\cdot&10&\cdot&\cdot\\
-1&7&6&\cdot&\cdot&\cdot&12&13\\
y&\cdot&\cdot&\cdot&\bullet&\cdot&\cdot&\cdot\\
+1&5&4&\cdot&\cdot&\cdot&14&15\\
+2&\cdot&\cdot&2&\cdot&0&\cdot&\cdot\\
+3&\cdot&\cdot&3&\cdot&1&\cdot&\cdot
\end{array}$$

We walk through them by applying 16 pairs of signed values \$(dx,dy)\$. Each pair is encoded as a single ASCII character.

 ID | char. | ASCII code | c%6-2 | c%7-2 | cumulated
----+-------+------------+-------+-------+-----------
  0 |  'Q'  |     81     |   +1  |   +2  |  (+1,+2)
  1 |  'P'  |     80     |    0  |   +1  |  (+1,+3)
  2 |  'N'  |     78     |   -2  |   -1  |  (-1,+2)
  3 |  'P'  |     80     |    0  |   +1  |  (-1,+3)
  4 |  '1'  |     49     |   -1  |   -2  |  (-2,+1)
  5 |  'O'  |     79     |   -1  |    0  |  (-3,+1)
  6 |  '?'  |     63     |   +1  |   -2  |  (-2,-1)
  7 |  'O'  |     79     |   -1  |    0  |  (-3,-1)
  8 |  '@'  |     64     |   +2  |   -1  |  (-1,-2)
  9 |  '2'  |     50     |    0  |   -1  |  (-1,-3)
 10 |  '4'  |     52     |   +2  |   +1  |  (+1,-2)
 11 |  '2'  |     50     |    0  |   -1  |  (+1,-3)
 12 |  'Q'  |     81     |   +1  |   +2  |  (+2,-1)
 13 |  '3'  |     51     |   +1  |    0  |  (+3,-1)
 14 |  'C'  |     67     |   -1  |   +2  |  (+2,+1)
 15 |  '3'  |     51     |   +1  |    0  |  (+3,+1)

We keep track of the minimum encountered value in \$m\$ and of the coordinates of the corresponding cell in \$(H,V)\$.

Once the best candidate has been found, we mark it as visited by setting a flag in the object \$g\$, which is also our main recursive function.

On the first iteration, we start with \$x=1\$ and \$y=2\$. This ensures that the first selected cell is \$(0,0)\$ and that it's the first cell to be marked as visited.


J, 27 bytes

([{~]+/&(|@i:)#@[-1+])-:@<:

Try it online!

An example will clarify the high-level approach.

Consider 'ABCDE' f 3

We notice that what we seek is simply the "cross addition" table of 1 0 1 and 3 2 1 0 1 2 3, which looks like this:

4 3 2 1 2 3 4
3 2 1 0 1 2 3
4 3 2 1 2 3 4

We then pull those indexes from the original string: [{~.

All the rest of the code is just boring arithmetic and the use of i: to construct the arguments 1 0 1 and 3 2 1 0 1 2 3.


05AB1E, 5 bytes

A positive number in the form 2n - 1 in binary only consists of 1's.

Code:

b`¹pP

Explanation:

b`      # Push each digit of the binary representation of the number onto the stack
  ¹p    # Check if the input is prime
    P   # Take the product of all these digits

Uses the CP-1252 encoding. Try it online! or Verify all test cases.


Convert C header names to C++ header names

80386 machine code, 13 bytes

Hexdump of the code:

b0 63 86 01 41 3c 2e 75 f9 c6 01 00 c3

Source code (can be compiled by Visual Studio):

__declspec(naked) void __fastcall conv(char s[])
{
    _asm {
        mov al, 'c';            // b0 63
    myloop:
        xchg al, [ecx];         // 86 01
        inc ecx;                // 41
        cmp al, '.';            // 3c 2e
        jne myloop;             // 75 f9
        mov byte ptr [ecx], 0;  // c6 01 00
        ret;                    // c3
    }
}

It converts the string in-place. The code is so simple, it doesn't need to save and restore registers (using only al and ecx, which the fastcall convention allows to clobber).


Python 3, 97 bytes

lambda n:[round(10**(i/n+2-(n<25)))+((.4<i/n<.67)-(.9<i/n<.92))*(n<25)+(i==185)for i in range(n)]

The output values scaled from 1 to 10 are well-approximated by an exponential interpolation:
10**(i/n)

Multiplying by 10 for 6, 12, 24 and 100 for 48, 96, 192 then rounding to the nearest integer
round(10**(i/n+2-(n<25)))

gives the right answers for all but 16 values, which gives errors of ±1.
n   i   est val  diff
6   3   32  33  -1
6   4   46  47  -1
12  5   26  27  -1
12  6   32  33  -1
12  7   38  39  -1
12  8   46  47  -1
12  11  83  82  1
24  10  26  27  -1
24  11  29  30  -1
24  12  32  33  -1
24  13  35  36  -1
24  14  38  39  -1
24  15  42  43  -1
24  16  46  47  -1
24  22  83  82  1
192 185 919 920 -1

For n<=24, most of these errors are for inputs values in the interval 10/24<=i/n<=6/24. There's one other error for n==24 that trickles down to n==12, and one error for n==192. We fudge these errors by adding or subtracting 1 to the estimate.


Implement an API for probability distributions

Ruby, 103

u=b=->*a{a}
o=->f,d{d[2]?(p=o[0,d[0]])*o[f,d[1]]+(1-p)*o[f,d[2]]:(f<a=d[0])?1:(f>b=d[1])?0:(b-f)/(b-a)}

Defines three lambdas, u, b, and o. u and b just create two-element and three-element arrays respectively. o assumes a two-element array is a uniform distribution and a three-element one is a blend of three distributions. In the latter case it calls itself recursively.


What will be on the top of this decorative calendar?


How many partitions contain only perfect squares?


MATLAB 32

i=1:n;i(isprime(i)&isprime(i+6))

n is your number


JavaScript (ES6/Node.js), 664 525 523 chars

f=(w,h)=>{Z=require('sleep');c=a=>console.log(a);X=1;Y=2;D='e';N='|';O={'|':[0,-1],'e':[1,0],'s':[0,1],'w':[-1,0]};S=[N,D,'s','w'];q=d=>F[Y+O[d][1]][X+O[d][0]];b=' '.repeat(w+4),U='  ';F=[b,b].concat([...Array(h)].map(x=>U+N.repeat(w)+U)).concat([b,b]).map(x=>x.split``);for(;;){f=F.map(a=>a.concat());f[Y][X]='@';d=O[D];f[Y-d[1]][X-d[0]]='=';c(f.map(x=>x.join``).join`\n`);if(F[Y][X]==N)F[Y][X]='.';d=O[D],f=q(D),R=S[(S.indexOf(D)+1)%4],r=q(R);(r==N)&&((f==' ')||(f=='.'))?D=R:(X+=d[0],Y+=d[1])
Z.msleep(1E3);c('\033[2J')}}

Unminified with comments:

f=(w,h)=>{
  Z = require('sleep');
  c=a=>console.log(a);
  //mower coordinates
  X = 1;
  Y = 2;
  //mower direction
  D='e'; //n/e/s/w
  N='|';
  //directions with amount of change in [x,y] coordinates
  O = {'|':[0,-1],'e':[1,0],'s':[0,1],'w':[-1,0]};
  //direction short names
  S=[N,D,'s','w'];
  //query for item in specified direction relative to mower
  q=d=>F[Y+O[d][1]][X+O[d][0]];
 //generate field + whitespace
 b=' '.repeat(w+4),U='  ';
 F=[b,b].concat([...Array(h)].map(x=>U+N.repeat(w)+U)).concat([b,b]).map(x=>x.split``);
 for(;;){
    //print the field:
    //make a copy of the field, so we can paste the mower on top of it
    f=F.map(a=>a.concat());
    //print mower head
    f[Y][X]='@';
    //print mower tail
    d = O[D];
    f[Y-d[1]][X-d[0]]='=';
    c(f.map(x=>x.join``).join`\n`);
    //-----
    //move the mower
    if(F[Y][X]==N)F[Y][X]='.';//cut the grass if we stand on some
    d=O[D],//how many fields to move forward
        f=q(D),//item in front of mower
        R=S[(S.indexOf(D)+1)%4],//name of direction if we rotate to the right
        r=q(R);//item to right of mower
    //if there is wall in front of me OR cut grass in front of me and uncut on the right, turn right, else go ahead
    (r==N) && ((f==' ') || (f=='.'))?D=R:(X+=d[0],Y+=d[1])
    Z.msleep(1E3);
    c('\033[2J');
};
}
//test script
f(3,3);

note: I suppose I should get of the 'sleep' package and rewrite with setTimeout to be nodejs independent


Computing a specific coefficient in a product of polynomials

J, 21 19 18 bytes

{ ::0[:+//.@(*/)/>

Try it online!

-1 byte thanks to FrownyFrog

J has a nice geometric idiom for multiplying polynomials, which we
represent as lists of coefficients, with explicit zeroes where needed:

+//.@(*/)

Let's see how this works using the example:

1 3 5 +//.@(*/) 5 3 2

First it creates a multiplication table */:

 5  3  2
15  9  6
25 15 10

And @: then it computes the sums along each diagonal +//. using the Oblique /. adverb:

This works because moving down a diagonal is equivalent to decrementing the
power of one x while incrementing the power of another, meaning that the
numbers along a diagonal represent all the components of some a factor x^n
for some n.

The rest of the solution is just mechanics for the problem as stated:

{ ::0[: <polynomial idiom> />

Since we can have an arbitrary number of polynomials, we represent them as a list of boxes (each box containing one polynomial) and take that as the right arg.  The left arg is the index we want.

Now { ::0 ... is a dyadic hook asking for the index specified by the left arg, after transforming the right arg by everything in ....  And, if you can't find the index, return 0 ::0.

Finally [: <polynomial idiom> /> says to first unbox > the right arg lists, filling any missing coefficients with 0.  Then reduce / that list using the polynomial multiplication idiom.


Python 2, 41 bytes

Saved 3 bytes thanks to @xnor

a,b="ab";exec"print a;a,b=b,a+b;"*input()

Test on Ideone

Simply follows the recursive definition.


Jelly, 7 bytes

ØWṖṗR;/

This is a monadic link that accepts an integer as input and returns an array of strings.

Try it online!

How it works

ØWṖṗR;/  Main link. Argument: n

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


Python 2, 73 70 bytes

A function that takes a string as input and returns a string representation of a Python list. Zero can be represented both by 0 and -0 (when it comes last):

lambda s:`map(len,s.split('0'))`.replace('0, ','-').replace('--','0,')

Explanation

split the input string s on zeroes.
Take the length of each string in the resulting list (using map).

That takes us a long way. Zeroes were separators after all. And the numbers were unary, so len conveniently converts those to decimal. But now we've messed up all the non-separator uses of 0. Luckily, all non-separator uses were leading zeroes so they came after a separator-zero and gave us zero-length strings ('00'.split('0') == ['', '', '']). Those zero-length strings then also became 0 because of the len.

Turn the list into a string (using "reverse quotes"), so we can fix up the mess more easily.
replace each zero that precedes another number by a negative sign on that number instead. That fixes the use of 0 as a sign but it breaks the literal zeroes. Literal zeroes were also preceded by a separator, so they've now become pairs of extra dashes on the next number.
replace each -- back into a 0 element in the "list".


MATL, 59 54 52 bytes

4t:g2I5vXdK8(3K23h32h(H14(t!XR+8: 7:Pht3$)'DtdTX.'w)

Try it online!

Explanation

The code follows three main steps:

Generate the 8x8 matrix

4 0 0 3 0 0 0 4
0 1 0 0 0 2 0 0
0 0 1 0 0 0 3 0
3 0 0 1 0 0 0 3
0 0 0 0 1 0 0 0
0 2 0 0 0 2 0 0
0 0 3 0 0 0 3 0
4 0 0 3 0 0 0 5

Extend it to the 15x15 matrix

4 0 0 3 0 0 0 4 0 0 0 3 0 0 4
0 1 0 0 0 2 0 0 0 2 0 0 0 1 0
0 0 1 0 0 0 3 0 3 0 0 0 1 0 0
3 0 0 1 0 0 0 3 0 0 0 1 0 0 3
0 0 0 0 1 0 0 0 0 0 1 0 0 0 0
0 2 0 0 0 2 0 0 0 2 0 0 0 2 0
0 0 3 0 0 0 3 0 3 0 0 0 3 0 0
4 0 0 3 0 0 0 5 0 0 0 3 0 0 4
0 0 3 0 0 0 3 0 3 0 0 0 3 0 0
0 2 0 0 0 2 0 0 0 2 0 0 0 2 0
0 0 0 0 1 0 0 0 0 0 1 0 0 0 0
3 0 0 1 0 0 0 3 0 0 0 1 0 0 3
0 0 1 0 0 0 3 0 3 0 0 0 1 0 0
0 1 0 0 0 2 0 0 0 2 0 0 0 1 0
4 0 0 3 0 0 0 4 0 0 0 3 0 0 4

Index the string 'DtdTX.' with that matrix to produce the desired result.

Step 1

4        % Push 4
t:       % Duplicate, range: pushes [1 2 3 4]
g        % Logical: convert to [1 1 1 1]
2I5      % Push 2, then 3, then 5
v        % Concatenate all stack vertically into vector [4 1 1 1 1 2 3 5]
Xd       % Generate diagonal matrix from that vector

Now we need to fill the nonzero off-diagonal entries. We will only fill those below the diagonal, and then make use symmetry to fill the others.

To fill each value we use linear indexing (see this answer, length-12 snippet). That means accessing the matrix as if it had only one dimension. For an 8×8 matrix, each value of the linear index refers to an entry as follows:

1   9         57
2  10         58
3  11
4
5  ...       ...
6
7             63
8  16 ... ... 64

So, the following assigns the value 4 to the lower-left entry:

K        % Push 4
8        % Push 8
(        % Assign 4 to the entry with linear index 8

The code for the value 3 is similar. In this case the index is a vector, because we need to fill several entries:

3        % Push 3
K        % Push 4
23h      % Push 23 and concatenate horizontally: [4 23]
32h      % Push 32 and concatenate horizontally: [4 23 32]
(        % Assign 4 to the entries specified by that vector

And for 2:

H        % Push 2
14       % Push 14
(        % Assign 2 to that entry

We now have the matrix

4 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0
0 0 1 0 0 0 0 0
3 0 0 1 0 0 0 0
0 0 0 0 1 0 0 0
0 2 0 0 0 2 0 0
0 0 3 0 0 0 3 0
4 0 0 3 0 0 0 5

To fill the upper half we exploit symmetry:

t!       % Duplicate and transpose
XR       % Keep the upper triangular part without the diagonal
+        % Add element-wise

Step 2

The stack now contains the 8×8 matrix resulting from step 1. To extend this matrix we use indexing, this time in the two dimensions.

8:       % Push vector [1 2 ... 7 8]
7:P      % Push vector [7 6 ... 1]
h        % Concatenate horizontally: [1 2 ... 7 8 7 ... 2 1]. This will be the row index
t        % Duplicate. This will be the column index
3$       % Specify that the next function will take 3 inputs
)        % Index the 8×8 matrix with the two vectors. Gives a 15×15 matrix

Step 3

The stack now contains the 15×15 matrix resulting from step 2.

'DtdTX.' % Push this string
w        % Swap the two elements in the stack. This brings the matrix to the top
)        % Index the string with the matrix


SWI Prolog, 183 characters

m(A,A).
m([i],[i,u]).
m([i,i,i|T],B):-m([u|T],B).
m([u,u|T],B):-m(T,B).
n([m|A],[m|B]):-(m(A,B);append(A,A,X),m(X,B)).
n(A,B):-m(A,B).
s(A,B):-atom_chars(A,X),atom_chars(B,Y),n(X,Y).

How about some Prolog, (since nobody has answered in 6 months).
To run, just use "s(mi,mu)."  The code breaks up atoms into chars, then searches for the solution.


PowerShell v2+, 89 bytes

param($n)for(){$r=-join"$n"["$n".length..0];if(!($n=(($r%$n),($n%$r))[$n-gt$r])){exit}$n}

Iterative solution. Lengthy because there's no easy way to reverse an array, so we stringify it and index on it backwards to store into $r. Then a pseudo-ternary to pull out the appropriate modulo and re-store into $n for the next round. However, if the result is zero, that means the !($n...) will be $true, so we exit instead of $n. The numbers are left on the pipeline and (implicitly) returned as an array, but without an encapsulating pipeline or saving the results into a variable, the default Write-Output sticks a newline between.

Try it online! (Yes, dead serious.)
PowerShell is now on TIO! You gotta give it a second or two, because PowerShell is a beast to startup, but now you, yes you, can verify PowerShell code right in your browser!


Mathematica, 48 68 bytes

Edit: Preprocess is added for accepting string as the parameter.

With the help of Tuples and Entropy, the implementation is both concise and readable.

Entropy[2,{-1,1}~Tuples~Length@#.#]&@Thread@ImportString[#,"Table"]&

where Tuples[{-1,1},n] gives all possible n-tuples from {-1,1}, and Entropy[2,list] gives the base-2 information entropy.

One of the cool things is that Mathematica will actually return an accurate expression:

%["-1 -1 \n -1 -1"]
(* 3/2 *)

Approximate result can be achieved with an extra . added (Entropy[2., ...).


Charcoal, 39 bytes

≔Ｅ⁺θ× ¬﹪Ｌθ³⌕βιθ⭆⪪Ｅ⁺÷θ⁹⁺÷θ³θ﹪ι³¦³§⁺β ↨³ι

Try it online! Link is to verbose version of code. Explanation:

≔               Assign
   θ            Input string
  ⁺             Concatenated with
                Literal space
    ×           Repeated
         θ      Input string
        Ｌ       Length
       ﹪        Modulo
          ³     Literal 3
      ¬         Logical not
 Ｅ              Mapped over characters
             ι  Current character
           ⌕    Position found in
            β   Lowercase alphabet
              θ To variable

     θ                      List of positions
    ÷                       Vectorised integer divide by
      ⁹                     Literal 9
   ⁺                        Concatenated with
         θ                  List of positions
        ÷                   Vectorised integer divide by
          ³                 Literal 3
       ⁺                    Concatenated with
           θ                List of positions
  Ｅ                         Map over values
             ι              Current value
            ﹪               Modulo
              ³             Literal 3
 ⪪                          Split into
                ³           Groups of 3
⭆                           Map over groups and join
                   β        Lowercase alphabet
                  ⁺         Concatenated with
                            Literal space
                 §          Cyclically indexed by
                       ι    Current group
                     ↨      Converted from
                      ³     Base 3
                            Implicitly print


Find the smallest number of participants with resulting percentages

Python 3, 80 bytes

lambda l,p:[i for i in range(1,10**p)if[round(round(e*i)/i,p)for e in l]==l][:3]

Try it online!


Generate a Brainf_ck program that outputs a string of given length


Java 8, 82 80 77 bytes

Class that extends Frame:

ImageIO.write(new Robot().createScreenCapture(bounds()),"png",new File("a"));

Regular Class 98 Bytes:

ImageIO.write(new Robot().createScreenCapture(Frame.getFrames()[0].bounds()),"png",new File("a"));

Uses deprecated bounds() method.


Mathematica
Graphics[{
   Gray, Rectangle[{0, 0}, {78, 50}],
   White, Rectangle[{9, 9}, {69, 50}]}
  ~Join~
  Table[{
    Blend[{Gray, Orange}, x/5],
    Rotate[
     Translate[
      Rectangle[{16, 16}, {61, 25}],
      {0.25x^3 + 0.6x^2 - 0.4x, -0.53x^3 + 3.26x^2 + 12x}],
     -0.05x^2 - 0.04x]},
   {x, 0, 5}]]

I decided to prettify my answer after realizing this isn't code golf. Whoops!
Screenshot:

In related news, I also created what I think the Stack Overflow logo might look like in... THE FUTURE:

Here's the code if anyone wants to play around with it (sorry for the mess):
Graphics3D[{EdgeForm[],
   Opacity[1],
   RGBColor[0.2, 0.2, 0.2], Cuboid[{0, 0, 0}, {78, 4, 50}],
   Cuboid[{0, 4, 0}, {4, 45, 50}],
    Cuboid[{74, 4, 0}, {78, 45, 50}],
   Opacity[1]}
  ~Join~
  Fold[Join, {},
   Table[{Hue[0.15 - i/5/12, i/3, 1],
     Translate[
      Rotate[
       Scale[Cuboid[{16, 16, 16}, {61, 25, 25}], {1, .3, .3}],
       (-.05 ((i*2 - 1.5)*1.25)^2 - .04 ((i*2)*1.2)), {0.3,
        0.8, -1}, {(16 + 61)/2, (16 + 25)/2, (16 + 25)/2}],
      {-((i*2)^2 - (i*2)*4)/2, (i*2)^2*3/2, 0}]},
    {i, 0, 4.5, 0.05}]], Lighting -> "Neutral", Axes -> False,
 Background -> White, Boxed -> False]


Script that outputs a script that prints a given input

pl, 0 bytes
Code:

Try it online!
Explanation:
An empty program in pl is simply a cat program, outputting the exact same as the input.
In pl, all ASCII characters are essentially variables, but when the variable doesn't exist (yet), pl assumes that they are part of a string.


APL (Dyalog Classic), 34 30 bytes

-4 thanks to jimmy23013

4≥+/¨|∘.-⍨,(⍳3)∘.⌽7 ¯1∘.,○⍳3 3

Try it online!

outputs an adjacency matrix with each vertex adjacent to itself

⍳3 3 generate an array of (0 0)(0 1)(0 2)(1 0)(1 1)(1 2)(2 0)(2 1)(2 2)

○ multiply all by π

7 ¯1∘., prepend 7 or -1 in all possible ways

(⍳3)∘.⌽ rotate coord triples by 0 1 2 steps in all possible ways

+/¨|∘.-⍨, compute manhattan distance between each pair

4≥ it must be no greater than 4 for neighbouring facets


Better Hex Color Codes for Your Internet

JavaScript, 86 82 77 bytes

x=>([s,a=0,b=a,c,d,e,f]=x,f?x:e?x+e:[s,a,d||a,c?b:a,d||b,v=c||b,d||v].join``)

just find out that remove recursive save 4 bytes...

idea from @Arnauld save 4 bytes, +1 more bytes


Mathematica, 255 234 206 bytes

I've seen so many 255s while testing this, I'm unreasonably happy about the size of the code. :) And then my ambition to golf it down even further got the best of me...

f=(j=ImageData[Import@#2,t="Byte"];k=(d=IntegerDigits)[j,2,8]~Flatten~2;n=1;(k[[n++,-1]]=#)&/@d[Length@#,2,24]~Join~#&[Join@@d[ToCharacterCode@#,2,8]];ArrayReshape[#~FromDigits~2&/@k,Dimensions@j]~Image~t)&

It's technically a function and not a "program", but then again this is pretty much how you write "programs" in Mathematica, if that concept is even valid there. Call it like

f["my secret", "fully/qualified/cat.png"]

It will return an actual image expression (because that's the most natural way to return an image in Mathematica), so if you want a file, you need to export it:

Export["output-cat.png", f["my secret", "input-cat.png"]]

Here is the required example:

I'd love to show you the decoded message here, but it doesn't fit... so run it through the OP's decoder. ;)

Btw, I could make it work with UTF-8 secrets for just 7 bytes (change ToCharacterCode@# into #~ToCharacterCode~"utf8").

Ungolfed code:

f[secret_, filename_] := (
  bits = Join @@ IntegerDigits[ToCharacterCode[secret], 2, 8];
  bits = Join[d[Length @ bits, 2, 24], bits];
  data = ImageData[Import@#2, "Byte"];
  dims = Dimensions@data;
  data = Flatten[IntegerDigits[data, 2, 8], 2];
  m = n = 1;
  While[m <= Length @ bits,
    data[[n++, -1]] = bits[[m++]]
  ];
  Image[ArrayReshape[FromDigits[#, 2] & /@ data, dims], "Byte"]
)


Jelly, ... 33 bytes

⁾()j
p`j”+Ç$€;;”-;ÇƊ€;®‘©¤Ṅ€
WÇ1¿

Try it online!

Wow, writing a correct submission is hard.

Python pseudocode equivalent:

import itertools

# Jelly: ⁾()j
def wrap_in_parentheses(x):
 return str(x).join(['(',')'])
 # or equivalently, `return '('+str(x)+')'

# Jelly: p`j”+Ç$€;;”-;ÇƊ€;®‘©¤Ṅ€
register = 0
def expand_and_print(expressions):
 # Jelly: p`
 result = list(itertools.product(expressions, repeat=2))

 # Jelly: j”+Ç$€
 result = [wrap_in_parentheses('+'.join(expr)) for expr in result]

 # Jelly: ;
 result.extend(expressions)

 # Jelly: ;”-;ÇƊ€
 result.extend([wrap_in_parentheses('-'+expr) for expr in expression])

 # Jelly: ;®‘©¤
 global register
 register += 1
 result.append(register)

 # Jelly: Ṅ€
 for expr in result:
  print(expr)

 return result

# Jelly: WÇ1¿
expressions = ['0']
while 1:
 expressions = expand_and_print(expressions)


Implement an encoder for RFC 1924 IPv6 Addresses

Pyth, 93 91 bytes

Ks[jkUTrG1G"!#$%&()*+-;<=>?@^_`{|}~")$from ipaddress import*;z=int(ip_address(z))$sm@Kdjz85

Second submission in Pyth!

Can't try online because $ is unsafe.

When tested against the example, produces the expected result:

$ pyth -c 'Ks[jkUTrG1G"!#$%&()*+-;<=>?@^_`{|}~")$from ipaddress import *$$z=int(ip_address(z))$sm@Kdjz85'
1080::8:800:200C:417A
4)+k&C#VzJ4br>0wv%Yp

Edits:

Saved two bytes by replacing $$ with ; and removing space before *

Explanation

First part creates the mapping string and assigns it to K:

0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%&()*+-;<=>?@^_`{|}~

This is done as follows:

Ks[jkUTrG1G"!#$%&()*+-;<=>?@^_`{|}~")
K                                       implicitly assign to K
 s[                                 )   the string joined from the following list
     UT                                 range [0..9]
   jk                                   joined with the empty string: 0123456789
       rG1                              capitalized version of the string G (whole alphabet)
          G                             G itself
           "!#$%&()*+-;<=>?@^_`{|}~"    all other symbols (shorter to declare than generate)

Then, the second part is two pieces of normal python amounting to 47 bytes, to convert the input ipv6 address to a number (because z is accessed later in the code, it is first implicitly assigned to any input value before running the Python code)

*from ipaddress import *$$z=int(ip_address(z))$

Then, the last part converts the resulting number to base 85 as a list and maps every value to the mapping string K:

sm@Kdjz85
     jz85  convert z to base 85
 m         map over the converted number with lambda d:
  @Kd      K[d]
s          join as a string and implicitly print

Pure Pyth, 100 bytes

Ks[jkUTrG1G"!#$%&()*+-;<=>?@^_`{|}~")IgJx=zcz\:kZ=z-z]k=z.n++<zJ]*-8lz]\0>zJ)=zimid16z65536sm@Kdjz85

You can try it here

In order to support leading/middle/trailing ::, I must insert a list of missing zeroes in the correct position in the ip once converted to a list of hex numbers, which takes up more space than the inline Python version. There's room for improvement but I doubt it can beat the other version!

63 bytes version

Doesn't support the :: notation to skip zeroes:

Ks[jkUTrG1G"!#$%&()*+-;<=>?@^_`{|}~")=zimid16cz\:65536sm@Kdjz85

You can try it here

The different part here is converting the ipv6 to a number using base conversions:

=zimid16cz\:65536
         z          read string from input and assign it to z
        c \:        split it at columns
   m                map over the split list with lambda d:
    id16            convert d from base 16 to 10
  i         65536   convert list of ints from base 65536 to 10
=z                  assign result back to z


Mathematica, 48 bytes - 3 = 45

Grid@Tally@Flatten@IntegerDigits@Tuples@Range@#&


Pyth, 25 19 18 bytes

msC_dcs_Cmck/lk2Q2

Online demonstration. It uses an 2D-array of chars.

Array of strings is one char longer (19 bytes). Online demonstration

Explanation:

         m      Q    map each string k in input:
            /lk2        calculate half the line-length: len(k)/2
          ck/lk2        chop k into pieces of length len(k)/2
                        results in two pieces
        C            zip the resulting list
                     results in a tuple ([first half of strings], [second half of strings])
       _             invert the order ([second half of strings], [first half of strings])
      s              sum (combine the two lists to a big one
     c           2   chop them into tuples
m                          for each tuple of strings:
 sC_d                        invert, zip, and sum

The last part is a bit confusing at first. Let's assume we have the tuple ['DEF', 'JKL'] (I use the example from the OP).

    d  (('D', 'E', 'F'), ('J', 'K', 'L'))   just the pair of strings
   _d  (('J', 'K', 'L'), ('D', 'E', 'F'))   invert the order
  C_d  [('J', 'D'), ('K', 'E'), ('L', 'F')] zipped
 sC_d  ('J', 'D', 'K', 'E', 'L', 'F')       sum (combine tuples)


Stax, 294 bytes

ê(·▲[*▬è0↑u■<pá{∞♫┼¢]$Fò╦7τ}αzoN≡ù÷♥R♪♪éé#Ä↑♂¼y>Φp←E├Tì·æ≈ßÿOÄ╩%▼Åp}∞½É÷_~ï♦♪s○╨5╓ok½♪◄}§3vimεå╩p"G4ƒs┬]K╡àbá•Ä◄E°µte\τ╚¥∞LH¥êoc▐I/♥∞íJ{σ↓⌠╢§♥]8<µ6ε∩╠ån¥←A↨⌡↨▼♠áiåcTε╛ëJv⌡♂'┬û▒╟_E2↑☺│╚ê£-vç╘▬╒ì)#Φ¼∟æ∟q⌐▀☻7w_ì~Δc'Ω∙j≡┼Γó2"äV√n◘j≤╦╓ΘiL.,▲♂▌▼∞ccñó╘î←iaΩï)NCøAP┼b_ε☺Cam╥~αDM↕Aä<₧¿é■N/╞τQ╠Γù>b^S>◘á↑

Run and debug it

Here's the approach:

Consider each possible substitution of characters for asterisks.  I'm using upper and lower-case letters, plus the handful of punctuation marks.
Interpret each candidate as a base-91 integer.  Why 91?  It covers the span of possible characters in the input, it's prime, and it's 2 digits.  It just seems good.  I don't know if it's optimal.
Modulus by a carefully chosen denominator. (359473561)  Then check for a the existence of the result in the embedded hash array.  If there's a match, that's the correct substitution.

In order to verify that no incorrect result would be produced, I used a C# program to verify the output for all possible inputs.  It's not very portable, and it's quite long running.  I've been letting it search for more than 24 hours for candidate denominators so far, so it's not really suitable for TIO.  I'm running it in LINQPad.

const string AllChars = " ',-.:ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const int Base = 91;
const int InputCount = 14252;

void Main() {
    string filename = Path.Combine(Path.GetDirectoryName(Util.CurrentQueryPath), "titles.txt");
    var titles = File.ReadAllLines(filename);
    Console.WriteLine("Original titles: {0}", titles.Length);
    Console.WriteLine("All characters: {0}", AllChars.Length);

    var originalHashes = titles.Select(Hash).ToArray().Dump("Original hashes");

    BigInteger candidateMod = 359473561; //BigInteger.One * InputCount * AllChars.Length * AllChars.Length * titles.Length;
    BigInteger? bestMod = null;
    BigInteger failJump = 1;

    var candidateContainer = new DumpContainer(candidateMod).Dump("Candidate");
    var bestContainer = new DumpContainer(bestMod).Dump("Best");
    var rateContainer = new DumpContainer().Dump("Candidates / s");

    int tested = 0;
    var sw = Stopwatch.StartNew();

    while (true) {
        bool success = TestCandidateMod(candidateMod, titles, originalHashes);
        if (success) {
            bestContainer.Content = bestMod = BigInteger.Min(bestMod ?? candidateMod, candidateMod);
            candidateMod = candidateMod * 99 / 100; // reduce by 1%;
        }
        rateContainer.Content = ++tested * 1e3 / sw.ElapsedMilliseconds;
        candidateContainer.Content = --candidateMod;
    }
}

bool TestCandidateMod(BigInteger candidateMod, string[] titles, BigInteger[] originalHashes) {
    var moddedHashes = new HashSet<BigInteger>(originalHashes.Select(h => h % candidateMod));

    bool TitleIsOk(string title) {
        BigInteger originalHash = Hash(title);
        for (int i1 = 0; i1 < title.Length - 1; i1++) {
            BigInteger placeValue1 = BigInteger.Pow(Base, title.Length - i1 - 1);
            foreach (var c1 in AllChars) {
                int offset1 = c1 - title[i1];
                BigInteger hash1 = originalHash + placeValue1 * offset1;
                for (int i2 = i1 + 1; i2 < title.Length; i2++) {
                    BigInteger placeValue2 = BigInteger.Pow(Base, title.Length - i2 - 1);
                    foreach (var c2 in AllChars) {
                        int offset2 = c2 - title[i2];
                        if (offset1 == 0 && offset2 == 0) continue;

                        BigInteger hash2 = hash1 + placeValue2 * offset2;
                        if (moddedHashes.Contains(hash2 % candidateMod)) {
                            return false;
                        }
                    }
                }
            }
        }
        return true;
    }

    return titles.AsParallel().AsUnordered().All(TitleIsOk);
}

BigInteger Hash(string title) => title.Aggregate(BigInteger.Zero, (a, b) => a * Base + b);

Another note about the storage of the embedded hash values in the program.  The hashes are sorted prior to embedding in the array.  I'm using a stax feature called "crammed integer arrays" which is a way of efficiently representing integer arrays.  This representation is able to store differences between elements if that's more efficient, so pre-sorting the values saves some bytes.

Here's the unpacked representation with some minimal comments.

Vl" ',-.:"+:2   all pairs of replacement characters
f   filter
 ;'*/s\$1T  do replacement
 91|E   base-91 digits
 359473561% mod by denominator
 ">m\zR^ehBT}/!P*Nv:0N?s}FGN\:M.RT0r2VVm560$k;!yP<I*&R0_&q6wEcg8)&DsZ_!}&}Y&:Ngv&B::n!g6y &&eej...Z-&J..7!Rso36>y89:*iA*eNHGBmZ5!kiZ5*D(};*Xgkvwqn^(g?!kJib&g$ep!aDaA!Xw$_!w,2E.6NFG6DPat&(u4?28BIRu<bBL\S!ugPf!Ry;&T0\/^y\S{gu;!\0spo!^3!}X0l!i$L5&Z8@|!X4}p.LyU:X2M&PR6Y!k*,[F(&v&(ZJ5Jo0d!RN!hsDFvV.kI*{u@_!a<oGoqsG2}XhJ:2,"!
 #  count occurrences in crammed array


Haskell, 27 bytes

foldr((*).max 1.read.pure)1

Try it online!

Ungolfed with UniHaskell and -XUnicodeSyntax

import UniHaskell

f ∷ String → Int
f = product ∘ map (max 1 ∘ read ∘ pure)

Explanation

I'll start with what I initially had:

product.map(max 1.read.pure)

This is a point-free expression that evaluates to a function taking a string (or a list of characters) s ("301") as an argument. It maps max 1.read.pure over s, essentially taking each character i, injecting it into a list (which makes it a string) (["3", "0", "1"]), then reading it, which evaluates the string ([3, 0, 1]) and finally taking the greater of i and 1 ([3, 1, 1]). Then it takes the product of the resulting list of integers (3).

I then golfed it by a byte with:

foldr((*).max 1.read.pure)1

This works because product is equivalent to foldr (*) 1. Instead of mapping and folding, I combined the two by folding with (*).max 1.read.pure which takes each non-zero digit and multiplies it with the accumulator.


Mathematica, 11 bytes

PartitionsP

Explanation

¯\_(ツ)_/¯


Return the nth digit of the sequence of aliquot series

Mathematica, 51 bytes

Array[##&@@IntegerDigits[Tr@Divisors@#-#]&,#][[#]]&

An unnamed function which takes and returns an integer and uses 1-based indexing. Handles input 10000 instantly.

Explanation

This is a very straight-forward implementation of the definition, making use of the fact that the first n divisor sums are always enough to determine the nth digit. As usual, the reading order of golfed Mathematica is a bit funny though:

Array[...&,#]...&

This generates a list with all the results of applying the unnamed function on the left to all the values i from 1 to n inclusive.

...Tr@Divisors@#-#...

We start by computing the divisors of i, summing them with Tr and subtracting i itself so that it's just the sum of divisors less than i.

...IntegerDigits[...]...

This turns the result into a list of its decimal digits.

##&@@...

And this removes the "list" head, so that all the digit lists are automatically concatenated in the result of Array. For more details on how ## works, see the "Sequences of arguments" section in this post.

...[[#]]

Finally, we select the nth digit from the result.


I multiply the source, you (probably) multiply the output!

R, 66 35 bytes

-29 bytes thanks to digEmAll.

-2 bytes thanks to Giuseppe.

+0->A
x=!0:F
F=F+1
sample(F*x+!x,1)

Try it online!

Check the distribution for N=4.

The key is the rightwards assignment ->. When the code is multiplied \$N\$ times, the first \$N-1\$ calls to sample will be assigned to A, and only the last call will be printed.

Original, more convoluted solution:

R, 66 bytes

T->TT
F=F+1
TT=0
`?`=function(x)if(x)sample(c(1,F),1,,c(1,F-1))
?T

Try it online!

Try it online (repeated 3 times)!

Uses two tricks: 1) call the main function of interest ?, so that we can call it without ending the program with a bracket, and 2) use variables T and TT, with code which starts with T and ends with ?T.

F is the iteration counter. ? is redefined as a function which takes a boolean argument: if the input of ? is TRUE (or T), it does the required random sampling; if the input is FALSE (or 0), it does nothing. The value of TT is defined as 0, so that ?T does the sampling but ?TT does nothing.

When the source is repeated, it looks like this:

T->TT
F=F+1
TT=0
`?`=function(x)if(x)sample(c(1,F),1,,c(1,F-1))
?TT->TT
F=F+1
TT=0
`?`=function(x)if(x)sample(c(1,F),1,,c(1,F-1))
?T

so the middle call ?TT outputs nothing but the final call ?T outputs the random result.


05AB1E, 54 52 47 46 bytes

ÅÉ¹L£D€g__ÏRv"/ \ "yg×N·©úˆyvy4yg-ð×}J®>úˆ}¯R»

Try it online!

Explanation

                                                # implicit input n
ÅÉ                                              # push a list of uneven numbers up to input
  ¹L£                                           # divide into sublists of length 1,2,3...n
     D€g__Ï                                     # remove empty sublists
           R                                    # reverse list
            v                                   # for each sublist
             "/ \ "                             # push the string "/ \ "
                   yg×                          # repeat it len(sublist) times
                      N·©ú                      # prepend (sublist index)*2 spaces
                          ˆ                     # add to global list
                           yv                   # for each number in sublist
                             y4yg-ð×            # prepend spaces until length is 4
                                    }           # end inner loop
                                     J          # join to string
                                      ®>ú       # prepend (sublist index)*2+1 spaces
                                         ˆ      # add to global list
                                          }     # end outer loop
                                           ¯    # push global list
                                            R   # reverse it
                                             »  # join rows by space and columns by newline
                                                # implicitly print

I could have saved 5 bytes with ÅÉ¹L£D€g__ÏRv"/ \ "yg×N·©úˆy4jJðÛ®>úˆ}¯R» if only I'd pushed that bugfix for j I wrote several weeks ago :/


Jelly -u, \$4\times10^{41}\$ bytes
“...”WẈbØ%ỌV

Except instead of ... its \$133390687877217192365177139021057049493695\$ Ɱ characters
More specifically, a score of \$400172063631651577095531417063171148481103\$
How it works
The standard cat program in Jelly is
ƈȮøL¿

Try it online!
If we convert each of these characters to their Unicode code point we get
[392, 558, 248, 76, 191]

Treat this a base \$4294967296 = 2^{32}\$ number and convert it back to decimal to get \$133390687877217192365177139021057049493695\$
The above program has a string consisting of \$133390687877217192365177139021057049493695\$ Ɱ characters. We then take its length, convert it to base \$4294967296\$, convert back to characters and run as Jelly code.
By forcing Jelly to encode the source as UTF-8 rather than using the Jelly code page, multi byte characters are counted as multiple bytes rather than just 1.
This is 100% irreducible. The cat program it encodes is optimal for Jelly, so there's no way to remove any of the Ɱ characters and still create a cat program, and all of the other characters are necessary to correctly convert the string to a program and execute it. More specifically:

Removing either “ or ” will cause syntax errors
Removing the W will cause Ẉ to return a list of lists of \$1\$s rather than the code points in base \$4294967296\$
Removing the Ẉ will mean the program won't ever convert the string to the code points in base \$4294967296\$
Removing any of bØ% will prevent the base conversion happening
Removing Ọ or V will stop the program from converting to characters and running the program

Furthermore, I believe this is the longest you can get using the method of "long string's length in a high base" in Jelly. The base being used must meet the following criteria:

The number isn't "constructed" via commands to be larger, as these commands can be removed and the long string adjusted for the lower base
The number doesn't have digits in it, as characters can be removed to just isolate the lowest digit and the long string can then be adjusted to match this new base

Ø% is the largest constant Jelly has which meets these criteria at \$2^{32}\$, so, as a higher base leads to a longer string, an answer in Jelly cannot beat this one.


Dyalog APL, 6 2 bytes

⊥⍨

Test it on TryAPL.

How it works

⊥ (uptack, dyadic: decode) performs base conversion. If the left operand is a vector, it performs mixed base conversion, which is perfect for this task.

For a base vector b = bn, ⋯, b0 and a digit vector a = an, ⋯, a0, b ⊥ a converts a to the mixed base b, i.e., it computes b0⋯bn-1an + ⋯ + b0b1a2 + b0a1 + a0.

Now, ⍨ (tilde dieresis, commute) modifies the operator to the left as follows. In a monadic context, it calls the operator with equal left and right arguments.

For example, ⊥⍨ a is defined as a ⊥ a, which computes a0⋯an + ⋯ + a0a1a2 + a0a1 + a0, the sum of all cumulative products from the right to the left.

For k trailing ones, the k rightmost products are 1 and all others are 0, so their sum is equal to k.


Jelly, 3 bytes

ḃ9Ḍ

Try it online!

How it works

ḃ9Ḍ  Main link. Argument: n (1-based index)

ḃ9   Convert n to bijective base 9.
  Ḍ  Convert the result from base 10 to integer.


GolfScript, 46 chars

0{`".~#"+.-1%+\.!@@}.~##~.}@@!.\+%1-.+"#~."`{1

Well, this is ugly, but it works.  The output equals the code reversed, and is also a valid GolfScript program which outputs the original code again.

OK, let me try to explain how I constructed it.  First, I started from the quine {".~"}.~, and modified it as in this answer to reverse itself.  To make the output an executable quine in itself, I made a copy of the code before reversing it, and included a # at the end of the code, so that the reversed version at the end became just a comment.  Thus, we get the palindromic quine:

{`".~#"+.-1%}.~##~.}%1-.+"#~."`{

However, by the rules, palindromes are not allowed, so I needed to break the symmetry somehow.  I figured the easiest way would be to include a 0 (which, in itself, is a quine in GolfScript) in the code and flip it to 1 with ! after creating the reversed copy.  Most of the remaining complexity is just ugly stack manipulation to get everything in the right order.


Pyke, 21 bytes
.dↄґ6C65h*325q/Al

Try it here!
     C65h*        -   multiply the day by the (current month + 1)
          325q    -  ^ == 325
    6         /   - 6 / ^
.dↄґ              -  load "merry christmas"
               Al - ^.capwords()

Or 18 bytes noncompetitive.
.dↄґ6Cs6Y1q/Al

Exactly the same except for this section:
Cs6Y1q
C      -    get_time()
 s6    -   add 1 week
   Y   -  get day of the year
    1q - ^ == 1

Try it here!


Ruby, 96 149 bytes

Regex solution to match all the valid kana. Interestingly, "ecchi" is not valid according to the current rules, but perhaps it's for the best.

->s{s.gsub(/(?![dt]u)(sh|ch|([gbknhmrp])\2?y?|([zdst])\3?)?[auo]|(\g<2>)?\4?[ie]|(\g<3>)\5?e|ww?[ao]|n|tsu|([fv])\6?u|jj?i|j?y?[aou]|yy[aou]/){}==""}

Try it online! feat. Cruel Angel's Thesis


Рапира (Rapira), 172 142 bytes
ВЫВОД: "АаБбВвГгДдЕеЁёЖжЗзИиЙйКкЛлМмНнОоПпСсТтУуФфХхЦцЧчШшЩщЪъЫыЬьЭэЮюЯя"

Try it online!
Just for fun, given the challenge. It may not be golfed; I'm not really familiar with the language.


Python 3.8 (pre-release), 1533 bytes

def w(n,ll,ans):
	global p,q
	from math import sin,cos,pi,atan2
	def y(s,e,f,a,b):
		x,y=f(s),f(e)
		g=lambda a,b,x:0<=(x-a)%2<=b-a
		while e-s>1e-15:
			m=(s+e)/2
			z=f(m)
			if x*z<=0:
				e,y=m,z
			else:
				s,x=m,z
		return (g(a,b,s)or g(a,b,e))and[s]or[]
	from fractions import Fraction as R
	s,v,d=(0,0,R(1,2)),[],1
	while True:
		for l in ll:
			b=s[2]+R(1,2)*d
			c=s+(R(2,n)*l,d,(s[0]-cos(b*pi),s[1]-sin(b*pi)),b,b-R(2,n)*l*d)
			if l:
				v.append(c)
				s=(c[5][0]+cos(c[7]*pi),c[5][1]+sin(c[7]*pi),(c[7]-R(1,2)*d)%R(2))
			d=-d
		if s[2]==R(1,2):
			break
	e,l=enumerate,len(v)
	q=lambda x:all(abs(i)<1e-7 for i in x)
	p=[]
	h=lambda i,p:any(all(q([j-k]) for j,k in zip(i,a))for a in p)
	def z(u):
		global p,q
		for i in u:
			if not h(i,p):
				p.append(i)
	if all(abs(i)<1e-6 for i in s[:2])and l>1:
		[z([c[:2]]) for c in v if c[3]==R(2)]
		x_=[t_ for n,c in e(v) for m,d in e(v) if (n-m)%l not in [0,1,l-1] and len(t_:=[(f,t) for f,g in [(c,d),(d,c)]if not q(x:=[f[5][i]-g[5][i]for i in[0,1]])and (a:=x[0])**2+(b:=x[1])**2<=4+1e-14 and(t:=sum((y((r:=[1,-1][b<0]*2/pi*atan2((1-(u:=a/(a*a+b*b)**.5)*u)**.5,u-1))-i,r+j,lambda t:(a+cos(pi*t))**2+(b+sin(pi*t))**2-1,*sorted(f[6:]))for i,j in[(1,0),(0,1)]),[]))])==2]
		[z([i for i in x[1] if h(i,x[0])])for x in[[[(f[5][0]+cos(i*pi),f[5][1]+sin(i*pi))for i in t]for f,t in t_]for t_ in x_]]
		print(len(p),sep='',end='')
		if len(p)!=ans:
			print(min((abs(i[0]-j[0])+abs(i[1]-j[1]),n,m) for n,i in e(p) for m,j in e(p) if n!=m))
		else:
			print('')
	else:
		print(0)

Try it online!

Python 2 (PyPy), 1580 bytes

n,ll=map(eval,input().split(' '))
from math import sin,cos,pi,atan2
#and let's implement the bisection
def y(s,e,f,a,b):#solve f=0 within (s,e) if x in (a,b)
    x,y=f(s),f(e)
    g=lambda a,b,x:0<=(x-a)%2<=b-a
    while e-s>1e-15:# or g(a,b,s)!=g(a,b,e):
        m=(s+e)/2
        z=f(m)
        if x*z<=0:
            e,y=m,z
        else:
            s,x=m,z
    c,d=g(a,b,s),g(a,b,e)
    #c,d
    #True,True [s]
    #True,False [s]
    #False,True [s]
    #False,False []
    return (c or d)and[s]or[]
from fractions import Fraction as R
#the start point
s=(0,0,R(1,2))
#now let's compute the arcs
#we need to store x0,y0,angle,length,direction,center,start angle,end angle
#arcs array
v=[]
d=1#the direction, 1 for clockwize
while True:
    for l in ll:
        b=s[2]+R(1,2)*d#start angle
        c=s+(R(2,n)*l,d,(s[0]-cos(b*pi),s[1]-sin(b*pi)),b,b-R(2,n)*l*d)#the arc
        if l:
            v.append(c)
            s=(c[5][0]+cos(c[7]*pi),c[5][1]+sin(c[7]*pi),(c[7]-R(1,2)*d)%R(2))
        d=-d
    if s[2]==R(1,2):
        break
e,l=enumerate,len(v)
q=lambda x:abs(x)<1e-7
p=[]#array of intersection points
#like in array
h=lambda i,p:any(all(q(j-k) for j,k in zip(i,a))for a in p)
def z(u):#add points if not in array
    global p,q
    #print(p,u)
    for i in u:
        if not h(i,p):
            p.append(i)
if all(abs(i)<1e-6 for i in s[:2])and l>1:
    #returned to the same point
    for n,c in e(v):
        if c[3]==R(2):z([c[:2]])
        for m,d in e(v):
            if (n-m)%l not in [0,1,l-1]:
                #compute the intersection
                x=[]
                for f,g in [(c,d),(d,c)]:
                    a,b=[f[5][i]-g[5][i]for i in[0,1]]
                    if q(a)and q(b):
                        break
                    if a*a+b*b>4+1e-14:
                        break
                    u=a/(a*a+b*b)**.5
                    #the angle from a to b
                    r=[1,-1][b<0]*2/pi*atan2((1-u*u)**.5,u-1)
                    t=sum(
                    (y(r-i,r+j,lambda t:(a+cos(pi*t))**2+(b+sin(pi*t))**2-1,\
                        *sorted(f[6:]))for i,j in[(1,0),(0,1)]),[])
                    #that's it
                    if not t:
                        break
                    x.append([(f[5][0]+cos(i*pi),f[5][1]+sin(i*pi))for i in t])
                else:
                    #intersection points
                    z([i for i in x[1] if h(i,x[0])])
    print(len(p))
else:
    #infinite, return 0
    print(0)

Try it online!

Runs in all test cases.

Python 3.8 + sympy, ungolfed, #

covering almost all test cases (except 7 and 19 -- sympy can't simplify some expressions)
at least to know what you have to bear.
Major improvement in comparison with previous version is that:
1) It simply holds array of intersection points,
2) Any arc end counts as intersection if arc length \$=2\pi\$ unless arc array length is \$1\$
Still need to be rewritten into precise \$i^{\frac{2\pi}{n}}\$ arithmetic

from sympy import *
R=Rational
angle=R(0)
class Arc:
    def __init__(self,x0,y0,angle,length,direction):
        #','.join('self.%s'%i for i in 'x0,y0,angle,length'.split(','))
        (self.x0,
         self.y0,
         self.angle,
         self.length,
         self.dir)=x0,y0,angle,length,direction
        self.start=(angle+pi/R(2)*direction)#%(R(2)*pi)
        self.end_=self.start-self.length*self.dir
        self.center=(x0-cos(self.start),y0-sin(self.start))
    def i(self,a0):
        #t=symbols('t')
        #param_form=(self.center[0]+cos(self.start+t),
        #            self.center[1]+sin(self.start+t))
        #z=solveset((a.center[0]-param_form[0])**2+
        #           (a.center[1]-param_form[1])**2-1,t)
        #return z
        #to (a + cos(t))^2 + (b + sin(t))^2 = 1
        a,b=[self.center[i]-a0.center[i] for i in [0,1]]
        try:
            d={frozenset([-cos(3*pi/7) - sin(pi/14), -2*sin(3*pi/7)]):False,
               frozenset([cos(3*pi/7) + sin(pi/14), 2*sin(3*pi/7)]):False}
            if (frozenset([a,b]) in d and d[frozenset([a,b])]) or \
               (frozenset([a,b]) not in d and a**R(2)+b**R(2)>R(4)):
                return set()
            if a**R(2)+b**R(2)==R(4):
                #https://www.wolframalpha.com/input/?i=%28a%2Bcos%28t%29%29%5E2%2B%28b%2Bsin%28t%29%29%5E2%3D1+and+a%5E2%2Bb%5E2%3D4
                #s=R(-1,2)*sqrt(R(4)-a**R(2))
                #c=R(-1,2)*a
                if (a==R(2)):
                    return set([pi])
                return set([(R(-1) if b<R(0) else R(1))*R(2)*\
                            atan2(sqrt(R(4)-a**R(2)),a-R(2))])
        except Exception:
            print((a,b))
            raise
        #https://www.wolframalpha.com/input/?i=%28a%2Bcos%28t%29%29%5E2%2B%28b%2Bsin%28t%29%29%5E2%3D1
        if a!=R(0) and a!=R(2) and ((z0:=b**R(2)+a**R(2)-R(2)*a)==0 or\
           abs(float(z0))<1e-6):
            s=R(2)*(R(-1) if b<R(0) else R(1))*atan2(sqrt(-(a-R(2))*a),(a-R(2)))
            return set([s])
        if not ((z0:=b**R(2)+a**R(2)-R(2)*a)==0 or\
           abs(float(z0))<1e-6):
            s=sqrt(-a**R(4)-2*a**R(2)*b**R(2)+4*a**R(2)-b**R(4)+R(4)*b**R(2))
            r=set()
            for sg in [R(-1),R(1)]:
                d=a**R(3)-2*a**R(2)+sg*b*s+a*b**R(2)-R(2)*b**R(2)
                if d!=0 or abs(float(d))>=1e-6:
                    r.add(R(2)*atan2((sg*s-R(2)*b),z0))
            return r
        #thank you so much for such interesting coding challenge
        if a==R(0) and b==R(0):
            return set()
        print((a,b))
        raise Exception('')
    def end(self):
        return (self.center[0]+cos(self.start-self.length*self.dir),
                self.center[1]+sin(self.start-self.length*self.dir),
                (self.end_-pi/R(2)*self.dir)%(R(2)*pi))

from PIL import Image,ImageDraw
d=300
x0,y0=d//2,d//2
r,r0=20,2
n,l=7 , [2,3,1,3,1,1]#5,[3,4]
s=(r'''  3 | [3,0]         | 0
  3 | [3,1]         | 3
  3 | [3,3]         | 1
  3 | [3,2,3,1]     | 2
  6 | [1,1]         | 0
  6 | [5,1]         | 3
  6 | [5,2]         | 1
  6 | [5,3]         | 3
  6 | [5,4]         | 6
  6 | [1,1,1,5]     | 3
  6 | [1,2,3,4]     | 0
  6 | [1,2,3,4,5,6] | 8
  7 | -[2,3,1,3,1,1] | 14
  7 | -[3,1,4,1]     | 56
 19 | -[1,2]         | 0'''
r'''5 | -[0,1,1,3,4,1,2,1,1,4,1,2,1,3] | 2
'''
)
def add_point(point):
    global points,count
    if not any(all(abs(float(j-k))<1e-6 \
                   for j,k in zip(i,point)) for i in points):
        points.append(point)
        count+=1

import re
for n,l,ans in\
re.findall(r'\s*(\d+)\s*\|\s*\[(.*?)\]\s*\|\s*(\d+)',s):
#[(5,'0,1,1,3,4,1,2,1,1,4,1,2,1,3',2)]:
#[('7', '2,3,1,3,1,1', '14')]:
#    [('6', '1, 1', '0')]:
#    [(6,'1,1,1,5',3)]:
    print(n,l,end='')
    n=int(n)
    l=[int(i.strip()) for i in l.split(',')]
    fn='196399/%d_%s.png'%(n,'_'.join(map(str,l)))
    start=(0,0,pi/R(2))
    dir_=1
    a_array=[]
    for count in range(30):
        for l_ in l:
            a=Arc(*start,pi/R(n)*R(2*l_),dir_*2-1)
            a_array.append(a)
            start=[simplify(i) for i in a.end()]
            #print(start,a.center,a.start,a.end_)
            dir_^=1
        if (abs(float(start[0]))<1e-3) and \
           (abs(float(start[1]))<1e-3) and start[2]%(R(2)*pi)==pi/R(2):
            break
##        else:
##            continue
##        break
    print(' ',count,'loops made',end='')
    a_array=[a for a in a_array if a.length!=0]
    print(' ',len(a_array),end='')
    count=0
    points=[]
    if len(a_array)==1:
        print(' ans=%s, count=%d'%(ans,count))
        continue
    for n,a in enumerate(a_array):
        if a.length==R(2)*pi:
            add_point((a.x0,a.y0))
        for m,b in enumerate(a_array):
            if (n-m)%len(a_array) not in [0,1,len(a_array)-1]:
                #print('.',sep='',end='')
                try:
                    i_=[list(a.i(b)),list(b.i(a))]
                    p_=list(list(0<=((-R(d_)*(i-st))%(R(2)*pi))<=l_ for i in s) \
                           for s,l_,st,d_ in \
                           zip(
                               (i_),
                               [a.length,b.length],
                               [a.start,b.start],
                               [a.dir,b.dir]
                               ))
                    if all(any(i) for i in p_):
                        for t,angle in zip(p_[0],i_[0]):
                            if t:break
                        point=tuple(i+f(angle) for i,f in zip(a.center,[cos,sin]))
                        add_point(point)
                        #print('\n',(n,m),sep='')
                except Exception:
                    print(i_,[a.length,b.length],[a.start,b.start])
                    raise
    #assert count//2==int(ans)
    print(' ans=%s, count=%d'%(ans,count))
    #break
    continue
    xy=[sum(map(f,a_array))/len(a_array) for f in \
        [(lambda i:lambda a:a.center[i])(i) for i in [0,1]]]
    image = Image.new('RGB',(d,d),'white')
    draw = ImageDraw.Draw(image)
    point=lambda x,y:draw.ellipse((x0-r0+x,y0-r0-y,x0+r0+x,y0+r0-y),'blue','blue')
    for a in a_array:
        start=[a.x0,a.y0,a.angle]
        dir_=a.dir
        point(*[int((i-xy_)*R(r)) for i,xy_ in zip(start[:2],xy)])
        c=[int((i-xy_)*R(r)) for i,xy_ in zip(a.center,xy)]
        draw.arc((c[0]-r+x0,-c[1]-r+y0,c[0]+r+x0,-c[1]+r+y0),
                 *([int(-a.start*180/pi),int(-a.end_*180/pi)][::dir_]),
                 0x3a2af6)
    #image.save(fn,'PNG')
    #break
#image.show()
a=a_array
f=lambda n,m:(a[n].i(a[m]),a[n].start,a[n].length,a[n].dir)
g=lambda a,b:list(list((0,((-R(d_)*(i-st))%(R(2)*pi)),l_) for i in s) \
                           for s,l_,st,d_ in \
                           zip(
                               (i_),
                               [a.length,b.length],
                               [a.start,b.start],
                               [a.dir,b.dir]
                               ))

Output:

3 3,0  0 loops made  1 ans=0, count=0
3 3,1  2 loops made  6 ans=3, count=3
3 3,3  0 loops made  2 ans=1, count=1
3 3,2,3,1  0 loops made  4 ans=2, count=2
6 1,1  29 loops made  60 ans=0, count=0
6 5,1  2 loops made  6 ans=3, count=3
6 5,2  1 loops made  4 ans=1, count=1
6 5,3  2 loops made  6 ans=3, count=3
6 5,4  5 loops made  12 ans=6, count=6
6 1,1,1,5  2 loops made  12 ans=3, count=3
6 1,2,3,4  2 loops made  12 ans=0, count=0
6 1,2,3,4,5,6  1 loops made  12 ans=8, count=8

But it can generate such things although it was not in the task.


Jelly, 1 byte

ṡ

Jelly has a single byte dyadic atom for this very operation

Try it online! (the footer splits the resulting list with newlines, to avoid a mushed representation being printed.)


JavaScript, 124 119

a=(x,y)=>y?a(x^y,(x&y)<<1):x
s=(x,y)=>a(x,a(1,~y))
m=(x,y)=>x?a(y,m(s(x,1),y)):0
d=(x,y)=>(x=s(x,y))>>31?0:a(1,d(x,y))

Addition and Subtraction work for any signed numbers, multiplication and division only for unsigned (this hasn't been specified).

The input is assumed to be 32 bit.

I've been very strict and not even used comparison operators, except testing for equality with zero. It could probably be written a bit shorter otherwise.


JavaScript (Node.js), 180 bytes

s=>(B=Buffer)(s).map(p=c=>(b='23841410645532207643205431765001333746443'[c*45%91%73%41]*2,t+=1/p?p-b?3/8*(g(b)+g(p)):g(b|c!=s):0,p=b,s=c),t=0,g=x=>10/B('4.2.5-75E6?3>4=4AA')[x])&&t

Try it online!
How?
Storing delays
The helper function \$g\$ takes an integer \$0\le x \le17\$ and returns a delay in seconds.
g = x => 10 / Buffer('4.2.5-75E6?3>4=4AA')[x]

The input \$x\$ is expected to be either:

twice the bin number to get the delay for the same letter
twice the bin number + 1 to get the delay for different letters

What is actually stored in the string '4.2.5-75E6?3>4=4AA' is the number of keystrokes per second multiplied by \$10\$ and converted to ASCII. Conveniently, all resulting characters are printable.
For instance, \$5.2\$ is stored as chr(52) which is '4'.
Converting a character to a key bin
We use the following hash function to convert an ASCII code \$c\$ to an index into a lookup table containing the bin numbers in \$[0..8]\$:
$$i = (((c\times 45) \bmod 91)\bmod 73)\bmod 41$$
Main loop
The total time \$t\$ is updated with:
t +=                        // add to t:
  1 / p ?                   //   if p is numeric:
    p - b ?                 //     if p is not equal to b:
      3 / 8 * (g(b) + g(p)) //       0.75 * (g(b) + g(p)) / 2
    :                       //     else:
      g(b | c != s)         //       g(b) if c == s or g(b + 1) otherwise
  :                         //   else (first iteration):
    0                       //     leave t unchanged

where \$p\$ is the previous bin and \$s\$ is the previous character.


C / C++

  Rule 1: octal constants shall not be used

  Rationale: octal constants can be a cause of confusion. For example, a
  casual glance over the line
  const int coefficients[] = {132, 521, 013, 102};
  might miss the fact, that one of the numbers in the array
  is defined in octal.

If you want to be even more evil, add the following:

  Rule 2: hexadecimal constants shall only be used in the context of bit manipulation.

  Rationale: If a constant represents a numerical value, it's more
  readable if it's in decimal. A hexadecimal constant should indicate
  that it represents a bit mask, not a numerical value.

How it can be abused:

Take the following simple program which will add the first 10 elements of an array. This code would not be standard-conforming.

sum = 0;
for (i = 0; i < 10; i++)
{
    sum += array[i];
}

   Note, that 0 is, per definition, an octal constant. Per rule 1, requiring it to be written as 0x00 all through the code is frustrating. Per rule 2, even more frustrating.


Haskell 300 bytes

This code should have no trailing newline. The function m1 takes the input as a Char and returns the answer as a Char.
f1 (l1 :n1 :p1 :y1 :l2 :n2 :p2 :y2 :r3 )x1 |y1 >p1 =b1 (x1 )y2 (f1 (r3 )x1 )y1 (n1 )n2 |p2 <p1 =b1 (x1 )y1 (n1 )p2 (f1 (p2 :y2 :r3 )x1 )l2 |p2 >p1 =b1 (x1 )p1 (l2 )l1 (n2 )n1
;b1 (x1 )s1 (r1 )b1 (r2 )r3 |x1 <s1 =r1 |x1 >b1 =r2 |s1 <b1 =r3
;m1 =f1 "d0 \t4 \r0 ~d3 {d1 `d3 [d1 @d3 :d2 /d3 !d4 \n0 ?d0 "

I couldn't resist a challenge that someone claimed was impossible for "conventional" languages.
You may dispute whether Haskell counts, but the majority of keywords and identifiers are multiple characters and cannot be used. However, top level function definitions, lists, string literals, strict comparisons, pattern matching and branching with guards work, as long as letters come just before digits, and if symbols also come just before letters we have escape characters like \t and \r. Unfortunately the permutations that work for general programming don't allow numeric literals, so I couldn't get numbers in any useful way.
How it works:

The intervals of character classes are encoded in the string on the last line, with boundary characters at most of the symbol places and the results in most of the digit places, although some at the ends are padding.
The main function is m1.
x1 is the character being analyzed.
The f1 function breaks up the string with list pattern matching, and has three branches: for when the boundaries are symbols larger than space, for when the boundaries are escaped control characters smaller than space, and for handling the final comparison to space itself. The names of the list pieces are mnemonic for the first branch: Letter, Number, sPace, sYmbol, Remainder.
The b1 function handles branching for two boundary characters s1 < b1 at a time.

Try it online


Perl, 119 118 117 bytes

Includes +4 for -0p

Give rotated board padded with spaces on STDIN (gravity pulls stones to the right)

connect4.pl
  OXXX
   XOO
    OX
  OOXX
  XXXO
XXOOXO
OOXXOO
^D

connect4.pl:

#!/usr/bin/perl -p0
y/XO/OX/if$^S|y/X//>y/O//;$_=$$_||=/Z@{[map"|O".".{$_}O"x3,0,5..7]}/sx||s% (?! )%$_="$`X$'";do$0%eg?/1/?3:1+/2/:2

Prints 3 if player to move wins, 1 if player to move loses and 2 for a draw.

On older perls you can use a literal ^S to gain one byte.
If you don't mind extreme inefficiency you can leave out the $$_||= (transposition table) and gain 6 more bytes. If you leave out the $_= it will show you where to play instead of the result (play on 1 and win if there is one, play on 2 and draw if there is one or play on any 3 and lose)

Builds and evaluates a complete minimax tree. You will run out of memory and time unless the board is already reasonably well filled.


Implement Homestuck's Catenative Doomsday Dice Cascader

Python 2, 76 69 bytes

from random import*
R=randint
v=6;exec"p=R(1,v);v*=p;"*R(1,6)
print p

Try it online!


Number of distinct tilings of an n X n square with free n-polyominoes

C, 7 terms

The seventh term is 19846102. (The first six are 1, 1, 2, 22, 515, 56734, as stated in the question).

#include <stdio.h>
#include <string.h>
#include <stdint.h>

#define N 7
#define ctz __builtin_ctzl

typedef uint64_t u64;

static u64 board[N*N] = { 0 };
static u64 adjacency_matrix[N*N] = { 0 };
static u64 count = 0;

static u64 check_symmetry()
{
    static const u64 symmetries[7][3] = {
        { 0,     +N, +1 },
        { N-1,   -1, +N },
        { N-1,   +N, -1 },
        { N*N-1, -1, -N },
        { N*N-1, -N, -1 },
        { N*N-N, +1, -N },
        { N*N-N, -N, +1 },
    };

    int order[N];

    for (u64 i = 0; i < 7; ++i) {
        u64 start = symmetries[i][0];
        u64 dcol = symmetries[i][1];
        u64 drow = symmetries[i][2];
        memset(order, 0xFF, N*sizeof(int));

        for (u64 row = 0, col = 0; col < N || (col = 0, ++row < N); ++col) {
            u64 base = board[col + N*row];
            u64 symmetry = board[start + dcol*col + drow*row];
            u64 lex = 0;

            while (order[lex] != symmetry && order[lex] != -1)
                ++lex;
            order[lex] = symmetry;

            if (lex < base)
                return 0;

            if (base < lex)
                break;
        }
    }

    return 1;
}

static void recurse(u64 mino, u64 cell, u64 occupied, u64 adjacent, u64 forbidden)
{
    if (cell >= N) {
        ++mino;

        if (mino == N) {
            count += check_symmetry();
            return;
        }

        u64 next = ctz(~occupied);
        board[next] = mino;
        recurse(mino, 1, occupied | 1ul << next, adjacency_matrix[next], 0);
        return;
    }

    adjacent &= ~occupied & ~forbidden;
    while (adjacent) {
        u64 next = ctz(adjacent);
        adjacent &= ~(1ul << next);
        forbidden |= 1ul << next;
        board[next] = mino;
        recurse(mino, cell + 1, occupied | 1ul << next, adjacent | adjacency_matrix[next], forbidden);
    }
}

int main(void)
{
    for (u64 i = 0; i < N*N; ++i) {
        if (i % N)
            adjacency_matrix[i] |= 1ul << (i - 1);
        if (i / N)
            adjacency_matrix[i] |= 1ul << (i - N);
        if (i % N != N - 1)
            adjacency_matrix[i] |= 1ul << (i + 1);
        if (i / N != N - 1)
            adjacency_matrix[i] |= 1ul << (i + N);
    }

    recurse(0, 2, 3, 4 | 3 << N, 0);
    printf("%ld\n", count);
}

Try it online! (for N=6, since N=7 would time out.)

On my machine, N=6 took 0.171s, and N=7 took 2m23s. N=8 would take a few weeks.


JavaScript (ES6),  71 65  55 bytes

Output is 0-indexed.

n=>(g=([a,b,...c])=>b?a+b-n&&1+g(c):g([a]+6*++i))(i='')

Try it online!

How?

Using a recursive function, we either 'consume' the first 2 characters of the string of concatenated multiples of \$6\$, or append new characters if we have less than 2 of them.

Example for \$n=3\$:

 string | operation                          | result
--------+------------------------------------+--------
 ''     | not enough characters: append '6'  |   0
 '6'    | not enough characters: append '12' |   0
 '612'  | consume '61', increment the result |   1
 '2'    | not enough characters: append '18' |   1
 '218'  | consume '21', increment the result |   2
 '8'    | not enough characters: append '24' |   2
 '824'  | consume '82', increment the result |   3
 '4'    | not enough characters: append '30' |   3
 '430'  | consume '43', increment the result |   4
 '0'    | not enough characters: append '36' |   4
 '036'  | consume '03': success              |   4

Commented

n => (             // n = input
  g = (            // g is a recursive function taking either a string or an array of
                   // characters split into:
    [a, b,         //   a = 1st character, b = 2nd character,
           ...c]   //   c[] = array of all remaining characters
  ) =>             //
    b ?            // if b is defined:
      a + b - n && //   if n subtracted from the concatenation of a and b is not zero:
        1 + g(c)   //     add 1 to the final result and do a recursive call with c[]
                   //   (otherwise: yield 0 and stop recursion)
    :              // else:
      g(           //   do a recursive call with:
        [a] +      //     the concatenation of a (forced to an empty string if undefined)
        6 * ++i    //     and 6 * i, with i pre-incremented
      )            //   end of recursive call
)(i = '')          // initial call to g with an empty string,
                   // and i set to empty string as well (zero'ish)


CJam, 13 bytes - 10 = 3

l_'x)?{_oNo}h

You'll need to use the Java interpreter for this, because the online interpreter only returns once the program terminates.

You can abort the program with SIGINT (by pressing Ctrl-C). It will read a line from STDIN, and print that line, or y if the input was empty.

Explanation

l             "Read line from STDIN.";
 _            "Duplicate.";
  'x          "Push character x.";
    )         "Increment to get y.";
     ?        "Ternary operator. Replaces line with y if it was empty.";
      {    }h "Repeat while true. Leaves condition on the stack, which is the output string.";
       _o     "Duplicate line and print.";
         No   "Push string with newline and print.";

After clarification of the OP, the following seems more to spec:

l{_o9c)o1}g

I'll wait with updating the submission until the OP replies to my comment, though.


3. ><>, 106 bytes
void main(){import std.stdio;"D".write;}
/*                        ;ooo"><>"
1j U8=XPC#18M<<}9F ,+;q,+;
*/

Try it online!
This program prints D in D, emmoS in Somme, and ><> in ><>.
Next answer cannot exceed 146 bytes (106 + 40).
Explanation
;ooo"><>" prints "><>" in ><> (which is a palindrome), then exits.


Haskell, 146 124 bytes

((""##))
a===bb=bb==a
((aa:bb))##((cc:dd))|aa===cc=bb##dd|1==1=((cc:aa:bb))##dd
a##""=""===a
""##cc=((cc!!00:cc!!00:""))##cc

No comments. Returns either True or False.

Try it online!

Edit: -22 bytes thanks to @Cat Wizard


Perl 6, 198 bytes (264 bytes - 25% bonus)

Managed to actually get this sucker into a Whatever block by inlining the helper functions from the original version.

*.permutations.map({([+] -1,5*@_,|(for (0,0),|@_ Z |@_,(0,0) ->((\i,\j),(\x,\y)){my ($s,\p)=0,i.Rat.nude[1]*j.Rat.nude[1]*abs(i -x).Rat.nude[0];(i+(x -i)*$_/p)%%1&&(j+(y -j)*$_/p)%%1&&$s++ for ^p;sqrt(abs(i -x)²+abs(j -y)²)+(p??$s!!abs(j.Int -y.Int))})),@_}).min

Try it online!

No doubt there are still a few little improvements that can be made.  Trickiest part was figuring out how to calculate the number of lattice points crossed.  The solution I went with uses the denominators of each X coordinate to calculate an iteration interval that is guaranteed to hit each whole number along with X axis, thus allowing a check for landing on a lattice point.  There is a catch, of course, that if there is no movement along X then the lattice points crossed will be the absolute value of the floor value of each Y coordinate.

This will be, nonetheless, very tricky for languages that don't have built in rationals, because of floating point errors (I can already see the .1 + .2 = .3 issue cropping up if any two X or Y coordinates are 10 apart).

Ungolfed version:

*                           #  Whatever block, takes a list of coordinates
.permutations.map({         #  Get all combinations and to each of them ...
 (                          #   Implicitly return a list consisting of
  [+]                       #    The sum of
   -1,                      #     -1 (to discount lattice +1 on return to origin)
   5*@_,                    #     5 * number of coordinates (or stops)
   |(for                    #     each value in the loop across
    (0,0),|@_ Z |@_,(0,0)   #      the coordinates (zipping with the origin
                            #        first/last for the return)
    ->((\i,\j),(\x,\y)) {   #      deconstructing into i,j,x,y
     my ($s,\p)=0,          #      set S (lattice stops) to 0
       i.Rat.nude[1]        #      set P (x check interval) to denominator of i
       *j.Rat.nude[1]       #       times denominator of p (psuedo lcm)
       *abs(i -x).Rat.nude[0]; #    times x-diff numerator (bc Rat simplification)
     (i+(x -i)*$_/p)%%1&&   #      check X is whole, if so,
      (j+(y -j)*$_/p)%%1&&  #       check Y is whole, if so,
      $s++                  #        increment S (trip crossed a lattice point)
     for ^p;                #      do the checks for 0 to P
     sqrt(                  #      implicitly return
      abs(i -x)²+abs(j -y)² #       the distance
     )+(p                   #        plus, if X values were different,
      ??$s                  #         S value, else
      !!abs(j.Int -y.Int)   #         Y difference = vertical lattice crossings
     )
    }
   )                        #
   ,@_)                     #   And the permutation
.min                        #  Find best (smallest) time

I'll probably add a more readable version because this golfing got unreadable fast.


Javascript ES6, 62 Bytes

s=>Math.sign([...s].reduce((p,c,i)=>p+~~c*(i-s.indexOf`^`),0))

-1 if left is heavier
0 if balanced
1 if right is heavier

Ungolfed:

s=>
  Math.sign(                     // output sign of weight of lever
    [...s].reduce((p,c,i)=>      // split and reduce input
      p+~~c*(i-s.indexOf`^`),0)) // add weights of all elements
                                 //   (elements left of pivot are negatively weighted)

Test runs (assigning anonymous function to f):

>> f("11   ^9")
<< 0

>> f("321^  12")
<< -1

>> f("9^         1")
<< 1

-11 bytes: changed output from R B L to -1 0 1
-3 bytes: changed e.split`` to [...e] (thanks @Vɪʜᴀɴ)
-33 bytes: changed algorithm to use negative weights rather than splitting at pivot
-9 bytes: removed pivot check (apparently, ~~'^' evaluates to 0...)
-2 bytes: made function anonymous (thanks @cᴏɴᴏʀ-obʀɪᴇɴ)


Java, 146 131 144 134 131 128

Not a very exciting answer. Returns true for anagrams, false for others. Actually works now. Cheapass abuse of generics in class declaration.

boolean b(T a,T b){return c(a).equals(c(b));}T c(T a){char[]c=a.toLowerCase().toCharArray();sort(c);return(T)valueOf(c).trim();}

Ungolfed:

boolean b(T a,T b) {
    return c(a).equals(c(b));
}

T c(T a) {
    char[] c = a.toLowerCase().toCharArray();
    sort(c);
    return (T) valueOf(c).trim();
}


Python O(mn log mn)

The best pairs can be found computing the distances of all the possible pairs, and iteratively choosing the best pair among those remaining after filtering out the already chosen items.

A simple implementation is shown in the following code:

def find_nearest_pairs_to_100(l, m):
    pair_list = sorted([((i, j), abs(100 - i - j)) for i in l for j in m], key=lambda x: x[1])
    chosen_pairs = []
    while pair_list:
        best_pair = pair_list[0][0]
        chosen_pairs.append(best_pair)
        pair_list = [(p, s) for (p, s) in pair_list if p[0] != best_pair[0] and p[1] != best_pair[1]]
    return chosen_pairs

The find_nearest_pairs_to_100 function takes the two lists in input and returns an ordered list with the chosen pairs.

The sorted function in Python is based on Timsort algorithm, that requires O(n log n) comparisons in the worst case (where n is the length of the list).

In this case the length of the list is the cardinality of the Cartesian product of the two input lists, i.e. mn (with n > m). Therefore, the total cost of this implementation is of O(mn log mn) comparisons, excluding the other comparison operations needed for filtering.

Including comparisons for filtering, at each iteration, in the worst case, all the items of the list are checked against the elements of the chosen pair; the length the pair_list is mn at the first iteration, (n-1)(m-1) at the second, (n-2)(m-2) at the third, and n-m+1 at the last step. So the total number of comparisons for filtering is O(n^3).

If you like golfing, it is a golfed version (163 bytes) of the previous one (a little bit different):

f=lambda l,m:l and m and[[k]+f(l.remove(k[0])or l,m.remove(k[1])or m)for k in sorted([[[[i,j]],abs(100-i-j)]for i in l for j in m],key=lambda x:x[1])[0][0]][0]or[]


Jelly, 2 bytes

sṚ

A full program that prints the result.

Try it online!

How?

sṚ - Main link: string, number                                   e.g. 'abcdefg', 3
s  - split string into chunks of length number (keeping any overflow) ["abc","def","g"]
 Ṛ - reverse the resulting list                                       ["g","def","abc"]
   - implicit print                                                   gdefabc


CJam, score → 0

{)1e9%"X$~"}0X$~

Try it online in the CJam interpreter.

The actual score of this program is obviously positive, but 1e9 can be replaced with 1e99, 1e999, 1e9999, 1e99999, etc.

The numerator of the score grows much slower than the denominator.

How it works

{          }     e# Define a block:
 )               e#   Increment the integer on the stack.
  1e9%           e#   Take the incremented integer modulo 1,000,000,000.
      "X$~"      e#   Push that string.
            0    e# Push 0.
             X$~ e# Copy the block and execute the copy.

                 e# The stack now holds the block, the modified integer and
                 e# the string "X$~", all of which CJam prints before exiting.

Executing the code prints {)1e9%"X$~"}1X$~ which, when executed, prints {)1e9%"X$~"}2X$~, etc.

After reaching {)1e9%"X$~"}999999999X$~, one more execution yields the original code.


JavaScript (ES8), 281 bytes

Takes input as (letter)(N). Returns a string.

c=>n=>(g=y=>y--?''.padEnd(w).replace(/./g,(_,x)=>(h=d=>~~(d/=5)?(P=parseInt)('hhvhefhfhfu111ufhhhfv1f1v11f1vehp1ehhvhhv444vehgggh979hv1111hhlrhhpljhehhhe11fhfuphheh9fhffge1u4444vehhhh4ahhhalhhhha4ah444ahv248v'[y/d%5+5*P(c,36)-50|0],36)>>x/d%5&1?h(d):' ':c)(w))+`
`+g(y):'')(w=5**n)

Try it online!

How?

Font encoding

The letters are \$5\times5\$, which means that each row can be encoded as a 5-digit binary value, i.e. \$0\$ to \$31\$ in decimal. These values can conveniently be stored as a single digit in Base36.

The pattern that is stored is mirrored both horizontally and vertically.

Example for 'F':

#####     ....#     00001      1     '1'
#....     ....#     00001      1     '1'
####. --> .#### --> 01111 --> 15 --> 'f' --> '11f1v'
#....     ....#     00001      1     '1'
#....     #####     11111     31     'v'

The whole font is stored as a single string of \$26\times5 = 130\$ characters.

To test the 'pixel' at \$(x,y)\$ for the \$n^{\text{th}}\$ letter, we do:

parseInt('hhvhefhfh...'[y + 5 * n], 36) >> x & 1

Main algorithm

Given \$n\$, we define \$w=5^n\$, which is the width of the final output.

For \$0\le x<w\$ and \$0\le y<w\$, we want to know if the output pixel at \$(x,y)\$ is set or not. We use the recursive function \$h\$, which tests the letter pixel located at:

$$\left(\left\lfloor\frac{x}{5^k}\right\rfloor\bmod 5,\left\lfloor\frac{y}{5^k}\right\rfloor\bmod 5\right)$$

for all \$k\$ in \$[0 \dots n-1]\$.

The function returns a space as soon as a blank pixel is detected at some depth, or the character corresponding to the input letter if all iterations are successful.


Jelly, 6 bytes

-*æ.¹A

Try it online!

How it works

-*æ.¹A  Main link. Argument: A (digit array)

-*      Raise -1 to A's digits, yielding 1 for even digits and -1 for odd ones.
    ¹   Identity; yield A.
  æ.    Take the dot product of the units and the digits.
     A  Apply absolute value.


An unintentional-looking but crash-causing bug

C, linux. Crashes system if run as root

/* Fork child process, wait 5 seconds and kill it */
pid_t pid = fork();
if(pid =! 0) {
    /* Parent */
    sleep(5);
    kill(pid, 11);
}
else {
    /* Child process. Would contain some code */
}

By changing != to =!, an innocent comparison is turned into an assignment. And given that pid 1 is init, and killing init causes a kernel panic, this is not code you would want to run as root :)


JavaScript, 38 characters

window.open("http://tinyurl.com/erjk34");

Here is the tweet, in all its glory: https://twitter.com/kevinaworkman/status/575425948562014209

And here is my previous entry at 95 characters:

function q() {
window.open("https://twitter.com/intent/tweet?text="+encodeURIComponent(q+";{q();}"));
};{q();}

And if that's not cheating...

HTML, 22 characters

http://tinyurl.com/erjk35