Interleave numbers from 1 to n, with the same numbers reversed

JavaScript (ES6), 30 bytes

f=(n,k=1)=>n?f(n-1,k+1)+n+k:''

How?

This is pretty straightforward but it's worth noting that the string is built from tail to head. An empty string at the beginning is appended last and allows the coercion of the final result to a string to happen.

Below is the detail of the recursion for f(4):

f(4) =                                            // initial call
f(4, 1) =                                         // applying the default value to k
f(3, 2) + 4 + 1 =                                 // recursive call #1
(f(2, 3) + 3 + 2) + 4 + 1 =                       // recursive call #2
((f(1, 4) + 2 + 3) + 3 + 2) + 4 + 1 =             // recursive call #3
(((f(0, 5) + 1 + 4) + 2 + 3) + 3 + 2) + 4 + 1 =   // recursive call #4
((('' + 1 + 4) + 2 + 3) + 3 + 2) + 4 + 1 =        // n = 0 --> end of recursion
'' + 1 + 4 + 2 + 3 + 3 + 2 + 4 + 1 =              // final sum
'14233241'                                        // final result

Test cases

f=(n,k=1)=>n?f(n-1,k+1)+n+k:''

console.log(f(1))
console.log(f(4))
console.log(f(26))
console.log(f(100))


Prime containment numbers (golf edition)

05AB1E, 8 bytes

∞.ΔIÅpåP

Try it online!

Explanation

           # from
∞          # a list of infinite positive integers
 .Δ        # find the first which satisfies the condition:
       P   # all
   IÅp     # of the first <input> prime numbers
      å    # are contained in the number


Constructing an Orthogonal-Diagonal Greco-Latin Square

Python 3

letters = []
numbers = []
for n in range(1,27):
    if n%2==0 or n%3==0:
        offsets=False
    else:
        offsets = [x for x in range(0,n,2)]
        offsets.extend([x for x in range(1,n,2)])
    letters.append(chr(96+n))
    numbers.append(n)
    if offsets :
        for y in range(n):
            for x in range(n):
                let=letters[(x+offsets[y])%n]
                num=numbers[(offsets[y]-x)%n]
                print (let+str(num), end= "  " if num<10 else " ")
            print("\n")
    else:
        print("Impossible\n")

How it works?

The naive implementation would be to look through all the possible arrangements of letter and numbers
in an NxN grid and look for one that is also a Orthogonal-Diagonal Latin Square (ODLS)
(and thus, for some it would just have to go through all configurations and return impossible). Such
an  algorithm wouldnt suit this challenge due to absurd time complexity.
So there are three major simplifications and justifications (partial proofs and insights to why it works) to ODLS constructions used in my implementation:

The first is the notion that we only need to generate a valid Diagonal Latin Square (A NxN grid such that each row, column, wrapped-diagonal
contains each element of a set of N distinct elements exactly once) of the first N letters of the alphabet.
If we can construct such a Diagonal Latin Square (DLS) then an ODLS can be constructed
using the DLS with appropriate exchange of elements and flipping. Justification:

Let us first look at an example using the example grid
a1 b2 c3 d4 e5
c4 d5 e1 a2 b3
e2 a3 b4 c5 d1
b5 c1 d2 e3 a4
d3 e4 a5 b1 c2
Every ODLS can be separated into two DLS (by definition), so
we can separate the grid above into two DLS, one containing letters, the other - numbers
a b c d e
c d e a b
e a b c d
b c d e a
d e a b c
and
1 2 3 4 5
4 5 1 2 3
2 3 4 5 1
5 1 2 3 4
3 4 5 1 2
If we transform the number DLS by the mapping 1-->e, 2-->d, 3-->c, 4-->b, 5-->a,
1 2 3 4 5 --> e d c b a
4 5 1 2 3 --> b a e d c
2 3 4 5 1 --> d c b a e
5 1 2 3 4 --> a e d c b
3 4 5 1 2 --> c b a e d
Now if we put the transformed number grid next to the original letter grid,
Original  | Transformed
a b c d e | e d c b a
c d e a b | b a e d c
e a b c d | d c b a e
b c d e a | a e d c b
d e a b c | c b a e d
It can be clearly seen that the number grid is a horizontal flip of
the letter grid withminor letter to number substitutions.
Now this works because flipping guarantees that no two pairs occur more than once,
and each DLS  satisfies the requirements of the ODLS.

The second simplification is the notion that if we found a suitable configuration (SC) of one element (A NxN grid such that each row, column, wrapped-diagonal
contains that element exactly once), then a DLS could be constructed by replacing the element and shifting the SC. Justification:

If "_" is an empty space and "a" the element then a valid SC of a 7x7 grid is
a _ _ _ _ _ _
_ _ a _ _ _ _
_ _ _ _ a _ _
_ _ _ _ _ _ a
_ a _ _ _ _ _
_ _ _ a _ _ _
_ _ _ _ _ a _
or
a _ _ _ _ _ _
_ _ _ a _ _ _
_ _ _ _ _ _ a
_ _ a _ _ _ _
_ _ _ _ _ a _
_ a _ _ _ _ _
_ _ _ _ a _ _
(the second one can actually be obtained from the first one via rotation)
now say we took the second SC, shifted it one unit to the right and
replaced all "a" with "b"
a _ _ _ _ _ _       _ a _ _ _ _ _       _ b _ _ _ _ _
_ _ _ a _ _ _       _ _ _ _ a _ _       _ _ _ _ b _ _
_ _ _ _ _ _ a       a _ _ _ _ _ _       b _ _ _ _ _ _
_ _ a _ _ _ _  -->  _ _ _ a _ _ _  -->  _ _ _ b _ _ _
_ _ _ _ _ a _       _ _ _ _ _ _ a       _ _ _ _ _ _ b
_ a _ _ _ _ _       _ _ a _ _ _ _       _ _ b _ _ _ _
_ _ _ _ a _ _       _ _ _ _ _ a _       _ _ _ _ _ b _
Now if we overlaid the SC of "a" with the SC of "b" we get
a b _ _ _ _ _
_ _ _ a b _ _
b _ _ _ _ _ a
_ _ a b _ _ _
_ _ _ _ _ a b
_ a b _ _ _ _
_ _ _ _ a b _
If we repeated these steps for the other five letters, we would arrive at a DLS
a b c d e f g
e f g a b c d
b c d e f g a
f g a b c d e
c d e f g a b
g a b c d e f
d e f g a b c
This is a DLS, since each SC follows the general requirements of a DLS
and shifting ensured that each element has its own cell.
Another thing to note is that each row contains the string "abcdefg" that is offset
by some cells. This leads to another simplification: we only need to find the
offsets of the string in every row and we are finished.

The last simplification is as follows - all DLS of prime N, except for N=2 or N=3,
can be constructed, and if N can be factored into two numbers whose appropriate
DLS can be constructed, then a DLS of that N can be constructed.
I conjecture that the converse also holds.
(In other words we can only construct an DLS for N that is not divisible by 2 or 3)

Pretty obvious why 2x2 or 3x3 cant be made. For any other prime this can be done
by assigning a each consecutive row a shift that is by two bigger than the previous,
for N=5 and N=7 this looks like (with elements other than "a" ommited)
N=5
a _ _ _ _ offset = 0
_ _ a _ _ offset = 2
_ _ _ _ a offset = 4
_ a _ _ _ offset = 6 = 1 (mod 5)
_ _ _ a _ offset = 8 = 3 (mod 5)
N=7
a _ _ _ _ _ _ offset = 0
_ _ a _ _ _ _ offset = 2
_ _ _ _ a _ _ offset = 4
_ _ _ _ _ _ a offset = 6
_ a _ _ _ _ _ offset = 8 = 1 (mod 7)
_ _ _ a _ _ _ offset = 10 = 3 (mod 7)
_ _ _ _ _ a _ offset = 12 = 5 (mod 7
(Why this works on all prime N (actually all N that are not divisible
by 3 or 2) can probably be proven via some kind of induction but i will
omit that, this is just what my code uses and it works)
Now, the first composite number that is not
divisible by 2 or 3 is 25 (it also occurs in the range our program must test)
Let A denote the DLS of N = 5
a b c d e
d e a b c
b c d e a
e a b c d
c d e a b
Let F be the DLS A where each letter is substituted by the letter five postions after it
a-->f, b-->g etc. So F is
f g h i j
j e f g h
g h i j f
j f g h i
h i j f g
Let K be the DLS a where each letter is substituted by the letter ten postions after it
a-->k, b--> l etc.
Let P be defined likewise (so a-->p, b-->q etc)
Let U be defined likewise (so a-->u, b-->v etc)
Now, since the DLS A could be constructed, then by substituting a --> A, b--> F etc.
we get a DLS of N=5*5 (A has five rows and five columns and each is filled with a
grid of five rows and five columns)
A F K P U
P U A F K
F K P U A
U A F K P
K P U A F
Now since smaller DLS in the big DLS satisfies the
conditions of a DLS and the big one also satisfies the DLS conditions,
then the resulting grid is also a DLS

A picture of what i meant with the smaller - bigger DLS

Now this kind of thing works for all constructible N and can be proven similiarly.

I have a strong sense that the converse (if some N isnt constructible
(2 and 3) then no multiple of that N is constructible) is also true but have a hard time
proving it (test data up to N=30 (took a veeery long time to calculate) confirm it though)


CJam, 123 114 112 110 bytes

Qq_eu";=KMVWX":T&"@"@?" -chiou"Tereu{i"^A^W^G;^Þ¯     ^Þ^Û9³·^É¿»
^@
^P
^Ü^Ò½7¦^_¶´§=   ^O^V&5^U¯¼¹^T³6/"=i2b9Ue[3/"!_!"f.{S?}.+}/N*

The above uses caret notation, since the code contains unprintable characters. One of them is a null byte (^@), which means that this code can only be executed from the command line.

At the cost of only two more bytes (for a total of 112), we can fix this.

Qq_eu";=KMVWX":T&"@"@?" -chiou"Tereu{i"AWG{ÞïIÞÛyó÷Éÿû
@
P
ÜÒýwæ_öôç}IOVfuUïüùTóvo"=i448+2b1>3/"!_!"f.{S?}.+}/N*

This time, all characters are printable. Try it online in the CJam interpreter.

Example run

$ LANG=en_US
$ xxd -ps -r > 7seg.cjam <<< 51715f6575223b3d4b4d565758223a5426224022403f22202d6368696f752254657265757b69220117073b9eaf099e9b39b3b789bfbb0a000a100a9c92bd37a61fb6b4a73d090f16263515afbcb914b3362f223d6932623955655b332f22215f2122662e7b533f7d2e2b7d2f4e2a
$ wc -c 7seg.cjam
110 7seg.cjam
$ echo -n '0123456789 chiou-?' | cjam 7seg.cjam; echo
 _     _  _     _  _  _  _  _                       _
! !  ! _! _!!_!!_ !_   !!_!!_!    _ !_     _     _  _!
!_!  !!_  _!  ! _!!_!  !!_! _!   !_ ! !  !!_!!_!   !
$ echo -n 'ABCDEFGHIJLNOPQRSTUYZ' | cjam 7seg.cjam; echo
 _     _     _  _  _                 _  _  _     _           _
!_!!_ !   _!!_ !_ !  !_!  !  !!   _ ! !!_!!_! _ !_ !_ ! !!_! _!
! !!_!!_ !_!!_ !  !_!! !  !!_!!_ ! !!_!!    !!   _!!_ !_! _!!_
$ echo -n 'World' | cjam 7seg.cjam; echo
 _
 _
 _

Idea (printable version)

Each character can be shown on the 9-segment display

!_!
!_!
!_!

by replacing some of its characters characters with spaces.

We can turn a specific character into an integer by replacing each shown segment, in natural reading order, with a 1, each not shown segment with a 0 and considering the result binary digits.

The first and third segment are never shown, so this will produce integers in the ranges [0,64) and [128,192).

We can encode each of these integers as a single byte, but half of them will result in unprintable characters. Thus, we add 64 to each integer before casting to character, which makes sure the code points are in the ranges [64,128) and [192,256).

The only unprintable character in these two ranges is DEL (code point 127), which corresponds to the following, unsued display configuration:

!_!
!_!

We can reverse the above encoding by adding 448 == 512 - 64 to each code point, converting to base 2 and removing the first binary digit.

All that's left to to find an efficient way of associating these encoded segmenets with their corresponding ASCII characters.

If we map the characters of " -chiou" to the characters of ";=KMVWX" and convert the entire input to uppercase, we can simply store encoding for all characters between 0 (code point 48) and Z (code point 90), giving a range of 43.

Array indexing is modular in CJam, so if A is a string of length 43, A86=, A43= and A0= all yield the same results. The character with code point 86 is V, so we simply store the encoded segments of V - Z and 0 - U, in order.

In the actual code, we select the at sign as "bad form" character, replace the entire input with the string "@" if it contains a forbidden letter and reverse the steps from above.

Code (printable version)

Q            e# Push an empty array for posterior concatenation.
q            e# Read from STDIN.
_eu          e# Copy the input and convert is to uppercase.
";=KMVWX":T& e# Intersect the result with with T := ";=KMVWX".
"@"@?        e# Select "@" if truthy and the input if falsy.
" -chiou"Ter e# Perform transliteration.
eu           e# Convert everything to uppercase.
{            e# For each character in the modified input:
  i          e#   Push its code point.
  "…"=       e#   Select the corresponding character from the string.
  i448+      e#   Push that character's code point and add 448.
  2b1>       e#   Convert to base 2 and discard the first digit.
  3/         e#   Group into triplets of digits (rows).
  "!_!"      e#   Push that string.
  f.{        e#   For each group of digits:
    S?       e#     Select the corresponding char of "!_!" for 1 and " " for 0.
  }          e#
  .+         e#   Concatenate along the rows with the previous results.
}/           e#
N*           e# Join, separating by linefeeds.


Mathematica

namedColors = {Red, Green, Blue, Black, White, Gray, Cyan, Magenta, Yellow, Brown, Orange, Pink, Purple};
    myRules =
      Table[Rule[namedColors[[i]], RandomChoice[namedColors]], {j, 4}, {i,
         Length[namedColors]}];

myImages = {--images here--};

Grid@Table[ColorQuantize[ColorReplace[myImages[[i]], myRules[[j]]],5],
{i, Length[myImages]}, {j, 4}]


Solve the Global Debt, the Code Golf way


previous solutions (part of them) can be found in the footer container in the tio link (those are probably more readable)

JavaScript (Node.js),883 436 411 360,345 311 bytes

g=>g.map((r,y)=>[...r].map((c,x)=>A+=c=="$"&&P(g,x,y)),A=0)|A
P=(g,x,y,m={},p={},I=i=9,M={})=>{if(/[.$]/.test(c=(g[y]||0)[x])){for(;i--;)if(/^[^.@$#]$/.test(C=(g[y+~-(i/3)]||0)[x+i%3-1])){if(m[C])return
M[C]=1}for(;I--;)if(!p[(X=x+~-(I/3))+","+(Y=y+I%3-1)]&&P(g,X,Y,M,{...p,[x+","+y]:1}))return 1}return c=="@"}

Try it online!

Explantion -

instead of going from the player to the cash i went from the case to the @. i think i should be faster because i know when to stop looking (reach the @) , and when you look for cash you need to always keep moving until you covered all of the spots (and the ways to get to them). so the algo is pretty simple that way - the main function
g.map((r,y)=>[...r].map((c,x)=>A+=c=="$"&&P(g,x,y)),A=0)|A:
find cash -> if you found it -> start looking for the player -> if you found him -> increment A
now lets got to the path finder aka P
if(/[.$]/.test(c=(g[y]||[])[x])) just check if the current cell is "special" -> if so we want to return if its a player. special cases : @#(monster)

for(;i--;)
if(/^[a-zA-Z*&]$/.test(C=(g[y+~-(i/3)]||0)[x+i%3-1])) -> if my neighbor is a monster
{if(m[C])return false -> and it already was in the previous turn - this path is not value
M[C]=1} -> if not just add it to the neighbors monsters
for(;I--;)
if(!p[(X=x+~-(I / 3))+","+(Y=y+I%3-1)]&&P(g,X,Y,M,{...p,[x+","+y]:1}))return true iterate neighbors again - if i wasn't already there (p is the path taken)
continue path (call P)


JavaScript (ES10), 99 bytes

s=>new Set([...s].map((q,i,a,j=i)=>a.map(_=>s.lastIndexOf(q+=s[++i])>j&!/ /.test(q)?q:[])).flat(2))

Try it online!


Mathematica, 273 268 264 242 bytes

c=CirclePoints;b@_=k=1>0;Graphics[Line/@Cases[Append[Join@@({c@6,{3^.5/2,-Pi/6}~c~6}),{0,0}][[b@#=!k;#]]&/@TakeWhile[#,t=k;(r=t;t=b@#;r)&]&/@Join@@RandomSample[{#,Reverse@#}&/@Partition[Range@12,3,2,1]~Join~Array[{2#,13,2#+6}&,3]],{_,__}]]

The  renders as a superscript T in Mathematica and is a postfix transpose operator.

Sorting out the bugs in this took forever... towards the end I hacked a few things together to make it work, so this is definitely suboptimal. I also wonder whether it might be better overall to implement the spec more literally via the lines across the outer hexagon and let Mathematica's geometry functions handle the intersections.

Note that this is a full program and if you want to run the code multiple times within a single REPL session you'll have to prefix it with Clear[b].

Here are the results of 20 runs:

Explanation

This solution doesn't make use of the outer star points at all. Instead it works directly with the points that are part of the hexaglyph and lines that cover three of them at a time.

Let's label the points:

1 starts on a slightly weird corner but this is due to the (also somewhat weird) default behaviour of CirclePoints. Starting the hexagon from there turned out cheapest.

Now we want to find the relevant lines through three of those points which correspond to connected points of the outer star. The ones around the hexagon are of course just 3 adjacent points (modulo 12), starting from an odd number. The ones across the centre consist of an even number n, 13 and n+6.

Representations of these lines (in the form of lists of three points are generated by the following code):

Partition[Range@12,3,2,1]~Join~Array[{2#,13,2#+6}&,3]

The Partition generates the lines around the hexagon and the Array the lines through the centre. To process both beams, we map this function over the list of lines:

{#,Reverse@#}&

Now we shuffle these with RandomSample to process them in a random order. Join @@ flattens the list of pairs so that we have a list of beams.

Short intermission: to keep track of which points are already blocked we use a lookup function b, which is initialised to True for all values by b@_=k=1>0;. When processing a beam we keep all points until the first point that has b[n] == False (including that one):

TakeWhile[#,t=k;(r=t;t=b@#;r)&]&

I feel like this is the most golfable part right now... the use of two temporary variables to play Mastermind seems really expensive. Anyway, the result of this gives us the points in a line we're allowed to draw. Now this function is mapped over each of those points:

Append[Join@@({c@6,{3^.5/2,-Pi/6}~c~6}),{0,0}][[b@#=!k;#]]&

The first part generates the list of all 13 points using the interleaved results of two calls to CirclePoints (with different radii for the edge centres and the corners of the hexagon). Note the b@#=!k which now sets the lookup table's value for the current point to False so that no further beam can pass through it. Finally, the value is used as an index into the list of coordinates to get the correct 2D point.

Cases[...,{_,__}]

This discards all single-element lists, because they would render as individual (and visible) points. Finally we render the result:

Graphics[Line/@...]


Ruby 2.0, 65 76 164 characters

eval r="gets p;$<.pos=0;`ruby -c 2>&0`;p$?==0&&$_!='eval r=%p'%r"

This uses Ruby's built-in syntax checker (ruby -c) to check the input's syntax, which means the code won't be evaluated.

Basic usage example:

ruby syntax.rb <<< foo
true
ruby syntax.rb <<< "'"
false
ruby syntax.rb < synxtax.rb # assumes the file was saved without trailing newline
false

Explanation

This solution is (was) based on the standard Ruby quine:

q="q=%p;puts q%%q";puts q%q

%p is the format specifier for arg.inspect, which can be compared to uneval: when evaling the string returned by arg.inspect, you (usually) get the original value again. Thus, when formatting the q string with itself as argument, the %p inside the string will be replaced with the quoted string itself (i.e. we get something like "q=\"q=%p;puts q%%q\";puts q%q").

Generalizing this type of quine leads to something like the following:

prelude;q="prelude;q=%p;postlude";postlude

This approach has one huge drawback though (at least in code-golf): All code needs to be duplicated. Luckily, eval can be used to get around this:

eval r="some code;'eval r=%p'%r"

What happens here is that the code passed to eval is stored inside r before eval is called. As a result, the full source code of the eval statement can be obtained with 'eval r=%p'%r. If we do this inside the evald code and ensure that the top level of our consists only of the one eval statement, that expression actually gives us the full source code of our program, since any additional code passed to eval is already stored inside r.

Side note: This approach actually allows us to write a Ruby quine in 26 characters: eval r="puts'eval r=%p'%r"

Now, in this solution the additional code executed inside eval consists of four statements:

gets p

First, we read all input from STDIN and implicitly save it into $_.

$<.pos=0

Then, we rewind STDIN so the input is available again for the subprocess we start in the next step.

`ruby -c 2>&0`

This starts Ruby in its built-in syntax checking mode, reading the source code from stdin. If the syntax of the supplied script (filename or stdin) is ok, it prints Syntax OK to its stdout (which is captured by the parent process), but in case of a syntax error, a description of the error is printed to stderr - which would be visible, so we redirect that into nirvana (2>&0) instead.

p$?==0&&$_!='eval r=%p'%r

Afterwards, we check the subprocess's exit code $?, which is 0 if the syntax was ok. Lastly, the input we read earlier ($_) is compared against our own source code (which, as I described earlier, can be obtained with 'eval r=%p'%r).

Edit: Saved 14 characters thanks to @histocrat!


Remove all occurrences of the first letter of a string from the entire string

brainfuck, 219 bytes

+[+[>+<+<]>],[<+<+>>-]>[<<[->]>[<]>-]++++[<++++++++>-]<<[[-]----[>-<----]>-<<[>+>+<<-]<,[[>+>>>+>>+>+<<<<<<<-]>>[<<+>>-]<<[>->+<<-]>[[-]+<]>[>]<<[>>+<<-]>>[<-<+>>-]<[[-]+>]>>[<]<<<<[>>>+<<<-]>>>-[>>.<<-]>>>[[-]<]<<<<<,]

(Requires tape that either allows the pointer to go to the negatives or loops to the end if it tries. Also requires , to return 0 at EOF. In my experience, most interpreters meet these requirements by default.)

This actually turned out to be pretty easy! I wouldn't be surprised if it's golfable (I have some idea of where there might be wasted bytes but I'm not super sure if it'll pan out). Still, getting it work wasn't really a challenge at all.

This code treats everything with an ASCII value below 97 as an uppercase character. If the first character is space, it'll try to remove any occurrences of a "lowercase space" (i.e. chr(32+32), i.e. @) from the string. This is okay, because only letters and spaces will ever be present.

With comments:

to make comments shorter: everywhere it says "fc" means "first character"

#################################### GET FC ####################################

+[+[>+<+<]>]        shortest way to get 96
                    any number above 89 and less than 97 would work because this
                    is only for figuring out if the first character is capital

,[<+<+>>-]          create two copies of the first character

### current tape: | fc | fc | 000 | 096 | ###
###      pointer:              ^          ###

########################### FIND MAX(FC MINUS 96; 0) ###########################

>[                  96 times:

  <<                  go to the cell with the first char

  [->]                if not 0: sub one and move right

  ### current tape: | fc | char being worked on | 000 | 096 | ###
  ###      pointer:                           ^ OR ^          ###

  >[<]>               collapse the wavefunction; sync the branches

-]

### current tape: | fc | fc is lowercase ? nonzero : zero | 000 | 000 | ###
###      pointer:                                                  ^    ###

############################# GET BOTH CASES OF FC #############################

++++[<++++++++>-]   get 32 (add to uppercase character to get lowercase)

<<[                 if the character is already lowercase:

  [-]                 clear the lowercase flag

  ----[>-<----]>-     sub 64 from the cell with 32

<]

<[>+>+<<-]          add fc to the 32 or minus 32 to get both cases

### current tape: | 000 | fc | other case of fc | ###
###      pointer:    ^                            ###

###################### LOOP THROUGH REMAINING CHARACTERS #######################

<,[                 for each character:

  [>+>>>+>>+>+<<<<<<<-]
                      make four copies
                      (only 3 are strictly needed; 4th will resync a branch)

  >>                  go to the first case of fc

  [<<+>>-]<<[>->+<<-] subtract one case of fc from one copy

  >[[-]+<]            if the result is nonzero set it to 1

  >[>]<<              go to the other case of fc (and resync branches)

  [>>+<<-]>>[<-<+>>-] subtract other case of fc from other copy

  <[[-]+>]            if the result is nonzero set it to 1

  >>[<]               resync branches using extra copy

  <<<<[>>>+<<<-]>>>   add results together

  -                   subtract 1

   if the character exactly matched either case: 1 plus 0 minus 1 = 0
  if the character exactly matched neither case: 1 plus 1 minus 1 = 1
    if the character exactly matched both cases: impossible

  [                   if the result is 1:

    >>.<<               output character

    -                   set cell to 0 to kill loop

  ]

  >>>[[-]<]           clean up remaining copies

  <<<<<,              get next character; or end loop if done

]


Haskell, 64 53 48 42 bytes

(0!)
k!(x:y)|x:y>y=1:2!y|2>1=k:0!y
_![]=[]

Try it online!

Ungolfed, with Char instead of Int:

suffixes :: String -> String
suffixes = go 'S'
 where
   go :: Char -> String -> String
   go _ "" = ""
   go lorstar s | s > tail s = 'L' : go '*' (tail s)
                | otherwise  = lorstar : go 'S' (tail s)


Shorter way to assign a default value to the standard output stream

37 33 32 bytes

tr \  \\n|sort -n|sed s/^$/0/\;q

Edit: Saved 4 bytes thanks to @DigitalTrauma.


Python 2 using pypy and pp: n = 15 in 3 minutes

Also just a simple brute force. Interesting to see, that I nearly get the same same speed as kuroi neko with C++. My code can reach n = 12 in about 5 minutes. And I only run it on one virtual core.

edit: Reduce search space by a factor of n

I noticed, that a cycled vector A* of A produces the same numbers as probabilities (same numbers) as the original vector A when I iterate over B.
E.g. The vector (1, 1, 0, 1, 0, 0) has the same probabilities as each of the vectors (1, 0, 1, 0, 0, 1), (0, 1, 0, 0, 1, 1), (1, 0, 0, 1, 1, 0), (0, 0, 1, 1, 0, 1) and (0, 1, 1, 0, 1, 0) when choosing a random B. Therefore I don't have to iterate over each of these 6 vectors, but only about 1 and replace count[i] += 1 with count[i] += cycle_number.

This reduces the complexity from Theta(n) = 6^n to Theta(n) = 6^n / n. Therefore for n = 13 it's about 13 times as fast as my previous version. It calculates n = 13 in about 2 minutes 20 seconds. For n = 14 it is still a little bit too slow. It takes about 13 minutes.

edit 2: Multi-core-programming

Not really happy with the next improvement. I decided to also try to execute my program on multiple cores. On my 2 + 2 cores I now can calculate n = 14 in about 7 minutes. Only a factor of 2 improvement.

The code is available in this github repo: Link. The multi-core programming makes is a little bit ugly.

edit 3: Reducing search space for A vectors and B vectors

I noticed the same mirror-symmetry for the vectors A as kuroi neko did. Still not sure, why this works (and if it works for each n).

The reducing of the search space for B vectors is a bit cleverer. I replaced the generation of the vectors (itertools.product), with an own function. Basically, I start with an empty list and put it on a stack. Until the stack is empty, I remove a list, if it has not the same lenght as n, I generate 3 other lists (by appending -1, 0, 1) and pushing them onto the stack. I a list has the same length as n, I can evaluate the sums.

Now that I generate the vectors myself, I can filter them depending on if I can reach the sum = 0 or not. E.g. if my vector A is (1, 1, 1, 0, 0), and my vector B looks (1, 1, ?, ?, ?), I know, that I cannot fill the ? with values, so that A*B = 0. So I don't have to iterate over all those 6 vectors B of the form (1, 1, ?, ?, ?).

We can improve on this, if we ignore the values for 1. As noted in the question, for the values for i = 1 are the sequence A081671. There are many ways to calculate those. I choose the simple recurrence: a(n) = (4*(2*n-1)*a(n-1) - 12*(n-1)*a(n-2)) / n. Since we can calculate i = 1 in basically no time, we can filter more vectors for B. E.g. A = (0, 1, 0, 1, 1) and B = (1, -1, ?, ?, ?). We can ignore vectors, where the first ? = 1, because the A * cycled(B) > 0, for all these vectors. I hope you can follow. It's probably not the best example.

With this I can calculate n = 15 in 6 minutes.

edit 4:

Quickly implemented kuroi neko's great idea, which says, that B and -B produces the same results. Speedup x2. Implementation is only a quick hack, though. n = 15 in 3 minutes.

Code:

For the complete code visit Github. The following code is only a representation of the main features. I left out imports, multicore programming, printing the results, ...

count = [0] * n
count[0] = oeis_A081671(n)

#generating all important vector A
visited = set(); todo = dict()
for A in product((0, 1), repeat=n):
    if A not in visited:
        # generate all vectors, which have the same probability
        # mirrored and cycled vectors
        same_probability_set = set()
        for i in range(n):
            tmp = [A[(i+j) % n] for j in range(n)]
            same_probability_set.add(tuple(tmp))
            same_probability_set.add(tuple(tmp[::-1]))
        visited.update(same_probability_set)
        todo[A] = len(same_probability_set)

# for each vector A, create all possible vectors B
stack = []
for A, cycled_count in dict_A.iteritems():
    ones = [sum(A[i:]) for i in range(n)] + [0]
    # + [0], so that later ones[n] doesn't throw a exception
    stack.append(([0] * n, 0, 0, 0, False))

    while stack:
        B, index, sum1, sum2, used_negative = stack.pop()
        if index < n:
            # fill vector B[index] in all possible ways,
            # so that it's still possible to reach 0.
            if used_negative:
                for v in (-1, 0, 1):
                    sum1_new = sum1 + v * A[index]
                    sum2_new = sum2 + v * A[index - 1 if index else n - 1]
                    if abs(sum1_new) <= ones[index+1]:
                        if abs(sum2_new) <= ones[index] - A[n-1]:
                            C = B[:]
                            C[index] = v
                            stack.append((C, index + 1, sum1_new, sum2_new, True))
            else:
                for v in (0, 1):
                    sum1_new = sum1 + v * A[index]
                    sum2_new = sum2 + v * A[index - 1 if index else n - 1]
                    if abs(sum1_new) <= ones[index+1]:
                        if abs(sum2_new) <= ones[index] - A[n-1]:
                            C = B[:]
                            C[index] = v
                            stack.append((C, index + 1, sum1_new, sum2_new, v == 1))
        else:
            # B is complete, calculate the sums
            count[1] += cycled_count  # we know that the sum = 0 for i = 1
            for i in range(2, n):
                sum_prod = 0
                for j in range(n-i):
                    sum_prod += A[j] * B[i+j]
                for j in range(i):
                    sum_prod += A[n-i+j] * B[j]
                if sum_prod:
                    break
                else:
                    if used_negative:
                        count[i] += 2*cycled_count
                    else:
                        count[i] += cycled_count

Usage:

You have to install pypy (for Python 2!!!). The parallel python module isn't ported for Python 3. Then you have to install the parallel python module pp-1.6.4.zip. Extract it, cd into the folder and call pypy setup.py install.

Then you can call my program with

pypy you-do-the-math.py 15

It will automatically determine the number of cpu's. There may be some error messages after finishing the program, just ignore them. n = 16 should be possible on your machine.

Output:

Calculation for n = 15 took 2:50 minutes

 1  83940771168 / 470184984576  17.85%
 2  17379109692 / 470184984576   3.70%
 3   3805906050 / 470184984576   0.81%
 4    887959110 / 470184984576   0.19%
 5    223260870 / 470184984576   0.05%
 6     67664580 / 470184984576   0.01%
 7     30019950 / 470184984576   0.01%
 8     20720730 / 470184984576   0.00%
 9     18352740 / 470184984576   0.00%
10     17730480 / 470184984576   0.00%
11     17566920 / 470184984576   0.00%
12     17521470 / 470184984576   0.00%
13     17510280 / 470184984576   0.00%
14     17507100 / 470184984576   0.00%
15     17506680 / 470184984576   0.00%

Notes and ideas:

I have a i7-4600m processor with 2 cores and 4 threads. It doesn't
matter If I use 2 or 4 threads. The cpu-usage is 50% with 2 threads and 100% with 4 threads, but it still takes the same amount of time. I don't know why. I checked, that each thread only has to the the half amout of data, when there are 4 threads, checked the results, ...
I use a lot of lists. Python isn't quite efficient in storing, I have to copy lots of lists, ... So I thought of using an integer instead. I could use the bits 00 (for 0) and 11 (for 1) in the vector A, and the bits 10 (for -1), 00 (for 0) and 01 (for 1) in the vector B. For the product of A and B, I would only have to calculate A & B and count the 01 and 10 blocks. Cycling can be done with shifting the vector and using masks, ... I actually implemented all this, you can find it in some of my older commits on Github. But it turned out, to be slower than with lists. I guess, pypy really optimizes list operations.


Haskell, 60 58 bytes

As a function we get:

f=length.show
iterate(\n->1+n+(f$n+1+f n))2>>=(++"*").show

Full program, 72 70 bytes

This outputs an infinite counterstring to STDOUT:

f=length.show
main=putStr$iterate(\n->1+n+(f$n+1+f n))2>>=(++"*").show

Inputting the length requires 20 additional bytes:

main=interact(\j->take(read j)$iterate(\n->1+n+(f$n+1+f n))2>>=(++"*").show)

This works up to your approximately your RAM size, since Haskell defaults numeric integral types to Integer.


Random spanning tree of a rectangular grid

Wolfram Language (Mathematica), 146 bytes

Block[{c,g=GridGraph@{##}},Graph[Range[1##],Join@@Reap[Do[c@n/._c:>#0[Sow[#<->n];n],{n,RandomSample@AdjacencyList[g,c@#=#]}]&@1][[2]],Options@g]]&

Try it online!

Based on my answer to the question Maze Generation.

Returns a Graph object.

For example, w = 20, h = 20 gives:


bash, 52 bytes

curl -IL codegolf.stackexchange.com/q/$1|grep 2\ 200

Takes input as a command line argument, and outputs in the form of exit code: 0 or "success" (truthy) for an undeleted question, and 1 or "failure" (falsy) for a nonexistent or deleted question.

It also prints a bunch of junk to STDERR and potentially STDOUT, but this is allowed to be ignored as per meta.

As an explanation, the -I flag to curl sends an HTTP HEAD request (fetch only the headers), and -L will follow redirects (http to https, and then /q to /questions). The full output from the curl command will look something like this:

HTTP/1.1 301 Moved Permanently
Location: https://codegolf.stackexchange.com/q/127030
X-Request-Guid: 1a0b6059-057c-448c-bfc9-a96f1b373abf
Content-Length: 160
Accept-Ranges: bytes
Date: Tue, 20 Jun 2017 04:07:30 GMT
Via: 1.1 varnish
Age: 503
Connection: keep-alive
X-Served-By: cache-itm7423-ITM
X-Cache: HIT
X-Cache-Hits: 1
X-Timer: S1497931651.709631,VS0,VE0
Vary: Fastly-SSL
X-DNS-Prefetch-Control: off
Set-Cookie: prov=933ae4b0-81b0-2b37-e26e-59a0fbb6991a; domain=.stackexchange.com; expires=Fri, 01-Jan-2055 00:00:00 GMT; path=/; HttpOnly

HTTP/2 302
date: Tue, 20 Jun 2017 04:07:31 GMT
content-type: text/html; charset=utf-8
location: https://codegolf.stackexchange.com/questions/127030/helping-danny-to-maximize-his-score
x-frame-options: SAMEORIGIN
x-request-guid: fdcaf556-7ae6-4240-89a1-ace7625f8821
strict-transport-security: max-age=15552000
accept-ranges: bytes
via: 1.1 varnish
age: 0
x-served-by: cache-nrt6132-NRT
x-cache: MISS
x-cache-hits: 0
x-timer: S1497931651.085546,VS0,VE166
vary: Fastly-SSL
x-dns-prefetch-control: off
set-cookie: prov=5e314a4f-0c50-08ef-afa2-9388b37e3b7a; domain=.stackexchange.com; expires=Fri, 01-Jan-2055 00:00:00 GMT; path=/; HttpOnly
cache-control: private
content-length: 204

HTTP/2 404
date: Tue, 20 Jun 2017 04:07:31 GMT
content-type: text/html; charset=utf-8
x-frame-options: SAMEORIGIN
x-request-guid: 3f72afb7-81e8-4e69-a8ad-474534f2abe6
strict-transport-security: max-age=15552000
accept-ranges: bytes
via: 1.1 varnish
age: 0
x-served-by: cache-nrt6132-NRT
x-cache: MISS
x-cache-hits: 0
x-timer: S1497931651.323339,VS0,VE189
vary: Fastly-SSL
x-dns-prefetch-control: off
set-cookie: prov=cede4119-eba5-d799-e376-848e4e457f07; domain=.stackexchange.com; expires=Fri, 01-Jan-2055 00:00:00 GMT; path=/; HttpOnly
cache-control: private
content-length: 42158

Note that the 2\ 200 (equivalent to '2 200') will match the line HTTP/2 200 if it exists (HTTP OK), and it will not match HTTP/2 404 (Not Found) for questions that do not exist. (The inclusion of the 2 is necessary to avoid false positives if some of the other headers happen to contain the sequence 200.)


Java, 70 bytes

String A(String[]b){return"## "+b[0]+", "+b[1]+" bytes\n\n    "+b[2];}

Assumes b[0] is the language name, b[1] is the byte count, and b[2] is the code.

Making it compilable costs 9 bytes, resulting in a 79-byte non-standalone program:

class a{String A(String[]b){return"## "+b[0]+", "+b[1]+" bytes\n\n    "+b[2];}}

The equivalent monolithic program is 103 bytes long:

interface a{static void main(String[]A){System.out.print("## "+A[0]+", "+A[1]+" bytes\n\n    "+A[2]);}}

The monolithic one works with command line arguments, assuming these just like the non-standalone program:

First argument is the language name
Second argument is the byte count
Third argument is the code

Java (lambda expression), 56 48 bytes

(b)->"## "+b[0]+", "+b[1]+" bytes\n\n    "+b[2];

This is a java.util.function.Function<String[], String>.

None of these programs/functions handle multiline strings. To do so, simply replace b[2] and A[2] with b[2].replace("\n","\n    ") and A[2].replace("\n","\n    ") - doing so adds 23 bytes.


Python 3, 226 224 bytes

My first Python golf, so probably very sub-optimal.
It produces a whole lot of trailing whitespace, but there are no preceding newlines, and at most two preceding spaces.
The input needs to be given by hand from command line (maybe someone knows a shorter way to get multiline input in Python...).

e,z,s=enumerate,'0',list(iter(input,""))
p=''.join(s)*5
r=[len(p)*[' ']for _ in p]
for y,l in e(s):
 for x,c in e(l):
  for i in range(-2,3):r[2*(x+y+(s>[z]))+i*(c>z)][2*(x+len(s)-y)+i*(c<z)]='#'
for l in r:print(''.join(l))

The idea is to initialize a huge array of spaces r, then iterate through the input and replace the spaces with # as needed, and finally print the whole array.
A trick I used is to compare characters to z = '0' instead of testing equality to '/' or '\', which saves a bunch of bytes.


Write code to determine the accepted answer

R, 1 char

1

You can supply the id of an answer as a command line argument if you wish. :)
Link to ideone.

Further elaboration

Since it is not practical for an answers to execute other answers (different languages, etc.) and evaluate them based on their result the only remaining way I can see for them to give a score is to use some code metric.

I have noticed that all other answers so far give a higher score to shorter programs. I believe this is the shortest code possible so it should rank high in the result of other answers.

How and what answer my code gives for other answers seams to be less relevant. The only important aspect is that others rank my answer high.


JavaScript (ES6), 108 bytes
a=>`01
4
9bc
efgjk

02
567
abd
efijk

03
587
9bc
efgjk

01
4
9bd
efhij

`.replace(/./g,n=>a[parseInt(n,36)])

Try it online!

Alternate version, 114 bytes
A slightly better compression, but sadly ruined by the larger decompression code.
a=>`835fc3cbbd3
84db3db4bbdb3
85cd1cc3cbbd3
835fc4bbcb3

`.replace(/./g,n=>a[n='0x'+n,i=n%8&&n%8-2+i]+[`
`[n>>3]])

Try it online!


C99 - 3x3 board in 0.084s
2020 edit/disclaimer: See comments section. It looks like there may have been errors in the original code. Proceed to the remainder of this answer with some skepticism until it is fixed.
Edit: I refactored my code and did some deeper analysis on the results.
Further Edits: Added pruning by symmetries. This makes 4 algorithm configurations: with or without symmetries X with or without alpha-beta pruning
Furthest Edits: Added memoization using a hash table, finally achieving the impossible: solving a 3x3 board!
Primary features:

straightforward implementation of minimax with alpha-beta pruning
very little memory management (maintains dll of valid moves; O(1) updates per branch in the tree search)
second file with pruning by symmetries. Still achieves O(1) updates per branch (technically O(S) where S is the number of symmetries. This is 7 for square boards and 3 for non-square boards)
third and fourth files add memoization. You have control over the hashtable's size (#define HASHTABLE_BITWIDTH). When this size is greater than or equal to the number of walls, it guarantees no collisions and O(1) updates. Smaller hashtables will have more collisions and be slightly slower.
compile with -DDEBUG for printouts

Potential improvements:

fix small memory leak fixed in first edit
alpha/beta pruning added in 2nd edit
prune symmetries added in 3rd edit (note that symmetries are not handled by memoization, so that remains a separate optimization.)
memoization added in 4th edit
currently memoization uses an indicator bit for each wall. A 3x4 board has 31 walls, so this method couldn't handle 4x4 boards regardless of time constraints. the improvement would be to emulate X-bit integers, where X is at least as large as the number of walls.

Code
Due to lack of organization, the number of files has grown out of hand. All code has been moved to this Github Repository. In the memoization edit, I added a makefile and testing script.
Results

Notes on Complexity
Brute-force approaches to dots and boxes blow up in complexity very quickly.
Consider a board with R rows and C columns. There are R*C squares, R*(C+1) vertical walls, and C*(R+1) horizontal walls. That is a total of W = 2*R*C + R + C.
Because Lembik asked us to solve the game with minimax, we need to traverse to the leaves of the game tree. Let's ignore pruning for now, because what matters is orders of magnitude.
There are W options for the first move. For each of those, the next player can play any of the W-1 remaining walls, etc.. That gives us a search-space of SS = W * (W-1) * (W-2) * ... * 1, or SS = W!. Factorials are huge, but that's only the beginning. SS is the number of leaf nodes in the search space. More relevant to our analysis is the total number of decisions which had to be made (i.e. the number of branches B in the tree). The first layer of branches has W options. For each of those, the next level has W-1, etc.
B = W + W*(W-1) + W*(W-1)*(W-2) + ... + W!

B = SUM W!/(W-k)!
  k=0..W-1

Let's look at some small table sizes:
Board Size  Walls  Leaves (SS)      Branches (B)
---------------------------------------------------
1x1         04     24               64
1x2         07     5040             13699
2x2         12     479001600        1302061344
2x3         17     355687428096000  966858672404689

These numbers are getting ridiculous. At least they explain why the brute-force code seems to hang forever on a 2x3 board. The search-space of a 2x3 board is 742560 times larger than 2x2. If 2x2 takes 20 seconds to complete, a conservative extrapolation predicts over 100 days of execution time for 2x3. Clearly we need to prune.
Pruning Analysis
I started by adding very simple pruning using the alpha-beta algorithm. Basically, it stops searching if an ideal opponent would never give it its current opportunities. "Hey look - I win by a lot if my opponent lets me get every square!", thought no AI, ever.
edit I have also added pruning based on symmetrical boards. I don't use a memoization approach, just in case someday I add memoization and want to keep that analysis separate. Instead, it works like this: most lines have a "symmetric pair" somewhere else on the grid. There are up to 7 symmetries (horizontal, vertical, 180 rotation, 90 rotation, 270 rotation, diagonal, and the other diagonal). All 7 apply to square boards, but the last 4 don't apply to non-square boards. Each wall has a pointer to it's "pair" for each of these symmetries. If, going into a turn, the board is horizontally symmetric, then only one of each horizontal pair needs to be played.
edit edit Memoization! Each wall gets a unique id, which I conveniently set to be an indicator bit; the nth wall has the id 1 << n. The hash of a board, then, is just the OR of all walls played. This is updated at each branch in O(1) time. The size of the hashtable is set in a #define. All tests were run with size 2^12, because why not? When there are more walls than bits indexing the hashtable (12 bits in this case), the least significant 12 are masked and used as the index. Collisions are handled with a linked list at each hashtable index. The following chart is my quick-and-dirty analysis of how hashtable size affects performance. On a computer with infinite RAM, we would always set the table's size to the number of walls. A 3x4 board would have a hashtable 2^31 long. Alas we don't have that luxury.

Ok, back to pruning.. By stopping the search high in the tree, we can save a lot of time by not going down to leaves. The 'Pruning Factor' is the fraction of all-possible-branches which we had to visit. Brute-force has a pruning factor of 1. The smaller it is, the better.


Python 3 (557 504 488)

import sys
s=sys.stdin
M=int(next(s))+1
j=Z=M*M-M
S=s.read(Z)
P=0
b=[0]*3
while j>0:j-=1+(j%M<1);b[int(S[j])]|=1<<j;P|=1<<j
N=lambda x:(x<<1|x>>1|x<<M|x>>M)&P&~x
def h(a,b):t=a|N(a)&b;return h(t,b)if t!=a else a
c,r,m=map(int,next(s).split())
o=m%2+1
p=1<<M*r+c
b[m]|=p
for n in(p<<1,p>>1,p<<M,p>>M):
 e=h(n&P,b[o])
 if~b[m]&N(e)<1<=n&b[o]:b[o]&=~e
_,B,W=b
g=~b[o]&N(h(p,b[m]))>=1>~_&p
print(+g)
q=''
while j<Z:
 r=1<<j
 if g*j%M>M-2:print(q);q=''
 else:q+='012E'[(r&B>0)+(r&W>0)*2]
 j+=1

Uses 3 bitfields to represent the board - one each for black, white, and empty spaces. Makes the find neighbors N and get chain h operations very concise.

An ungolfed version with lots of comments:
https://gist.github.com/airfrog/8429006


Find the length of a number's "base-jumping" path

Jelly, 7 bytes

b@Ṁ‘ɗƬL

A dyadic Link accepting b on the left and N on the right which yields the sequence length.

Try it online!

How?

b@Ṁ‘ɗƬL - Link: b; N
     Ƭ  - Collect up until no longer unique, applying:
    ɗ   -   last three links as a dyad - i.e. f(X[initially b], N):
 @      -     with swapped arguments:
b       -       convert (N) to base (X)
  Ṁ     -     maximum
   ‘    -     incremented
      L - length


Scratch, 1604 – 125 = 1479

I'm here for the fun, not the golf.

Edit: updated scoring method based on community consensus.

Main program:

Individual sprites:

This is the sprite with number 0. The other sprites have the same script, except the number.

Play with it online.

Code used for byte counting: (Using snippet to hide code)

when green flag clicked
set [s v] to [0]
delete (all v) of [a v]
forever
  set [x v] to (pick random (0) to (3))
  add (x) to [a v]
  set [i v] to [1]
  repeat (length of [a v] :: list)
    broadcast (item (i) of [a v] :: list)
    wait (0.3) secs
    change [i v] by (1)
  end
  set [i v] to [1]
  wait until <(x) = [4]>
end

when I receive [0 v]
play sound [0 v]
next costume
wait (0.3) secs
next costume

when this sprite clicked
broadcast [0 v]
wait (0.3) secs
if <[0] = (item (i) of [a v] :: list)> then
  change [i v] by (1)
else
  stop [all v]
end
if <(i) > (length of [a v] :: list)> then
  set [x v] to [4]
  change [s v] by (1)
end

when this sprite clicked
broadcast [3 v]
wait (0.3) secs
if <[3] = (item (i) of [a v] :: list)> then
  change [i v] by (1)
else
  stop [all v]
end
if <(i) > (length of [a v] :: list)> then
  set [x v] to [4]
  change [s v] by (1)
end

when I receive [3 v]
play sound [3 v]
next costume
wait (0.3) secs
next costume

when I receive [1 v]
play sound [1 v]
next costume
wait (0.3) secs
next costume

when this sprite clicked
broadcast [1 v]
wait (0.3) secs
if <[1] = (item (i) of [a v] :: list)> then
  change [i v] by (1)
else
  stop [all v]
end
if <(i) > (length of [a v] :: list)> then
  set [x v] to [4]
  change [s v] by (1)
end

when this sprite clicked
broadcast [2 v]
wait (0.3) secs
if <[2] = (item (i) of [a v] :: list)> then
  change [i v] by (1)
else
  stop [all v]
end
if <(i) > (length of [a v] :: list)> then
  set [x v] to [4]
  change [s v] by (1)
end

when I receive [2 v]
play sound [2 v]
next costume
wait (0.3) secs
next costume

Note: Code automatically generated using scratchblocks generator, modified as somehow the generator doesn't correctly handle decimal numbers (treating 0.3 as 0).

Screenshot:

Note: Please do not press two buttons within 0.3 seconds.


Adding up the digits and the digits reversed

05AB1E, 7 bytes
LDRJsJ+

Try it online.
Explanation
LDRJsJ+

L        range from 1 .. input
 D       duplicate
  R      reverse
   JsJ   convert both arrays to strings
      +  add (coerces both strings to ints)


Generating versions of an array with elements changed in ruby

Ruby, 102 99 98 95 bytes

(k=input.map &:dup)[$.-=1][0]=%i[nop jmp acc][k[$.][0]<=>:jmp]until(r=try_with k||$:)[1]>:t;p r

Try it online!
I assume that input and try_with are mandatory names for the Advent of Code challenge. If not, the code can obviously be even shorter. Here, I also assume that the try_with method will accept invalid input, that is, an array whose elements are not of the form [:instruction, integer]. See below for a slightly longer version in case try_with strictly requires valid input.
See commented code below for a complete list of ideas used. Apart from generic code-golf tips such as 'use short variable names', or common Ruby tips such as 'omit parentheses in method calls', here are some specific tips for the problem posed:

Instead of each_with_index, use a counter variable together with an anonymous lambda and redo together with until (or while) in modifier form. For the counter, a good choice in this case is the predefined global variable $., which is initialised to 0. Processing the input array in reverse (by decrementing $. in place) is the best approach. Incrementing $. in place doesn't work (because input[0] would be skipped); incrementing $. at the end of the loop would cost bytes.
Only call dup at the lowest level, that is, on the elements of input, not on input itself.
Lexicographical comparisons work with symbols, so >:t is better than == :terminate, for example.
It turns out to be slightly shorter to use the spaceship operator <=> instead of a ternary conditional to choose between instructions. In the code, k[$.][0]<=>:jmp returns -1 if the current instruction is :acc, 0 if it is :jmp, and 1 if it is :nop. Use these values to index into an array of the three symbols, ordered such that the correct replacement is chosen.

(k=                # use parentheses to define variables inline
   input.map &:dup # only duplicate the lowest-level arrays, and do all at once
)[$.-=1][0]        # use $. as a counter and decrement in place
=%i[nop jmp acc][k[$.][0]<=>:jmp] # use the spaceship operator to choose between instructions
until              # loop with until
(r=try_with k      # omit parentheses in the call to try_with
||$:)[1]           # on the first iteration (only), k is nil so pass the predefined array $: to try_with as dummy input
>:t;               # test for >:t instead of ==:terminate
p r                # print the result

Ruby, 98 bytes

p->{(k=input.map &:dup)[$.-=1][0]=%i[nop jmp acc][k[$.][0]<=>:jmp];(r=try_with k)[1]>:t||redo;r}[]

Try it online!
Use this version if try_with rejects $: as valid input. Here, we iterate using an anonymous lambda and redo.


Convert Japanese Mario titles to American titles

sed, 52

1 byte saved thanks to @MikeScott

Straightforward replacement:
s/ 2/: The Lost Levels/
s/USA/Bros. 2/
s/B.*4/World/

Try it online.


Charcoal, 16 bytes

ＮλＦλ«Ｐ↘⁻λι←↙¹‖Ｔ→

Try it online!

How?

Ｎλ inputs the size of the largest mountain into λ. Ｆλ« runs a loop over values of ι from 0 through λ-1. (The closing » is implied at the end of the program.)

Inside the loop, Ｐ↘⁻λι calculates λ-ι and draws, without moving the cursor afterward, a line of that length going southeast. Based on its direction, this line will consist of \ characters. ← moves one step to the west, and ↙¹ draws a line of length 1 going southwest (made of /). Finally, ‖Ｔ→ horizontally reflects the drawing, transforming characters as appropriate: \ becomes / and / becomes \.

Adding the dump instruction Ｄ at the beginning of the loop (try it) allows us to see the progression:

    /\
   /
  /
 /
/
    /\
   /\ \
  /    \
 /      \
/        \
    /\
   / /\
  / /\ \
 / /    \
/ /      \
    /\
   /\ \
  / /\ \
 / /\ \ \
/ /    \ \
    /\
   / /\
  / /\ \
 / / /\ \
/ / /\ \ \


Ruby

s = [[/t{1}he_way/,'to_a'],[/\*j{1}ewel/,'*rule']].to_a
puts <<'-'.*(2).tap { |code| s.each { |rule| code.sub! *rule } }, '-'
s = [[/t{1}he_way/,'to_a'],[/\*j{1}ewel/,'*rule']].the_way
puts <<'-'.*(2).tap { |code| s.each { |rule| code.sub! *jewel } }, '-'
-
s = [[/t{1}he_curse/,'reverse'],[/\*c{1}raze/,'*phrase']].reverse
puts <<'-'.*(2).tap { |code| s.each { |phrase| code.sub! *phrase } }, '-'
s = [[/t{1}he_curse/,'reverse'],[/\*c{1}raze/,'*phrase']].the_curse
puts <<'-'.*(2).tap { |code| s.each { |phrase| code.sub! *craze } }, '-'
-
s = [[/r{1}eject/,'collect'],[/\*b{1}ird/,'*word']].collect
puts <<'-'.*(2).tap { |code| s.each { |word| code.sub! *word } }, '-'
s = [[/r{1}eject/,'collect'],[/\*b{1}ird/,'*word']].reject
puts <<'-'.*(2).tap { |code| s.each { |word| code.sub! *bird } }, '-'
-
puts <<'-'.*(2).tap { |code| [[/\*l{1}augh/,'*half']].each { |half| code.sub! *half } }, '-'
puts <<'-'.*(2).tap { |code| [[/\*l{1}augh/,'*half']].each { |half| code.sub! *laugh } }, '-'
-

Don't pronounce the dashes, they're just there to delimit stanzas. Scansion's not perfect but decent.


Convert a Forsyth-Edwards Notation string to ASCII art

Retina, 13 bytes

\d
$*
/
¶

|

Try it online!

Explanation

The first part (note the trailing space):

\d
$*

is to convert a to the specific number of spaces. Retina has a $* feature to repeat. The way it works is: <num>$*<char> if there is no <num>, Retina will assume $& or the matched string, in this case the matched number.

The next part:

/
¶

is pretty simple, it replaces all / with ¶ which is a newline.

The last part works the same:

|

This will replace everything (hence why there is nothing on the first line) with |. Putting a | everywhere.


Total: 104 101 99 chars

Problem 1

   12 chars
 while L[6:]:

Problem 2

   5 chars
 x>0<y

Problem 3

   7 chars
 L=L[b:]

Problem 4

   13 chars
 len(set(L))<2
 L[1:]==L[:-1]

Problem 5

   13 chars
 L+=set(L)&{n}

Problem 6

   11 chars
 (x>0)-(x<0)

 8 chars (Python 2)
 cmp(x,0)

Problem 7

   12 chars
 while[.5]<L:

Problem 8

   9 chars
 while~-n:

Problem 9

   5 chars
 s<'.'

Problem 10

   15 chars
 'LWoisne'[b::2]


JavaScript, 105 97 bytes
Saved 8 bytes thanks to @Patrick Roberts!
l=a=>a.slice(1,-1)
p=a=>l(a).map(l)
c=a=>a.join``.replace(/[^0]/g,"")
s=a=>c(p(a))<c(a)?s(p(a)):a

Defines function s, which returns a 2D array of integers when provided a 2D array of integers as input.
How it Works

function l: given an array a, returns a copy without its first and last indexes.

function p: given a 2D array a, calls l to remove the first and last row, then for each remaining row calls l to remove the fist and last column. This performs the onion peeling.

function c: given a 2D array a, returns a string that only contains the 0s in the stringified form of a.

function s: given a 2D array a, calls c on the peeled form of the array given by p, and on the array itself. Compares these strings lexicographically to determine if the peeled form has less 0s than the original. If it does, then the original is contaminated, so call s recursively on the peeled form. Otherwise return the original.


CJam, 59 52 50 49 45 43 42 bytes

qN/ee::~e!{_0+{0a&}#>W%_{1$|(z@-},,\;}%:e<

Thanks to @MartinBüttner for golfing off 3 bytes and paving the way for 4 more!

Try it online in the CJam interpreter.

How it works

qN/      e# Read all input and split it at linefeeds.
ee       e# Enumerate the lines.
         e# STACK: [[0 "i0 i1 ..."] [1 "j0 j1 ..."] ...]
::~      e# Apply ~ (bitwise NOT/evaluate) to each item of the pairs.
         e# STACK: [[-1 i0 i1 ...] [-2 j0 j1 ...] ...]
e!       e# Push all unique permutations of the resulting array.
{        e# For each permutation:
  _0+    e#   Push a copy and append 0 to it.
  {0a&}# e#   Find the first index of an element that contains 0.
  >      e#   Discard all previous elements of the array.
  W%     e#   Reverse the resulting array.
         e#   We now have a (partial) permutation that contains
         e#   all treasures and ends with a treasure.
  _      e#   Push a copy. The original (which contains lists, but no
              numbers) will serve as accumulator.
  {      e#   Filter; for each list in the array:
    1$|  e#     Push a copy of the accumulator and perform set union.
    (    e#     Shift out the first element (bitwise NOT of 0-based index).
    z    e#     Apply absolute value to push the 1-based index.
    @-   e#     Perform set difference with the former state of the
         e#     accumulator. This pushes an empty list iff the 1-based
         e#     index was already in the accumulator, i.e., iff we already
         e#     had a key.
  },     e#   Keep the element if we did not have the key.
  ,      e#   Count the kept elements.
  \;     e#   Discard the accumulator from the stack.
}%       e#
:e<      e# Get the minimum of all results.


print 1 to 100 without using recursion and conditions

C (90) (79) (59) (47) (42) (40)

static int

x=1;a(){char b[8];printf("%d\n",x++);b[24]-=5*(1-x/101);}main(){a();return 0;}

The function a which prints the numbers does not call itself! I exploited a buffer overflow and changed the return address to make the program counter go over function a again as long as I need.

I don't know if this is considered to be a recursion, but I thought it would worth trying.
This code works on my 64-bit machines with gcc 4.6, for other platforms the last statement of function a, could be a little different.

Exp1: I allocated a dummy buffer on stack b, and then addressed a passed-by-end location, which is the location of return address. I anticipated the distance between start of buffer and return address location from disassembly of function a.

Exp2: Expression 5*(1-x/101), is 5 for all x<=100 and 0 for x=101. By looking at disassembly of main (in my case), if you decrease the return address by 5, you will set the PC to calling point of a again. In the updated codes, the return value of printf is used for checking loop condition.

Update: After applying ugoren's suggestions and some other changes:

x;a(){int b[2];b[3*(printf("%d\n",++x)&2)]-=5;}main(){a();}

Update2: After Removing function a:

x;main(){int b[2];b[6^printf("%d ",++x)&4]-=7;}

Update3:

x;main(b){(&b)[1|printf("%d ",++x)&2]-=7;}

Update4: Thanks to mbz :)

x;main(b){(&b)[3|printf("%d ",++x)]-=7;}


Alphabet to Number and Number to Alphabet

Pure Bash, 51
Most of the rest of the answers use some sort of conditional.  This one dispenses with conditionals entirely, and instead treats the input as a base-36 number which indexes into an appropriately constructed bash-brace-expansion array:
a=(_ {A..I} {1..26} {J..Z} {A..Z})
echo ${a[36#$1]}

Ideone.


Counting unit squares circle passes through

Python 2, 54 bytes

f=lambda r,x=0:r-x and-~((r*r-x*x)**.5%1>0)*4+f(r,x+1)

Try it online!
Less golfed (55 bytes) (TIO)
lambda r:8*r-4*sum((r*r-x*x)**.5%1==0for x in range(r))

This estimates the output as 8*r, then corrects for vertex crossings. The result is 8*r-g(r*r), where g(x) counts the number of ways to write x as a sum of two squares (except g(0)=0).
If the circle never went through any vertices, the number of cells touched would equal the number of edges crossed. The circle passes through 2*r vertical gridlines and 2*r horizontal gridlines, passing each one in both directions, for a total of 8*r.
But, each crossing at a vertex counts as two edge crossings while only entering one new cell. So, we compensate by subtracting the number of vertex crossings.
This includes the points on axes like (r,0) as well as Pythagorean triples like (4,3) for r=5.
We count for a single quadrant the points (x,y) with x>=0 and y>0 with x*x+y*y==n, then multiply by 4. We do this by counting the numer of sqrt(r*r-x*x) that are whole number for x in the interval [0,r).


Perl - 131 96 94 chars

$i="";for$_(split/([\Q$ARGV[0]$ARGV[1]\E])/,$ARGV[2]){$i=~s/..// if/[\Q$ARGV[1]\E]/;print "$i$_\n"if$_;$i.='  'if/[\Q$ARGV[0]\E]/;}

Seems like there should be room for eliminating common expressions, at least, but it's a quick take that handles the example, as well as Joey Adams's hypothetical about arbitrary brackets.

There was, indeed, plenty of room for improvement:

$_=pop;($s,$e)=map"[\Q$_\E]",@ARGV;for(split/($s|$e)/){print"  "x($i-=/$e/),"$_\n"if$_;$i+=/$s/}

...and still a little more:

$_=pop;($s,$e)=map"[\Q$_\E]",@ARGV;map{print"  "x($i-=/$e/),"$_\n"if$_;$i+=/$s/}split/($s|$e)/


Python 2, 81 bytes

f=lambda k,n:k and sorted([x/2,x*3+1][x%2]for x in f(k-1,n*2))[:n]or range(1,n+1)

Try it online!
-19 bytes thanks to Leo and Bubbler
-11 bytes thanks to dingledooper (-6 + -5 from Python 2)
-8 bytes by swapping over to the brute force solution
-2 bytes thanks to Noodle9
To get \$s_k\$ up to \$n\$ elements, we only need to get \$s_{k-1}\$ up to \$2n\$ elements.


Brackets autocomplete

This is my biggest tip for anyone golfing in Keg: when writing programs, brackets used in loops or if-statements are automatically balanced if there are unclosed brackets.

For example:

(9|0.)

Can be shortened to:

(9|0.

And:

{:1=[1.]}

Can be shortened to:

{:1=[1.


Python, 1281.375 1268.625 bytes

We encode the Latin square one “decision” at a time, where each decision is of one of these three forms:

which number goes in row i, column j;
in row i, which column the number k goes in;
in column j, which row the number k goes in.

At each step, we make all the logical inferences we can based on previous decisions, then pick the decision with the smallest number of possible choices, which therefore take the smallest number of bits to represent.

The choices are provided by a simple arithmetic decoder (div/mod by the number of choices).  But that leaves some redundancy in the encoding: if k decodes to a square where the product of all the numbers of choices was m, then k + m, k + 2⋅m, k + 3⋅m, … decode to the same square with some leftover state at the end.

We take advantage of this redundancy to avoid explicitly encoding the size of the square.  The decompressor starts by trying to decode a square of size 1.  Whenever the decoder finishes with leftover state, it throws out that result, subtracts m from the original number, increases the size by 1, and tries again.

import numpy as np

class Latin(object):
    def __init__(self, size):
        self.size = size
        self.possible = np.full((size, size, size), True, dtype=bool)
        self.count = np.full((3, size, size), size, dtype=int)
        self.chosen = np.full((3, size, size), -1, dtype=int)

    def decision(self):
        axis, u, v = np.unravel_index(np.where(self.chosen == -1, self.count, self.size).argmin(), self.count.shape)
        if self.chosen[axis, u, v] == -1:
            ws, = np.rollaxis(self.possible, axis)[:, u, v].nonzero()
            return axis, u, v, list(ws)
        else:
            return None, None, None, None

    def choose(self, axis, u, v, w):
        t = [u, v]
        t[axis:axis] = [w]
        i, j, k = t
        assert self.possible[i, j, k]
        assert self.chosen[0, j, k] == self.chosen[1, i, k] == self.chosen[2, i, j] == -1

        self.count[1, :, k] -= self.possible[:, j, k]
        self.count[2, :, j] -= self.possible[:, j, k]
        self.count[0, :, k] -= self.possible[i, :, k]
        self.count[2, i, :] -= self.possible[i, :, k]
        self.count[0, j, :] -= self.possible[i, j, :]
        self.count[1, i, :] -= self.possible[i, j, :]
        self.count[0, j, k] = self.count[1, i, k] = self.count[2, i, j] = 1
        self.possible[i, j, :] = self.possible[i, :, k] = self.possible[:, j, k] = False
        self.possible[i, j, k] = True
        self.chosen[0, j, k] = i
        self.chosen[1, i, k] = j
        self.chosen[2, i, j] = k

def encode_sized(size, square):
    square = np.array(square, dtype=int)
    latin = Latin(size)
    chosen = np.array([np.argmax(square[:, :, np.newaxis] == np.arange(size)[np.newaxis, np.newaxis, :], axis=axis) for axis in range(3)])
    num, denom = 0, 1
    while True:
        axis, u, v, ws = latin.decision()
        if axis is None:
            break
        w = chosen[axis, u, v]
        num += ws.index(w)*denom
        denom *= len(ws)
        latin.choose(axis, u, v, w)
    return num

def decode_sized(size, num):
    latin = Latin(size)
    denom = 1
    while True:
        axis, u, v, ws = latin.decision()
        if axis is None:
            break
        if not ws:
            return None, 0
        latin.choose(axis, u, v, ws[num % len(ws)])
        num //= len(ws)
        denom *= len(ws)
    return latin.chosen[2].tolist(), denom

def compress(square):
    size = len(square)
    assert size > 0
    num = encode_sized(size, square)
    while size > 1:
        size -= 1
        square, denom = decode_sized(size, num)
        num += denom
    return '{:b}'.format(num + 1)[1:]

def decompress(bits):
    num = int('1' + bits, 2) - 1
    size = 1
    while True:
        square, denom = decode_sized(size, num)
        num -= denom
        if num < 0:
            return square
        size += 1

total = 0
with open('latin_squares.txt') as f:
    while True:
        square = [list(map(int, l.split(','))) for l in iter(lambda: next(f), '\n')]
        if not square:
            break

        bits = compress(square)
        assert set(bits) <= {'0', '1'}
        assert square == decompress(bits)
        print('Square {}: {} bits'.format(len(square), len(bits)))
        total += len(bits)

print('Total: {} bits = {} bytes'.format(total, total/8.0))

Output:

Square 1: 0 bits
Square 2: 1 bits
Square 3: 3 bits
Square 4: 8 bits
Square 5: 12 bits
Square 6: 29 bits
Square 7: 43 bits
Square 8: 66 bits
Square 9: 94 bits
Square 10: 122 bits
Square 11: 153 bits
Square 12: 198 bits
Square 13: 250 bits
Square 14: 305 bits
Square 15: 363 bits
Square 16: 436 bits
Square 17: 506 bits
Square 18: 584 bits
Square 19: 674 bits
Square 20: 763 bits
Square 21: 877 bits
Square 22: 978 bits
Square 23: 1097 bits
Square 24: 1230 bits
Square 25: 1357 bits
Total: 10149 bits = 1268.625 bytes


GolfScript, 16 bytes

{%}+")1$~":x`+0x

Try it online in Web GolfScript.

Example run

$ echo -n 3 | golfscript quining.gs
{3 % ")1$~"}0)1$~
$ echo -n 3 | golfscript quining.gs | golfscript
{3 % ")1$~"}1)1$~
$ echo -n 3 | golfscript quining.gs | golfscript | golfscript
{3 % ")1$~"}2)1$~
$ echo -n 3 | golfscript quining.gs | golfscript | golfscript | golfscript
{3 % ")1$~"}0)1$~

Generator

                 # (implicit) Read from STDIN.
{%}+             # Concatenate the read input with the block.
                 # For example, "3"{%}+ -> {3 %}.
    ")1$~":x     # Push that string and save it in the the variable `x'.
            `+   # Inspect the string and concatenate it with the block.
                 # For example, {3 %}'")1$~"'+ -> {3 % ")1$~"}
              0x # Push a 0 and the string stored in `x'.

Modular quine

For example, the modular quine {3 % ")1$~"}0)1$~ works as follows.

{          }      # Define a block.
 3 %              # Take the integer on the stack modulo 3.
     ")1$~"       # Push that string.
            0)    # Push 0 and increment. Pushes 1.
              1$~ # Copy the block from the bottom of the stack and execute it.

The original copy of the block, the modified integer and the string the block pushed are printed, resulting in {3 % ")1$~"}1)1$~.

All printed programs have a trailing linefeed, which GolfScript prints automatically.


05AB1E, 9 6 5 bytes
LnIÖO

Try it online or verify all test cases.
Previous 9 6 bytes approach:
LR.ΔnÖ

-3 bytes thanks to @ovs.
Try it online or verify all test cases.
Explanation:

L       # Push a list in the range [1, (implicit) input]
 n      # Take the square of each value in the list
  IÖ    # Check which squares are divisible by the input (1 if truthy; 0 if falsey)
    O   # And sum those checks
        # (after which this sum is output implicitly as result)

L       # Push a list in the range [1, (implicit) input]
 R      # Reverse it to [input, 1]
  .Δ    # Find the first value in this list which is truthy for:
    n   #  Square the current value
     Ö  #  Check if the (implicit) input is evenly divisible by this square
        # (after which the found value is output implicitly as result)


Python, 672 548 characters, more interesting puzzles

Although going strictly by the rules, my other Python program beats this one, I decided to write one that would generate more interesting puzzles anyway. Here it is:

R=range;import random as J;X=J.randint
x=(0,1,-1,0);y=x[2:]+x
g=lambda r,c:(0<=r<H)+(0<=c<W)>1and f[r][c]or x[(r,c)in(A,E)]
l=lambda r,c:g(r+y[d],c+x[d])<1and(r,c)or l(r+y[d],c+x[d])
H,W,P=input();J.seed(P)
while 1:
 A=(-1,X(0,W));E=(H,X(0,W));f=[[X(0,7)for _ in R(W)]for _ in R(H)]
 q=[(A,'')];n=z={}
 while q and n!=E:
    n,O=q.pop()
    for d in R(4):
     N=l(*n)
     if g(n[0]+y[d],n[1]+x[d])and N not in z:q[:0]=[(N,O+"URLD"[d])];z[N]=1
 if(n==E)*len(O)>min(H,W):print"\n".join(''.join('O.'[c>0]for c in T)for T in f),"\nT",A[1],"\nB",E[1],"\n",O;break

Indentation levels are space, tab, tab+space.

Samples:

$ echo [10,15,0] | python ice2.py
.....OO........
...............
...O....O.OO..O
...........O...
..O....O.......
.......O....O..
....O..........
.............O.
..............O
...............
T 1
B 10
DLURDRURULDRD

It uses P as a seed, so each P will generate the same puzzle, and each different P is exceedingly likely to be different:

$ echo [10,15,1] | python ice2.py
.OOO.O.........
...O......O.O.O
.......O.......
..O..........OO
.....O.........
.............O.
.O.............
.O............O
O....O.........
......O........
T 14
B 8
DLDRDLURULD

It works reasonably fast up to sizes of M=25,N=40 but past that it gets really slow. It should theoretically work for M=30, N=40 if you let it run long enough. I've manually written in the trail here since it is hard to follow - the program just outputs the puzzle.

$ echo [25,40,0] | python ice2.py
                   *
...................dO....urrrO..O..O....
....O.....O........dO....u..dO..........
..........O.....O..d....Ou.Odrrrrrrrrrrr
...........O.......d.O..Ou..O.....OOllld
.O....O.OO.........drrrrrrO....Olllud..O
O......O...O.O.....O............dO.ud...
O........OO..........O.........Od..ud..O
.........O......................d..ud...
....O.....O.O....O.....O........d..ud.O.
.....O..O...................O...d..udO..
.........O.........O..O.........d..ud...
.......O.O...O..O.OO....O...OOlldOOld...
........Olllllllllu....OO.OO..dOO...O...
.O.O....Od........u......O....d..O...O..
..O....O.d........u..O........d..O..O...
....O....d..O.....uO.....O....d.........
.........d........u...........d.........
.........d....O...u.O..O.....Od.O.......
........Od...O....u...........d.........
.O.....OuxrrrrO...u...OOOO..O.d.........
........udO..dO.O.u...........d.........
O..O.O..ud...d..urrO..........d.O...O...
........ud...d..u.O.O........Od..O...O..
..OO....ud..Od..u......OllllludO.....O..
..O....OldO..dOOlllllllld...Old...O..O..
             *
T 19
B 13
DRURDRDLDLULDLDLULDLURULDLURD

Explanation:

The program loops, generating a random start position on the top, a random end position on the bottom, and a random grid with a 12.5% chance for a boulder on any given spot. It then solves the puzzle with a breadth-first-search and if the solution exists and is bigger than min(H,W), it prints and exits.


How do I alias member functions in Python?

No problemo! You can alias a method, but you have to know how to use it:

>>> r=str.replace
>>> a='hello'
>>> r(r(r(r(a,'h','j'),'e','i'),'l','m'),'o','y')
'jimmy'

The key is that you have to pass self explicitly, because the alias is a kind of function that takes an extra argument that takes self:

>>> type(r)
<type 'method_descriptor'>


Average an array until all numbers are (almost) equal

Perl 6,  83  82 bytes

->\a(\b,|c){(c,{[(b,|$_,b).rotor(3=>-2).map: *.sum/3]}...{(b+.sum)/a~~b-1..b+1})-1}

Try it

->\a(\b,|c){(c,{[(b,|$_,b).rotor(3=>-2).map: *.sum/3]}...{1>abs (b+.sum)/a -b})-1}

Try it (also works for complex numbers

Expanded

->      # pointy block lambda

  \a    # the input array
  (
    \b, # the first value
    |c  # all the rest of the values
  )

{
  (
    # generate a sequence

    c,                 # initialize the sequence starting with the second value

    {                  # bare block lambda with implicit parameter ｢$_｣

      [                # turn the result from a Seq into an array

        ( b, |$_, b )  # re-add the first element
                       # and add it to the end

        .rotor(3=>-2)  # grab 3 at a time, backing up 2

        .map: *.sum/3  # return the average for each sub sequence

      ]
    }

    ...                # keep calling that to generate values until

    {
      1 > abs ( b + .sum )/a - b     # they are almost equal
    }

  ) - 1 # count them and reduce by one (ignore initial value)
}


Random script that isn't actually random

C
It's important to decide who is buying as quickly as possible, so as not to waste precious drinking time - hence C is the obvious choice in order to get maximum performance:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
    const char *buyer;
    int n;

    srand(time(NULL)); // make sure we get a good random seed to make things fair !
    n = rand();
    switch (n % 5)
    {
        case 0: buyer = "John";
        case 1: buyer = "Jeff";
        case 2: buyer = "Emma";
        case 3: buyer = "Steve";
        case 4: buyer = "Julie";
    }
    printf("The person who is buying the drinks today is: %s !!!\n", buyer);
    return 0;
}

Explanation:

 This would work just fine if there was a break; after each case in the switch statement. As it stands however each case "falls through" to the next one, so poor Julie always ends up buying the drinks.


JavaScript (ES6), 40 37 bytes

f=(n,i=s='0')=>(s+=++i)[n]?i-1:f(n,i)
<input type=number min=1 value=1 oninput=o.textContent=f(this.value)><pre id=o>0

Edit: Saved 3 bytes with some help from @Arnauld.


Retina, 68% 72.8% (old) 74.8% 77.5% (new test battery)

i`^h(a[iy]|eya?|i(h?i|ya|)|ello)[ ,]+

T`l`L`^.

Try it online! Edit: Gained 4.8% (old) 2.7% (new) coverage with help from @MartinEnder's tips.


Python 2 - 18
max(d,key=d.count)

Since your python answer doesn't seem to print, I expect this is what you want.
Add 6 bytes for print  normally.


Size Does Matter (at least referring to bottles)

Python 2, 61 60 59 bytes

lambda n:[a*(1+.03*n)**i*75for a in 4,8for i in range(n/2)]

Try it online!

-1 byte, thanks to Joseph Sible


Javascript ES6, 398 bytes
By far the longest golf I have ever done, I'm sure this can be improved but my brain doesn't recognize anything other than chicken at this point.
(a,b)=>{for(c='chicken',s=[j=0,b,...A=a.split`
`.map(m=>m.split(c).length-1)],i=A.length+2;j<A.length;([_=>s[++i]=c,_=>s[--i]=s[i]+s[i+1],_=>s[--i]=s[i]-s[i+1],_=>s[--i]=s[i]*s[i+1],_=>s[--i]=s[i]==s[i+1],_=>s[i]=s[2+j++]?b[s[i]]:s[s[i]],_=>s[s[i--]]=s[i--],_=>j+=s[--i]?s[--i+2]:0,_=>s[i]=String.fromCharCode(s[i])][s[j+2]-1]||(_=>s[++i]=s[j+1]-10))(j++));return /[^chicken \n]\w/g.test(a)?0:s[i]}

I will edit the explanation in when my brain starts functioning again. Here's a slightly ungolfed version for now.
Outputs a falsey value (0) for everything which isn't chicken
(a,b)=>{
    for(c='chicken',s=[j=0,b,...A=a.split`
    `.map(m=>m.split(c).length-1)],i=A.length+2; // loop init
    j<A.length; // loop condition
    ( // everything else
        [
            _=>s[++i]=c,
            _=>s[--i]=s[i]+s[i+1],
            _=>s[--i]=s[i]-s[i+1],
            _=>s[--i]=s[i]*s[i+1],
            _=>s[--i]=s[i]==s[i+1],
            _=>s[i]=s[2+j++]?b[s[i]]:s[s[i]],
            _=>s[s[i--]]=s[i--],
            _=>j+=s[--i]?s[--i+2]:0,
            _=>s[i]=String.fromCharCode(s[i])
        ][s[j+2]-1]
        ||(_=>s[++i]=s[j+1]-10)
    )(j++)
);
return /[^chicken \n]\w/g.test(a)?0:s[i]}

Try it here

f=
  (a,b)=>{for(c='chicken',s=[j=0,b,...A=a.split`
`.map(m=>m.split(c).length-1)],i=A.length+2;j<A.length;([_=>s[++i]=c,_=>s[--i]=s[i]+s[i+1],_=>s[--i]=s[i]-s[i+1],_=>s[--i]=s[i]*s[i+1],_=>s[--i]=s[i]==s[i+1],_=>s[i]=s[2+j++]?b[s[i]]:s[s[i]],_=>s[s[i--]]=s[i--],_=>j+=s[--i]?s[--i+2]:0,_=>s[i]=String.fromCharCode(s[i])][s[j+2]-1]||(_=>s[++i]=s[j+1]-10))(j++));return /[^chicken \n]\w/g.test(a)?0:s[i]}

i.innerHTML = f(`chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken chicken
chicken chicken chicken chicken chicken chicken
`, 'Hello world!')
<pre id=i>


Retina, 30 27 bytes

!`(?<=^\1 .*[?&](.*)=)[^&]+

This is a full program that expects the key and the URL to be space-separated on STDIN, e.g.

action http://sub.example.com/some/dir/file.php?action=delete&file=test.foo&strict=true

This is essentially just a (.NET-flavoured) regex, which matches the correct value by checking that the preceding key is equal to the first string in the input (using a backreference). The only thing that's a bit odd about the regex is that .NET matches lookbehinds from right to left, which is why the "backreference" actually references a group that appears later in the pattern. The !` instructs Retina to print the actual match (if there is one) instead of the number of matches.

For those who don't regex, here is an annotated version. Read the lookbehind from the bottom up, because that's how it's processed:

(?<=        # A lookbehind. Everything we match in here will not be returned as part of
            # actual match. Start reading this from the corresponding parenthesis.
  ^         # Ensure we're at the beginning of the input, so that we've checked
            # against the entire input key.
  \1        # Backreference to the key to check that it's the one we've asked for.
  [ ]       # Match a space.
  .*        # Consume the rest of the URL.
  [?&]      # Match a ? or a & to ensure we've actually captured the entire key.
  (         # End of group 1.
    .+      # Match the key.
  )         # Capturing group 1. Use this to keep track of the key.
  =         # Make sure we start right after a '='
)           # Start reading the lookbehind here.
[^&]+       # Match the value, i.e. as many non-& characters as possible.


APL 19

≢¨∪/⌈\(⍉⍪⌽⍪⊖∘⌽∘⍉⍪⊖)

(golfed a bit more after ngn's suggestion, thanks)

Explanation:

(⍉⍪⌽⍪⊖∘⌽∘⍉⍪⊖)  rotates matrix 4 times appending results
⌈\ gets maximums for each row up to current column (example: 4 2 3 5 1 gives 4 4 4 5 5)
≢¨∪/ counts unique elements for each row

Try it on tryapl.org


CJam, 22 - 15 = 7
l~_mc\ms@me:X*\X*'+@'i

Try it online here
Takes input in the form of a b where a is the real component and b is the complex.
For ex. 2i is
0 2

gives
-0.4161468365471424+0.9092974268256817i


Jelly, 16 + 16 + 1² = 33

A107083

⁵*+31ÆḍÆNB>/
1Ç#

Try it online!

A221860

⁵*+31ÆạÆNB>/
1Ç#

Try it online!

How it works

1Ç#           Main link. Argument: n

1             Set the return value to 1.
 Ç#           Call the helper link with arguments k, k + 1, k + 2, ... until n of
              them return a truthy value. Return the array of n matches.

⁵*+31ÆḍÆNB>/  Helper link. Argument: k

⁵*            Yield 10**k.
  +31         Yield 10**k + 31.
     Æḍ       Count the proper divisors of 10**k + 31.
              This yields c = 1 if 10**k + 31 is prime, an integer c > 1 otherwise.
       ÆN     Yield the c-th prime.
              This yields q = 2 if 10**k + 31 is prime, a prime q > 2 otherwise.
         B    Binary; yield the array of q's digits in base 2.
          >/  Reduce by "greater than".
              This yields 1 if and only if the binary digits match the regex /10*/,
              i.e., iff q is a power of 2, i.e., iff 10**k + 31 is prime.

⁵*+31ÆạÆNB>/  Helper link. Argument: k

     Æ        Unrecognized token.
              The token, as well as all links to its left, are ignored.
       ÆN     Yield p, the k-th prime.
      ạ       Take the absolute difference of k and p, i.e., p - k.
         B    Binary; yield the array of (p - k)'s digits in base 2.
          >/  Reduce by "greater than".
              This yields 1 if and only if the binary digits match the regex /10*/,
              i.e., iff p - k is a power of 2.


Charcoal, 16 10 9 bytes

ＦＮ«↖Ｉθ→‖Ｔ

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


Husk, 11 bytes

!uΣz:NCNmΠN

Try it online! Or showing the stats for the first 100 n in the first 5000 terms

Explanation

        mΠ     Map factorial over
          N    the Natural numbers
      CN       Cut into lists of lengths corresponding to the natural numbers
   z:N         ZipWith append the natural numbers and ^
  Σ            Concatenate into one list
 u             Remove duplicates
!              Index

Proof (Without the u)

For triangle numbers : f(½n*(n+1))=n

Otherwise : f(n)=k! for some k.

As the density of triangular numbers is zero, this has the same probability as the sequence of factorials: 1


ASCII art uncompression from a base-n number

05AB1E, 7 6 bytes
gв¹sèJ

Since it was inspired by an 05AB1E answer, an answer given in 05AB1E seems fitting. :)
-1 byte thanks to @Emigna by removing the foreach and doing this implicitly.
Try it online or verify all test cases.
Explanation:

g         # `l`: Take the length of the first (string) input
 в        # And then take the second input in base `l`
          # For each digit `y` of this base-converted number:
  ¹sè     #  Push the `y`'th character of the first input
     J    # Join everything together (and output implicitly)


PowerShell v2+, 10 bytes

for(){1>1}

Simply loops infinitely with an empty for loop. Each iteration, we output the integer 1 (implicitly converted to a string) with the > redirect operator, which overwrites the file named 1 in the local directory.


Japt, 41 37 35 34 bytes

I finally have a chance to put ¾ to good use! :-)

55*2pU¬®-1¾ª"C#D EF G A B"bZ /C} x

Try it online!

How it works

          // Implicit: U = input string, C = 12
U¬®    }  // Take U, split into chars, and map each item Z by this function:
-1¾       //  Subtract 1.75 from Z. This produces NaN for non-digits.
ª"..."bZ  //  If the result is falsy (NaN), instead return the index of Z in this string.
          //  C produces 0, D -> 2, E -> 4, F -> 5, G -> 7, A -> 9, B -> 11.
          //  # -> 1, and b -> -1, so we don't need to calculate them separately.
/C        //  Divide the index by 12.
x         // Sum.
2p        // Take 2 to the power of the result.
55*       // Multiply by 55.

Test cases

All the valid test cases come through fine. It's the invalid ones where it gets weird...

input --> output       (program's reasoning)
A0  --> 27.5           (Yep, I can do that for you!)
C4  --> 261.625565...  (Yep, I can do that for you!)
F#3 --> 184.997211...  (Yep, I can do that for you!)
Bb6 --> 1864.6550...   (Yep, I can do that for you!)
A#6 --> 1864.6550...   (Yep, I can do that for you!)
A4  --> 440            (Yep, I can do that for you!)
D9  --> 9397.27257...  (Who says that's too high?)
G0  --> 24.49971...    (I've heard that note before.)
Fb5 --> 659.25511...   (Wait, Fb isn't supposed to be a note?)
E   --> 69.295657...   (I'm gonna guess that the missing octave is 1¾.)
b2  --> 61.735412...   (I assume that b means Cb...)
H#4 --> 261.625565...  (H# is C!)


Husk, 8 6 bytes
←VE¡Ẋ-

Try it online!
-2 bytes from Leo.
Explanation
←VE¡Ẋ- Input: list of P(x)
   ¡Ẋ- repeatedly take deltas and put in infinite list
 V     First index where
  E    all elements are equal
←      decrement


Scratch 3.0, 9 blocks/76 bytes

As SB Syntax:
define
set[N v]to(1
repeat until<(N)=(0
set[N v]to(pick random(0)to(99
say(N

Try it on Scratch
It just wouldn't be right if I didn't golf this in scratch. This is a function that achieves the desired result
Explained
define                             // Create a function with no name (not a lambda)
set[N v]to(1                       // Initalise the variable we will use to generate random numbers with
                                   // If we didn't set it to 1, the next loop wouldn't start, as it would see that N = 0.
repeat until<(N)=(0                // Pretty self-explanatory
set[N v]to(pick random(0)to(99     // Also pretty self-explanatory. But putting this here means we don't have to include two calls to this block: we've essentially created a post-test loop instead of a pre-test loop
say(N                              // Output the randomly generated number and repeat


05AB1E, 3 bytes

FÒO

Try it online!

Explanations:

FÒO
F    Loops <input> times + 1
 Ò   List of prime factors w/ duplicates
  O  Total sum of the list
     -- implicit output


Husk, 8 bytes
ḟ>1M<¹Π↑

Try it online! (Missing the testcase for perfect numbers because it was too slow, and the one for semiprimes because implementing the list of semiprimes is a challenge itself)
Takes as input S and n, where S is an infinite list.
Explanation
ḟ>1M<¹Π↑
       ↑     Take the first n elements from S
      Π       and get their product
   M ¹       For each element x in S
    <         subtract the product if it is smaller than x, return 0 if it is bigger
ḟ            Find the first element in this list
 >1           that is greater than 1


JavaScript (ES7),  80 74 66  65 bytes

(a,b,c)=>(s=a+b+c,(p=a*b*c/s)*p/4*(s/=2)/(s-a)/(s-b)/(s-c)-p)**.5

Try it online!
How?
This is derived from:

The semiperimeter \$s\$ of the triangle:
$$s=\frac{a+b+c}{2}$$

The circumradius \$R\$ of the triangle:
$$R=\frac{abc}{4\sqrt{s(s-a)(s-b)(s-c)}}$$

The product of the inradius \$r\$ and the circumradius:
$$rR=\frac{abc}{2(a+b+c)}=\frac{abc}{4s}$$

Euler's theorem:
$$d=\sqrt{R(R-2r)}=\sqrt{R^2-2rR}=\sqrt{R^2-\frac{abc}{2s}}$$


C 529 bytes

#define M m[y][x]
char**m,*l,i;main(Y,X){for(;scanf("%ms",&l)>0;)(m=realloc(m,Y*8))[Y-1]=l,X=puts(m[Y++-1])-2;puts("");int s(x,y,c,d){(x<0|y<0|y/Y)?:({if(M^'R'&&M^'Y')if(M^'B'||c^2&&!((y&&m[y-1][x]=='Y')|(x&&m[y][x-1]=='Y')|(y<Y-1&&m[y+1][x]=='Y')|(x<X-1&&m[y][x+1]=='Y'))){x^X?:({M='#';return 1;});c=M^'O'?c:2;M^'U'?:({return s(x+(d<4?d-2:0),y+(d>3?d-5:0),1,d)?({M='#';1;}):0;});if(d^1&&s(x+1,y,c,3)||d^4&&s(x,y+1,c,6)||d^6&&s(x,y-1,c,4)||d^3&&s(x-1,y,c,1)){M='#';return 1;}}});return 0;}s(0,--Y/2,0,3);for(;i<Y;)puts(m[i++]);}

We approach the puzzle by stepping first to the right, provided we are not blocked, then trying up, then down and finally back to the left.  The search is recursive and once we identify a successful path, we mark the spaces in our matrix and return.

Try it Online

Ungolfed

#include <stdio.h>
#include <malloc.h>
char**m,*l,i;
main(Y,X) {
  for(Y=1;scanf("%ms",&l)>0;Y++)
      m=realloc(m,Y*8),
      m[Y-1]=l,
      X=puts(m[Y-1])-2;
  puts("");
  int step(x,y,c,d,i){
    if(x<0||y<0||y>=Y)return 0;
      if(m[y][x]=='R'||m[y][x]=='Y')return 0;
      if(m[y][x]=='B'&&(c==2||(y&&m[y-1][x]=='Y')||(x&&m[y][x-1]=='Y')
               ||(y<Y-1&&m[y+1][x]=='Y')||(x<X-1&&m[y][x+1]=='Y')))return 0;
      if(x==X){m[y][x]='#';return 1;}
      if(m[y][x]=='O')c=2;
      if(m[y][x]=='U')return step(x+(d<4?d-2:0),y+(d>3?d-5:0),1,d,i+1)?({m[y][x]='#';1;}):0;
      else if((d!=1&&step(x+1,y,c,3,i+1)) ||
    (d!=4&&step(x,y+1,c,6,i+1)) || (d!=6&&step(x,y-1,c,4,i+1)) ||
    (d!=3&&step(x-1,y,c,1,i+1))) {m[y][x]='#';return 1;}
      return 0;
  }
  step(0,--Y/2,0,3,0);
  for(;i<Y;)puts(m[i++]);
}

Example Output 1

PYYOPPPP
YRGGRYRG
PGPBYPUR
PYRBOYOG
OBPGYYPP
PRGPOYPO
YPYOUGPP
YGROBRYY
RGRYBBOG

PYY#####
YR##RYRG
###BYPUR
#YRBOYOG
#BPGYYPP
PRGPOYPO
YPYOUGPP
YGROBRYY
RGRYBBOG

Example Output 2

PBYRYPGP
OBRGOOBG
PGPGUROO
PUGORBUG
PUPUUURO
BGGUYPRG
GBOPGGRG
PUPUBUYB
GYOPRPOG

PBYRYPGP
OBRGOOBG
PGPGUROO
PUGORBUG
###UUURO
BG#UYPRG
GB####RG
PUPUB#YB
GYOPR###

Example Output 3

RRRR
RPPR
PUOR
RPBP

RRRR
R##R
###R
R###


Combine loops if possible

In non-trivial computations you'll often find yourself using several loops to process data:

+`stage1
+`stage2
+`stage3

So this runs stage1 until the output converges, then stage2 until the output converges and then stage3 until the output converges.

However, it's always worth examining the stages in detail. Sometimes it's possible to run the loop in an interleaved fashion as stage1, stage2, stage3, stage1, stage2, stage3, ... instead (this depends a lot on what the stages actually do, but sometimes they make completely orthogonal changes or work well as a pipeline). In this case you can save bytes by wrapping them in a single loop:

{`stage1
stage2
}`stage3

If stage1 is the first stage or stage3 is the last stage of the program you can then even omit on of those parentheses as well (which means this can already save bytes for a loop of two stages).

A recent use of this technique can be seen in this answer.


Fortran IV:

2=0

After this every constant 2 in the program is zero. Trust me, I have done this (ok, 25 years ago)


The ternary conditional operator ?: can often be used as a stand in for simple if--else statements at considerable savings.

It is of special value in that it can be used to select alternate lvalues as in

#include <iostream>
#include <cstdlib>
int main(int c, char**v){
  int o=0,e=0,u;
  while(--c) ((u=atoi(v[c]))%2?o:e)+=u;
  std::cout << "Sum of odds " << o <<std::endl
            << "Sum of evens " << e <<std::endl;
}


Ruby 221

->a{l=a.join(?o*(5-w=a[0].size))
s=?o*25
q=(0..25-l.size).select{|i|i/5==(i+w-1)/5}.map{|i|(?o*i+l+s)}
(h=q[0].size.times.map{|i|q.count{|p|p[i]<?o}}
s[c=h.index(h.max)]=?X
q.reject!{|p|p[c]<?o})while q!=[]
s.scan /.{5}/}

Input and Output

This is a Ruby function that takes one parameter representing the animal and returns the solution, both being represented as string arrays.

For example, the Hippo is represented as:

['XoX',
 'ooo',
 'XoX']

and its solution is:

['ooooo',
 'oXXoo',
 'oXXoo',
 'ooooo',
 'ooooo']

Test

Here's a working version. Feel free to experiment with it and enter more animals as parameters.

Algorithm

I found this problem very interesting and I experimented to solve it in different ways, including brute force, which is less feasible, but possible for the given inputs (it would be terribly inefficient for the input ['X'] though).

The algorithm I found to be the most efficient is the following:

Compute all possible positions for the animal on the 5x5 board
Given the existing positions, compute a map of frequencies for each of the 25 cells
Take one of the cells that contain the max number of "hits" and make it part of the solution. Exclude all positions that are "hit" in that particular cell.
Repeat steps 2-3 until there are no positions left.

I don't have a proof of optimality for this algorithm, but it tested most animals present on the wiki page and it returned optimal solutions for all.

Note that for some animals the solutions are not identical to the ones presented in the wiki, but involve the same number of blocks.

For example, the Wooly Rhino page presents this solution:

ooooo
ooooo
oXXXo
ooooo
ooooo

and the algorithm returns this one:

ooooo
oooXo
ooXXo
ooooo
ooooo

which is also correct and optimal (3 blocks).

Here's the (slightly more) readable version of the program:

SIZE = 5

# return all possible placements for the animal on a 5x5 board
def get_placements(animal)
  # represent the 5x5 board and the animal as linear arrays
  linear_animal = animal.join(?o*(SIZE - animal[0].size))
  d = SIZE*SIZE
  (0..d-linear_animal.size)
    .select{|i| i/5 == (i+animal[0].size-1)/5} # to avoid wrap-around positions
    .map { |i|
      (?o*i + linear_animal + ?o*d)[0...d]
    }
end

# given a set of possible placements,
# return a map of frequencies for every cell
def heatmap(placements)
  placements[0].size.times.map do |i|
    placements.count {|p|p[i] < ?o}
  end
end

# given an animal, return the solution as an array of 5 5-character strings
def solve(animal)
  placements = get_placements animal
  solution = []

  while placements.any?
    h = heatmap(placements)

    solution << chosen = h.index(h.max)

    placements = placements.reject {|pl| pl[chosen] < ?o }
  end

  (0...25).map{|i| solution.include?(i) ? ?X : ?o }.join.scan /.{5}/
end


PowerShell, 73 bytes

' '*48;46..0|%{" "*$_+-join[char[]](($x=79-$_)..($y=$x+$j++)+(++$y)..$x)}

Try it online!

Outputs the first whitespace-only line, then loops from 46 to 0. Each iteration, outputs the corresponding number of spaces and then a -joined together char-array of the appropriate symbols, via some calculations.


Can you win with two more moves at Three Men's Morris?

C# - 739 663 bytes

Complete program, reads input from argv, and appears to work. Run it like

ThreeMill 1 2 1 1 2 0 0 0 2

If this method of input is unacceptable, I'll be glad to change it (never like using argv).

using System;using System.Linq;class P{static void Main(string[]A){var I=new[]{0,3,6,1,4,7,2,5,8};Func<string[],string>J=S=>S[0]+S[1]+S[2]+" "+S[3]+S[4]+S[5]+" "+S[6]+S[7]+S[8]+" ";Func<string[],string,int>W=(B,p)=>(J(B)+J(I.Select(i=>B[i]).ToArray())).Contains(p+p+p)?1:0;Func<string[],string,string[][]>V=(B,p)=>I.SelectMany(a=>I.Where(b=>a!=b&B[a]==p&B[b]=="0"&(a==4|b==4|a-b==3|b-a==3|((a-b==1|b-a==1)&a/3==b/3))).Select(b=>{var N=(string[])B.Clone();N[b]=p;N[a]="0";return N;})).DefaultIfEmpty(B).ToArray();int h,G;Console.WriteLine(":"+"(|))"[V(A,"1").Max(z=>((h=0)<(G=V(z,"2").Sum(j=>V(j,"1").Max(q=>W(q,"1")-W(q,"2"))+h++*0))?1:0)+(h>G?W(z,"1")*2:2))]);}}

I was disinclined to post this yesterday, because I've not been able to golf it down much (not had all that much time, and I might be out of practice), but since there hasn't been a response yet, I'll post it anyway, I certainly don't expect the bounty, I'd rather it went to someone who's put a bit more effort into theirs before posting!

Edit: replaced all the bools with ints, which meant I could make better use of Linq, and managed to collapse both foreach loops, giving big savings. I am slightly amazed that the h counter works... ++ is such a subtle utility.

The program is very simple, it just explores every possible set of moves (stores board state in a string[]). It iterates over all of our possible moves (the boards that result thereof), and counts the number of responses by our opponent that we can successful beat (G) (i.e. those that we win, and he doesn't). It also counts the number of possible responses (h). If we can win any, then it's a possible, and we add 1 to the sum, if we can win them all, it's a definite, and we add 2 to the sum. The maximum some is therefore our best possible outcome, and we index into the string "(|))" to return the appropriate face. Note that we need the extra ")" because the sum can be 2 or 3 if it's a definite (it's possible that we don't appear to be able to beat any responses having already won on the first go, so the possible check is a tad misleading).

The program checks for a victory by producing a string from the board, that is space-separated rows and columns, and just looks for a string of 3 of the player's character in this string (e.g. "201 201 021 220 002 111 " is a win for us)

using System;
using System.Linq; // all important

class P
{
    static void Main(string[]A) // transform to int?
    {
        var I=new[]{0,3,6,1,4,7,2,5,8}; // vertical indexes
        Func<string[],string>J=S=>S[0]+S[1]+S[2]+" "+S[3]+S[4]+S[5]+" "+S[6]+S[7]+S[8]+" "; // joins the strings up, so that there is a space separating each group of three (including at end)
        Func<string[],string,int>W=(B,p)=>(J(B)+J(I.Select(i=>B[i]).ToArray())).Contains(p+p+p)?1:0; // checks if a particular player wins
        Func<string[],string,string[][]>V=(B,p)=>I.SelectMany(a=>I // for each imagineable move
            .Where(b=>a!=b&B[a]==p&B[b]=="0"&(a==4|b==4|a-b==3|b-a==3|((a-b==1|b-a==1)&a/3==b/3))) // where it's legal
            .Select(b=>{var N=(string[])B.Clone();N[b]=p;N[a]="0";return N;}) // select the resulting board
        ).DefaultIfEmpty(B) // allow not-moving
        .ToArray();

        int h, // h stores the number of responses the opponent has to each move
        G; // G stores the number of responses by the opponent we can beat

        Console.WriteLine(":"+"(|))"[ // we index into this to decide which smiley
            V(A,"1").Max(z=>
                    ((h=0)<(G=V(z,"2").Sum(j=>V(j,"1").Max(q=>W(q,"1")-W(q,"2"))+h++*0))?1:0) // if there is atleast 1 reponse by the opponent we can beat, we can possibly win
                    +(h>G?W(z,"1")*2:2) // if there are moves which we can't win, then if we have already won (one-move), else, we can definitely win
                   ) // sum is therefore 0 if impossible, 1 if possible, >2 (no more than 3) if definite
            ]);

    }
}

Here is my test script:

ThreeMill 2 1 0 2 1 2 0 0 1
ThreeMill 2 1 0 0 1 0 2 2 1
ThreeMill 1 0 1 1 0 2 0 2 2
ThreeMill 1 2 2 2 1 0 0 0 1

ThreeMill 1 0 1 1 2 2 2 0 0
ThreeMill 1 0 1 1 2 0 2 0 2
ThreeMill 1 2 2 0 0 1 2 1 0

ThreeMill 1 0 0 1 2 2 2 0 1
ThreeMill 1 2 1 1 2 0 0 0 2
ThreeMill 1 0 1 2 0 2 1 0 2

Which outputs

:)
:)
:)
:)
:|
:|
:|
:(
:|
:)


Python 3, 76 bytes

F=lambda x:x<2or x*F(x-1)
f=lambda x,n=1:x<2or n*(F(x)>F(x-n)**2)or f(x,n+1)

Try it online!

Relies on the fact that for eating \$n\$ candies to still win and the total number of candies being \$x\$, \$\frac{x!}{(x-n)!}>(x-n)!\$ must be true, which means \$x!>((x-n)!)^2\$.

-1 from Skidsdev

-3 -6 from BMO

-3 from Sparr

+6 to fix x = 1