SOGL V0.12, 75 bytes
l√u²m√lH»{ā;l⁾:A∫Ba{bIwFIWhFbž;FIbI@ž}};}¹K⁴{ē2\⌡±e{@Κ};⁴┼┼};0E{ē2\⌡№:h++}╚

Try it Here!
This expects the input on the stack, so for ease-of-use I added , at the start. That can cause issues if the input contains only numbers so here
is a a test-suite for that.
70 bytes √lH»{ā;l⁾:A∫Ba{bIwFIWhFbž;FIbI@ž}};}¹K⁴{ē2\⌡±e{@Κ};⁴┼┼};0E{ē2\⌡№:h++}╚ works too, but as I only now implemented √ on strings and the documentation didn't mention that it would floor the length I won't count it.
Explanation:
creating a square from the input

l       get the length of the input
 √      get its square root
  u     floor that
   ²    square it
    m   mold the input to that length
     √  convert it to a square

creating the unfoldings of the square - the idea is to cut out the inner squares to a new array

lH»{                              } (length-1)//2 times do
    ā;                                push an empty array below ToS
      l⁾                              push ToS.length - 2 (ToS here is the square or the previous unfolding)
        :A                            save a copy of that in the variable A
          ∫B                    }     repeat that amount of times, saving iteration on B - cutting the inner square to the empty array
            a{                 }        variable A times do
              bIw                         get the b+1th row of the previous unfolding
                 FIW                      get the (current loops iteration + 1)th character of that
                    h                     swap the 2 items below ToS - so the stack now is [..., prevUnfolding, newArray, character]
                     Fbž                  at [current loops iteration; b] insert that character in the array
                        ;                 swap the top 2 items - the stack now is [..., newArray, prevUnfolding]
                         FIbI@ž           at [current loops iteration+1; b+1] insert a space
                                 ;    get the now not empty array ontop of the stack

add the horizontal unfoldings

¹                    wrap the stack in an array
 K                   push the 1st item of that, which will function as the canvas
  ⁴{              }  iterate over a copy of the remaining items
    ē2\⌡               repeat (e++ divides by 2) times (default for the variable E is the input, which defaults to 0)
        ±                reverse the array horizontally
         e{  }         repeat e times
           @Κ            add a space before ToS
              ;⁴┼┼     add that horizontally before and after the canvas

add the veertical unfoldings

;                get the copy of the foldings above the canvas
 0E              reset the variable E to 0
   {         }   iterate the copy of the foldings
    ē2\⌡           repeat (e++ divides by 2) times (default for the variable E is the input, which defaults to 0)
        №            reverse the array vertically
         :h++      add that vertically before and after the canvas
              ╚  center the canvas vertically


Vim, 44 42 bytes

qqy$P0xjf1"_xP{@qq@q:s/0/ /g^M:s/,/^V^M/g^M{D

Saved 2 bytes thanks to @DjMcMoylex!

Here, the ^M is a literal newline, and the ^V is CTRL-V

Takes the input in this format:

PPCG
00100,01010,10001,01010,00100

Disclaimer: If the string is longer than ~40 chars long, your computer might run out of ram.

Explanation:

qq             @qq@q                            # Start recording a recursive macro.
  y$P0x                                         # Duplicate the string and cut out the first character
       jf1"_xP{                                 # Find the first 1, and replace it with the cut character from the string.
                                                # Now we have replaced all the 1's with their respective character, but we still have the array in the original format, and we have the string massivly duplicated at the first line, so we need to clean it up:
                    :s/0/ /g^M                  # Replace all 0's with a space
                              :s/,/^V^M/g^M     # Replace all ,'s with a newline. The ^V acts like a backslash, it escapes the newline so that the command isn't run too soon
                                           {D   # Delete the first line

Here's a gif of me "running" the "program":


Japt, 13 bytes

n36 Ä s36 ù0A

Try it online! and Verify test cases

Takes input as a string

Explanation

n36            converts input to base 36
    Ä           +1
      s36       to base 36 string
          ù0A   left-pad with 0 to length 10


Python, 329 chars

import sys
N=[[1]]+[map(int,x.split())for x in sys.stdin]
N[-1][0]=1
n=len(N)
S=[set([i])for i in range(2*n)]
for x in range(n):
 C=S[2*x]
 for y in N[x][1:]:C|=S[2*y+1]
 for x in C:S[x]|=C
V=[0]*(2*n-1)+[1]
for k in range(999):
 for i in range(1,2*n-1):V[i]+=sum((V[j^1]-V[i])/N[j/2][0]for j in S[i])/9./len(S[i])
print 1/V[1]-2

Calculates the resistance by doing a voltage relaxation on the circuit.  First it tacks on a 1 ohm resistor to the start and changes the last resistor from 0 ohm to 1 ohm.  Then it sets the input voltage to 0 and the output voltage to 1 volt.  After simulating current flow through the network, the network resistance is calculated using the voltage drop across the first 1 ohm resistor.

Each resistor is given two numbers, the number for its left terminal and the number for its right terminal.  Resistor r's left terminal is 2*r and its right terminal is 2*r+1.  The input is used to calculate S, the sets of terminals that are connected together.  Each terminal is given a voltage V[t] and a relaxation is done by raising the voltage if current is net flowing into a terminal set and lowering the voltage if current is net flowing out.


Four weights to produce integer scale differences from 0 through 40 pounds

APL 198 * 50% = 99
z←W n
l←⍉(n⍴3)⊤w←0,⍳+/b←3*0,⍳n-1
r←(⍴l)⍴0
:while 0≠+/+/l>1
    r←r+l>1
    l←((l≤1)×l)+1⌽l>1
:end
a←' ',⌽⎕av[97+⍳n]
c←(⍴l)⍴⍳n
b←0,⌽b
z←l≠r
l←z×l
r←z×r
l←1+l×c
r←1+r×c
z←w,'{',a[l],'}','{',a[r],'}','{',b[l],'}','{',b[r],'}'

As we are effectively working in base three the arithmetic is fairly trivial and is complete by the end of the while loop where the arrays l and r are the contents of the left and right scale pans respectively in base three. This takes about 80 characters. The rest is formatting the output which I am sure can be improved.
To run simply type W followed by the number of weights you want to use. Below is a sample output for n=3:
 W 3
 0 {   }{   }{ 0 0 0 }{ 0 0 0 }
 1 {  a}{   }{ 0 0 1 }{ 0 0 0 }
 2 { b }{  a}{ 0 3 0 }{ 0 0 1 }
 3 { b }{   }{ 0 3 0 }{ 0 0 0 }
 4 { ba}{   }{ 0 3 1 }{ 0 0 0 }
 5 {c  }{ ba}{ 9 0 0 }{ 0 3 1 }
 6 {c  }{ b }{ 9 0 0 }{ 0 3 0 }
 7 {c a}{ b }{ 9 0 1 }{ 0 3 0 }
 8 {c  }{  a}{ 9 0 0 }{ 0 0 1 }
 9 {c  }{   }{ 9 0 0 }{ 0 0 0 }
10 {c a}{   }{ 9 0 1 }{ 0 0 0 }
11 {cb }{  a}{ 9 3 0 }{ 0 0 1 }
12 {cb }{   }{ 9 3 0 }{ 0 0 0 }
13 {cba}{   }{ 9 3 1 }{ 0 0 0 }


05AB1E, 54 52 bytes
Thanks to Kevin Cruijssen for -2 bytes!
T"ÿ, 0, 0.
ÿ,
0.
"T.•ý‹¨ΣªßˆTδ}vØ#•.ª'x¡‡žMv=žMyÞ‡}?

Try it online!
Commented:
T                         # push 10
 "ÿ, 0, 0.\nÿ,\n0.\n"     # push string literal "10, 0, 0.\n10,\n0.\n"
  T                       # push 10 again
   .•ý‹¨ΣªßˆTδ}vØ#•       # push compressed string "priletela xmuha na zid"
    .ª                    # sentence case => "Priletela xmuha na zid"
      ‛x¡                 # split on 'x'  => ["Priletela ", "muha na zid"]
         ‡                # replace every digit of 10 with the corresponding list entry in the string literal
                          # this is the first verse
          žM              # push the vowels "aeiou"
            v      }      # for y in vowels:
             =            #   print the last verse without removing it from the stack
              žM          #   push the vowels
                yÞ        #   the infinite list of the vowel y
                  ‡       #   replace every vowel with y
                    ?     # print the last verse without a trailing newline

more obfuscated and a lot slower 52-byter:
•nöðrb•ØTz… ,
«ÅвJT.•ý‹¨ΣªßˆTδ}vØ#•.ª'x¡‡žMv=žMyÞ‡}?

Don’t try it online!
•nöðrb•              # push compressed integer 211262272027
       Ø             # push the 211262272028th prime 5996494318979 (slow)
        Tz           # push 1/10
          … ,\n      # push string " ,\n"
               «     # concatenate to "0.1 ,\n"
                Åв   # convert the prime into that custom base
                  J  # join from list of chars into a string
                     # this generates the same string as T"ÿ, 0, 0.\nÿ,\n0.\n" above


Mathematica, 16 bytes

CarmichaelLambda

Well...


Reorder a Master List Based on a Reordered Subset

Retina 0.8.2, 51 bytes

+`(\b(\w+),(\w+)\b.*¶.*\b)\3,(.*\b\2\b)
$1$4,$3
1A`

Try it online! Takes input as a comma-separated list of subwords on the first line and a comma-separated master list of words on the second line. Explanation:

(\b(\w+),(\w+)\b.*¶.*\b)\3,(.*\b\2\b)

Find two adjacent subwords where the second word precedes the first on the master list.

$1$4,$3

Move the second word to appear after the first word in the master list.

+`

Repeat until no words appear out of order.

1A`

Delete the subwords.


Display the exponent from a binary floating point number as a decimal value

Haskell, 33 bytes

foldl1(\x y->x*2+y-1).take 8.tail

Try it online!
Input is a list of integers 0 or 1.
It's slightly shorter to foldl1 by x*2+y-1 than to subtract 127 at the end. This works because
  foldl1 (\x y->x*2+y-1) [a,b,c,d,e,f,g,h]
= ((((((a*2+b-1)*2+c-1)*2+d-1)*2+e-1)*2+f-1)*2+g-1)*2+h-1
= a*128 + b*64-64 + c*32-32 + d*16-16 + e*8-8 + f*4-4 + g*2-2 + h-1
= 128a + 64b + 32c + 16d + 8e + 4f + 2g + h - 127
= fromBinary[a,b,c,d,e,f,g,h]-127


Create all arrays of non-negative integers of length N with sum of parts equal to T

JavaScript (V8),  71 69  67 bytes
Saved 1 byte thanks to @l4m2
Expects (n, t) and prints all possible arrays.

f=(n,t,a=[],v=0)=>n?f(n-1,t,[...a,v])|t&&f(n,t-1,a,v+1):t||print(a)

Try it online!
Commented
f = (             // f is a recursive function taking:
  n,              //   n   = expected number of entries
  t,              //   t   = expected sum
  a = [],         //   a[] = current output array
  v = 0           //   v   = current value to be added to a[]
) =>              //
  n ?             // if there's at least one more entry to add:
    f(            //   do a first recursive call:
      n - 1,      //     decrement n
      t,          //     pass t unchanged
      [...a, v]   //     append v to a[]
    ) | t         //   end of recursive call; yield t
    &&            //   if the above is truthy ...
    f(            //   ... do a 2nd recursive call:
      n,          //     pass n unchanged
      t - 1,      //     decrement t
      a,          //     pass a[] unchanged
      v + 1       //     increment v
    )             //   end of recursive call
  :               // else:
    t || print(a) //   print a[] if t = 0


Write a program that uses all printable non-alphanumeric ASCII symbols

Perl, 32 chars

no hiding symbols in comments, string literals, or regular expressions. uses all symbols precisely once.

$`<@"^[(\{_},)]/+-~%'?&|:!*.=>;#

Description

i have tried to indicate operator precedence with indentation: the right-most expressions are evaluated before those to their left

        $`            # scalar variable $ named `
      <               # numeric less-than inequality <
        @"            # array variable @ named "
                      #   (array evaluated in scalar context)
    ^                 # bitwise XOR ^
        [(\{_},)]     # array reference []
                      #   containing array ()
                      #     containing reference \
                      #       to anonymous hash reference {}
                      #         with one key "_"
                      #           and no value (nothing following comma ,)
                      #             (reference evaluated in scalar context)
      /               # numeric division /
        +-~%'         # unary addition +
                      #   and unary negation -
                      #     and bitwise complement ~
                      #       on hash variable % named '
                      #         (hash evaluated in scalar context)
  ?                   # ternary conditional operator ?:
    &|                # code reference variable & named |
  :                   # ternary conditional operator ?:
    ! *.              # logical negation !
                      #   on typeglob variable * named .
                      #     (typeglob evaluated in scalar context)
  =>                  # fat comma => for compound expression
                      #   (evaluates LHS as string, RHS is empty)
;                     # end of expression ;
#                     # start of comment #


Befunge '98, 91 characters

Was formerly 104, then 101. Saved another 10 chars by moving the "Fi...E!" sentence to output position 89 using 'E' (instead of ' ' at 55), and moving the actual code into the space this opened up, with a slightly improved print loop.

"!ENIUQ os si iccanobiF"f6*>:;#-1,g0;#:_ "}\"f:4++"{'{",,0$,,,,@"}4{ naht erom si 30" b >0a

produces the following output (fibonacci positions marked):

a0> b "03 is more than {4}"@,,,,$0,,"{'{"++4:f"\}" _:#;0g,1-#;:>*6f"Fibonacci is so QUINE!{'{"\}
--- -  -    -       -            -                    -                                 -
|   |               |                                                                   |
 |     |                         |
  |         |                                         |

This snippet outputs all of itself, except for the first character, in reverse order. Then it appends {'{"\} to the output, yielding a total of 96 chars including 98.9% of the code.

Positions 1, 5, 21 and 89 are each occupied by 'a', 'b' or 'E'.
Positions 2, 8 and 34 each have a '0'.
In positions 3, 13 and 55, we find '>', ' ' and ';', all symbols according to the definition given by Plarsen.

There are 3 completely unused cells, and all of b >0a is utterly useless code, only there for the aesthetics of a0> b  0. There may (still) be room for optimization.

Since String mode means pushing a reverse string to the stack and then pop/print-ing it forward, writing them in reverse order is totally natural in Befunge.

Breakdown

f6* calculates 90, the index of the last character in the source. It's 15 * 6.
>: means 'head east and duplicate the top of stack value'. Stack [ ... 90 90 ].
;...; skips over the code in between.
#:_ skips the :, then pops TOS and heads back west if not 0. Stack [ ... 'F' 90].
Now RTL: ,g0;#: duplicates TOS, skips entry to the ; portal, gets the character at (TOS, 0) and prints it.
Still RTL: :;#-1 decrements TOS, skips ; and duplicates TOS. Execution continues at step 2.) Stack [ ... 89 89 ]
Once the TOS counter is down to 0, _ lets us through.
We push the third required string , whereby we have to calculate the '"' because there is no escaping in Befunge. f:4++ is 15 + 15 + 4. The commas write it back out from the stack. I had to insert 0$ there (push 0 then pop/discard) to meet the requirement.
@ terminates.


Perl, 190 180 154 133 128 117 bytes

includes +1 for -p

use POSIX;$m=1E4;for$q(80,100,120){($m,@z)=($p,$n,ceil$_/$n)if$m>($p=(150,200,220)[$x++]*($n=ceil$_/$q))}$_="@z $m"

Commented:

use POSIX;                                  # for ceil()
$m = 1E4;                                   # init min price to 10k
for $q (80,100,120) {                       # iterate widths
    ($m,@z) = ($p,$n, ceil $_/$n)           # update min, output
    if $m > (                               #
       $p = (150,200,220)[$x++]             # grab price
          * ( $n = ceil $_/$q )             # times nr of doors needed
    )
}
$_="@z $m"

Save 11 bytes by inlining and splitting hash to two arrays
Save 5 bytes by using -p (thanks to @dev-null)
Save 18 bytes by using POSIX::ceil and 3 more by using list syntax for hash (thanks to @msh210)


Mathematica, 33 bytes

-Min@Accumulate[2#2-1&@@@Sort@#]&

I had to read the problem statement better to realize that there's a much simpler algorithm that doesn't require the license plate information.

Unnamed function returning an integer; the input format is a list of ordered triples in the form {time, 0|1, license plate}. We start by Sorting, which makes the list chronological and also breaks time-ties by sorting 0s before 1s; then 2#2-1&@@@ keeps the arrival/departure information and forgets the rest, and also converts 0s to -1s.

Accumulate calculates the running totals of that list; the result is a list of the negatives of the numbers of cars in the parking lot after every arrival/departure. Then Min picks the smallest (most negative) of these and the negative sign is stripped.

Mathematica, 56 bytes

Max[<|#|>~Count~0&/@FoldList[List,{},#3->#2&@@@Sort@#]]&

The original submission (the first several comments refer to this submission). Unnamed function returning an integer; the input format is a list of ordered triples in the form {time, 0|1, license plate}.

The reason we choose to put the time entry first and the in/out entry second is so that Sort@# sorts the list chronologically, and records arrivals before departures if they're simultaneous. After that, #3->#2&@@@ returns a list of "rules" of the form license plate -> 0|1, still sorted chronologically.

Then, FoldList[List,{},...] creates a list of all the initial segments of that list of rules. Actually, it really messes up those initial segments; the kth initial segment ends up being a list with one rule at depth 2, one rule at depth 3, ..., and one rule at depth k+1. (FoldList[Append,{},...] would yield the more natural result.) However, <|#|> turns each of these initial segments into an "association", which has two desirable effects: first, it completely flattens the nested-list structure we just created; and second, it forces later rules to override earlier rules, which is exactly what we need here—for any car that has left the parking lot, the record of its initial entry is now completely gone (and similarly for cars that re-enter).

So all that's left to do is to Count how many 0s there are in each of these associations, and take the Max.


Jelly, 7 3 bytes
ḤḢ_

Try it online!
Background
The deltas of (a, b, c, d) are b - a, c - b, and d - c. Cumulatively reducing (a, b - a, c - b, d - c) by subtraction yields a - (b - a) = 2a - b, 2a - b - (c - b) = 2a - c, and 2a - c - (d - c) = 2a - d, so the correct result is (2a - a, 2a - b, 2a - c, 2a - d).
How it works
ḤḢ_  Main link. Argument: A (array)

Ḥ    Unhalve; multiply all integers in A by 2.
 Ḣ   Head; extract first element of 2A.
  _  Subtract the elements of A from the result.


Jelly, 33 32 24 bytes

Zæ%1.»0$+¥\>-‘żZḅ3Ff5,7Ḣ

This prints 5 instead of -1, and 7 instead of 1. Try it online! or verify all test cases.

How it works

Zæ%1.»0$+¥\>-‘żZḅ3Ff5,7Ḣ  Main link. Argument: A (digit list array)

Z                         Zip; group corresponding digits.
 æ%1.                     Map the digits in (-1.5, 1.5].
                          This replaces [1, 2, 3] with [1, -1, 0].
          \               Cumulatively reduce the pairs by doing the following.
     »0$                    Take the maximum of the left value and 0, i.e., replace
                            a -1 with a 0.
        +¥                  Add the modified left value to the right value.
                          This computes the available ammo after each action. An
                          ammo of -1 indicates a cheating attempt.
           >-             Compare the results with -1.
             ‘            Increment. And unilateral cheating attempt is now [1, 2]
                          or [2, 1], where 1 signals the cheater and 2 the winner.
              żZ          Pair each result with the corr., original digits.
                ḅ3        Convert each pair from base 3 to integer.
                          This maps [1, 2] and [2, 1] to 5 and 7.
                  F       Flatten the resulting, nested list.
                   f5,7   Discard all but 5's and 7's.
                       Ḣ  Grab the first element (5 or 7).
                          If the list is empty, this returns 0.


Optimizing edge selection from a list of numbers

k, 48 43 38 bytes

-5 bytes thanks to ngn.

{a@*>*+a:x{(+/x*1+<y*|!#x;y)}/:+!2|-x}

Try it online! It simply tries all possibilities, and chooses the first one with the maximum value. Left/right encoded as 0/1.

{                                    } /functions accepts x
                               +!2|-x  /all possible selections
          { +/x*1+<y*|!#x   }          /calculate the total sum
           (             ;y)           /also record the selection with each sum
         x                   /:        /map over all selections
 a@*>*+a:                              /choose the one with max total sum

This can probably be golfed further.


Python 2, 227 220 214 bytes

lambda y,c:[[choice([["wretch",m,"creature","demon",d,F,"it"],["vile insect",a+m,F,"wretched "+d,a+d]][c>9]),"Frankenstein's "+m][y>1818],0][y<1818]
from random import*
m,d,F,a='monster','devil','fiend',"abhorred "

Try it online!


JavaScript (ES6), 156 137 bytes
Saved 18 bytes thanks to @l4m2
That's quite a lot of map() ...

f=(a,n=1)=>a.map(B=(r,y)=>r.map((_,x)=>a.map(b=q=>q.map(v=>b=b<(d=X*X--+Y*Y)|!v?b:d,X=x)&Y--,Y=y)|v|b<=B||(R=r,C=x,B=b)))|B?f(a,R[C]=++n):a

Try it online!
Commented
f = (a, n = 1) =>               // a = input array; n = seat counter
  a.map(B =                     // initialize B to a non-numeric value
    (r, y) =>                   // for each row r at position y in a[]:
    r.map((_, x) =>             //   for each target seat at position x in r[]:
      a.map(b =                 //     initialize b to a non-numeric value
        q =>                    //     for each row q in a[]:
        q.map(v =>              //       for each reference seat v in q[]:
          b = b < (             //         if b is less than d, defined as
            d = X * X-- + Y * Y //           the square of the Euclidean distance
          ) | !v ?              //           or the reference seat is empty
            b                   //             let b unchanged
          :                     //           else:
            d,                  //             update b to d
          X = x                 //         start with X = x
        ) & Y--,                //       end of q.map(); decrement Y
        Y = y                   //       start with Y = y
      ) |                       //     end of inner a.map()
      b <= B ||                 //     unless b is less than or equal to B,
      (R = r, C = x, B = b)     //     update B to b and save this position in (R, C)
    )                           //   end of r.map()
  ) | B ?                       // end of outer a.map(); if B was updated:
    f(a, R[C] = ++n)            //   update the best target seat and do a recursive call
  :                             // else:
    a                           //   stop recursion and return a[]


Create a C program that takes the longest period of time to compile in gcc

#define a "xxxxxxxxxxx"
#define b a a a a a a a
#define c b b b b b b b
#define d c c c c c c c
#define e d d d d d d d
#define f e e e e e e e
#define g f f f f f f f
#define h g g g g g g g
#define i h h h h h h h
#define j i i i i i i i
z=j;


Python 2, 2986 2881 2949 2135 2075 2071 1996 bytes

Saved 105 bytes, implemented the program as a function to comply with standard rules. Implemented Wheat Wizard's tab and space suggestion.
Added 68 bytes due to fixing a bug.
Saved 814+51 bytes thanks to Halvard Hummel.
Saved 9+4 bytes.
Saved 4 bytes thanks to Erik the Outgolfer.
Saved 71 bytes thanks to ppperry's suggestion.

exec r"""def Z(P):
 H,n,I,o,O,i,d,D,W=[type,range]+list(" dD#xX*");R=(1,0),(-1,0),(0,1),(0,-1)
 def F(j,k,l):P[j][k]=l
 def E(j,k,v,w):
	if G(j,k,v):F(k,j,w)
 def q(b,c,d):[[E(j+J,k+K,b,c)for J,K in M]&L if G(j,k,d)]
 def A(e,r,l,o,q):
	S,E,P[q][o],Q,X=P[q][o],e,0,[(o,q)],0
	for a,b in Q:
	 &R:
		x,y=a+j,b+k
		if(0<=x<w!=0<=y<h)<1:continue
		if e in((x,y),P[y][x]):X=1;e=x,y;break
		if I!=P[y][x]:continue
		F(y,x,P[b][a]+1);Q+=[(x,y)]
	 if X:break
	p,i=e,0
	while(o,q)!=p:
	 a,b=p;P[b][a],m=[r,l][l and i==1],0
	 &R:
		x,y=a+j,b+k
		if(0<=x<w!=0<=y<h)-1:continue
		if(H(P[y][x])==H(0))*(m==0 or P[y][x]<P[m[1]][m[0]]):m=x,y
	 p=m;i+=1
	P[q][o],P[e[1]][e[0]]=S,E;[F(k,j,I)&L if H(P[k][j])==H(0)]
 def B(N):
	[[E(j,k,"x*",I),0<j<w-1 and E(j,k,O,I)]&L]
	&L:
	 if G(j,k,D):[E(j+J,k+K,I,d)for J,K in M]
	 if G(j,k,O)and j==0:T=0,k
	if N:A(O,o,0,*T)
	U,V=M[-1];[[[F(k+K,j+J,I)for J,K in M if(P[k+K][j+J]!=i)*((0<=j+J+U<w!=0<=k+K+V<h and G(j+J+U,k+K+V,D))<1)],F(k,j,W),A(o,W,O,j,k),q(I,d,W),F(k,j,D)]&L if G(j,k,D)];q("xX*# @+-|",i,o)
 for j in"|+-":P=P.replace(j,i)
 P=list(map(list,P.split("\n")));h=len(P);w=len(P[0]);b,L,M,G="#+-|D",[(k,j)for k in n(w)for j in n(h)],[(k-1,j-1)for k in n(3)for j in n(3)if(j,k)!=(1,1)],lambda j,k,v:P[k][j]in v
 B(1);Y=lambda:0<j<w-1!=0<k<h-1and G(j,k,i);[[[F(k,j,o),F(k+g,j+N,i)]for N,g in((-1,-1),(-1,1),(1,-1),(1,1))if P[k][j+g]+P[k][j-g]==P[k+N][j+g]+P[k-N][j]==P[k+N][j]+i==o+i]&L if(j in(1,w-2)or k in(1,h-2))*Y()for N in n(w*h)];[F(k,j,I)&L if Y()];B(0)
 def c(x,y,b,l,d,f,Q):
	F(y,x,b)
	for J,K in M:Q+=[[],[(x+J,y+K)]][G(x+J,y+K,l)];E(x+J,y+K,d,f)
 &L:
	if G(j,k,D):Q=[(j,k)];[c(x,y,"@",W,d,I,Q)for x,y in Q if G(x,y,"X*")];[G(u,v,"X*")and[E(u+U,v+V,I,d)for U,V in M]or E(u,v,"@",I)for u,v in L];Q=Q[:1];[c(x,y,"$",I,"x*",i,Q)for x,y in Q];F(k,j,D)
 &L:E(j,k,"@$d",I);X=(k>0and G(j,k-1,b))+(k<h-1and G(j,k+1,b))-(j>0and G(j-1,k,b))-(j<w-1and G(j+1,k,b));E(j,k,i,{2:"+",X:"|",-X:"-"}[2])
 print"\n".join("".join(p)for p in P)""".replace("&","for j,k in ")

Try it online!

It was golfed down significantly; yet there may still be room for improvement. This piece of code, however, solves all test cases. Does not run very efficiently; for large prisons the architect may take their time to figure it out.
Uses a simple pathfinding algorithm to connect both doors and the prisoners to the corridor. Then it encapsulates all prisoners and their walls and pushes said walls in empty space until all of it is filled. As a final step, the ASCII art appearance is implemented.

Took me for sure several hours to write. I hope it also works on other prisons than the test cases. (You cannot test them all, can you?)


CJam, 66 + 65 + 64 + 63 + 62 = 320 325 355  bytes

The following 5 lines are the first 5 generations:

{     `(\1>+q~](\_,["_~"a{~mp'P"Not p"?"rime"@;}{~,>{mp},p;}]=~}_~
{    `(\1>+q~](\_,["_~"a{~mp'P"Not p"?"rime"@;}{~,>{mp},p;}]=~}_~
{   `(\1>+q~](\_,["_~"a{~mp'P"Not p"?"rime"@;}{~,>{mp},p;}]=~}_~
{  `(\1>+q~](\_,["_~"a{~mp'P"Not p"?"rime"@;}{~,>{mp},p;}]=~}_~
{ `(\1>+q~](\_,["_~"a{~mp'P"Not p"?"rime"@;}{~,>{mp},p;}]=~}_~

The last one produces

{`(\1>+q~](\_,["_~"a{~mp'P"Not p"?"rime"@;}{~,>{mp},p;}]=~}_~

which still performs the prime tasks correctly.

Test it here.

Explanation

The basic CJam quine is

{"_~"}_~

which can be extended very easily to a generalised quine. For an explanation of this see my answer here.

The basic ideas for this answer are:

Start the quine with a bunch of spaces and remove one of these when quining.
Get an array with all input numbers (0, 1 or 2) and choose some code to run depending on the length (by using it to index into an array).

Here is a breakdown of the code inside the quine:

"Remove a space from the block's string representation:";
`(\1>+
`      "Get the string representation of the block.";
 (\    "Slice off the leading '{' and pull the remaining string back up.";
   1>  "Remove the first character, i.e. a space.";
     + "Prepend the '{' to the string again.";

"Get the array of inputs and choose the code:";
q~](\_,[...]=~
q~             "Read and eval the input.";
  ]            "Wrap everything (including the string for the block) in an array.";
   (\          "Shift off the string and swap it with the rest of the array.";
     _,        "Duplicate the input array and get its length.";
       [...]=  "Use it to index into this array.";
             ~ "If there are no inputs there will now be an array on the top of the
                stack, which ~ will unwrap. Otherwise there will be a block which ~
                will evaluate.";

"If there is no input, push the string needed for the quine and put it in
 an array for ~ to unwrap:";
"_~"a

"If there is one input, test for primality:";
~mp'P"Not p"?"rime"@;
~mp                   "Unwrap the input array and test for primality.";
   'P"Not p"?         "Choose either 'P' or 'Not p' depending on the result.";
             "rime"   "Push the common part of the string.";
                   @; "Pull up the quine string and discard it.";

"If there are two inputs, print an array with all the primes in the range:";
~,>{mp},p;
~          "Unwrap the array leaving N and M on the stack.";
 ,         "Get a range [0 1 .. N-1].";
  >        "Drop the first M elements, giving [M M+1 .. N-1].";
   {mp},   "Filter to keep only the primes.";
        p  "Pretty-print the array.";
         ; "Discard the quine string.";


Pyth, 51 48 bytes
FGITW.
=cQdMqeGhHL++hQb@Q1holN{+Fmf.AgVTtTyM+]Y._d.p>Q2

Test suite.


Pyth, 25 bytes

mcl@.:d2.:z2tlzc2"\__//\/

Test suite

Outputs smoothness, chunkiness. Basically, it takes the hard coded string and cuts it in half. Each half is decomposed into its 2 character substrings, and the same is done for the input. We take the intersection, resulting in the south and chunky pairs. Then, we take the the length, divide by the number of pairs, and print.


Ways of specifying random generation in challenges

Return a thousand different foos

This makes it impossible to return hardcoded values and have a half decent golf. However, a legit foo generator does have a small chance of outputting duplicate foos unless it is actually checking them. To remove the burden of checking, an empirically tested failure rate, say 10%, could be specified as acceptable.

Be aware of the birthday paradox, that the probability of duplicates may be higher than you think. If there are only a million possible foos, a thousand random foos will have a probability of about 0.6 that there is a duplicate in there somewhere, and that's assuming that foo generation is completely uniform. If this could be an issue, require say 900 unique foos for every 1000 generated, which is far more generous for a genuine foo generator but still impractical for hardcoding.

This also allows you to repeatedly generate foo-like things and check fooness until you get foos. I think this is a valid solution myself, but if you don't like it:

Do it quickly

The chances of a completely random foo-like thing being foo are probably quite low, so specifying a time limit is likely to force a genuine attempt at foo generation.

To accomodate the speed differences between different languages, you may want to have different time limits depending on the language like Hackerrank: https://www.hackerrank.com/environment . However if you specify large enough foos the probability of random foo-like things being foo might be really low, so a "before the heat death of the Universe" rule might be sufficient.


Golfscript, 71 70 69 chars

2\!:^2^..292^15.2/3]{(.)2/.9>+{\+.((}*;.}do;;]-1%{^0@{2$*+\}/"/"\n}/;

(Assumes that you don't pass it anything on stdin)

I don't want to hear any more whinging by people who don't have built-in constants for pi. I don't even have floating point numbers!

See http://en.wikipedia.org/wiki/Continued_fraction#Best_rational_approximations for the background.

# No input, so the stack contains ""
2\!:^2^..292^15.2/3]
# ^ is used to store 1 because that saves a char by allowing the elimination of whitespace
# Otherwise straightforward: stack now contains [2 1 2 1 1 1 292 1 15 7 3]
# Pi as a continued fraction is 3+1/(7+1/(15+1/(...)))
# If you reverse the array now on the stack you get the first 10 continuants followed by 2
# (rather than 3)
# That's a little hack to avoid passing the denominator 1000000

{
    # Stack holds: ... [c_n c_{n-1} ... c_0]
    (.)2/.9>+
    # Stack holds ... [c_{n-1} ... c_0] c_n (1+c_n)/2+((1+c_n)/2 > 9 ? 1 : 0)
    # (1+c_n)/2 > 9 is an ad-hoc approximation of the "half rule"
    # which works in this case but not in general
    # Let k = (1+c_n)/2+((1+c_n)/2 > 9 ? 1 : 0)
    # We execute the next block k times
    {
        # ... [c_{n-1} ... c_0] z
        \+.((
        # ... [z c_{n-1} ... c_0] [c_{n-1} ... c_0] z-1
    }*
    # So we now have ... [c_n c_{n-1} ... c_0] [(c_n)-1 c_{n-1} ... c_0] ...
    #                    [(c_n)-k+1 c_{n-1} ... c_0] [c_{n-1} ... c_0] c_n-k
    ;
    # Go round the loop until the array runs out
    .
}do

# Stack now contains all the solutions as CFs in reverse order, plus two surplus:
# [2 1 2 1 1 1 292 1 15 7 3] [1 2 1 1 1 292 1 15 7 3] ... [6 3] [5 3] [4 3] [3] [2] []
# Ditch the two surplus ones, bundle everything up in an array, and reverse it
;;]-1%

# For each CF...
{
    # Stack holds ... [(c_n)-j c_{n-1} ... c_0]
    # We now need to convert the CF into a rational in canonical form
    # We unwind from the inside out starting with (c_n)-j + 1/infinity,
    # representing infinity as 1/0
    ^0@
    # ... 1 0 [c_n-j c_{n-1} ... c_0]
    # Loop over the terms of the CF
    {
        # ... numerator denominator term-of-CF
        2$*+\
        # ... (term-of-CF * numerator + denominator) numerator
    }/

    # Presentation
    "/"\n
    # ... numerator "/" denominator newline
}/

# Pop that final newline to avoid a trailing blank line which isn't in the spec
;


APL (77)

{0=⍴,⍵:1⋄C←0/⍨⍴V←∪∊G←⍵⋄0∊C⊣{C[V⍳⍵]:⍬⋄C[V⍳⍵]←1⋄∇¨⍵~⍨∊G/⍨⍵∊¨G}⊃V:0⋄+/∇¨⍵∘~∘⊂¨⍵}

This is a function that takes a list of edges as a graph, i.e.:

      {0=⍴,⍵:1⋄C←0/⍨⍴V←∪∊G←⍵⋄0∊C⊣{C[V⍳⍵]:⍬⋄C[V⍳⍵]←1⋄∇¨⍵~⍨∊G/⍨⍵∊¨G}⊃V:0⋄+/∇¨⍵∘~∘⊂¨⍵} (0 2)(0 3)(1 3)(1 4)(1 5)(2 3)(3 4)(3 5)
16560

(Incidentally, this takes about half a second on my computer.)

So the format is [[v1,v2], [v1,v2], ...]. To pass in a single-edge graph, you need to enclose it first, otherwise you get [0,1] instead of [[0,1]]:

      {0=⍴,⍵:1⋄C←0/⍨⍴V←∪∊G←⍵⋄0∊C⊣{C[V⍳⍵]:⍬⋄C[V⍳⍵]←1⋄∇¨⍵~⍨∊G/⍨⍵∊¨G}⊃V:0⋄+/∇¨⍵∘~∘⊂¨⍵} ⊂0 1
1

Explanation:

Base case 1 (empty graph):

0=⍴,⍵:1: if the graph is empty, return 1: the current path has emptied the graph while keeping it connected.

Base case 2 (unconnected graph):

C←0/⍨⍴V←∪∊G←⍵: store the list of edges in G, the vertices in V, and a 0 for each vertex in C.
{...}⊃V: See if the graph is connected. Starting with the first vertex:

C[V⍳⍵]:⍬: if the vertex has already been visited, do nothing
C[V⍳⍵]←1: mark the current vertex as visited
G/⍨⍵∊¨G: find each edge this vertex is connected to
⍵~⍨∊: find all vertices involved in those edges, except the current vertex
∇¨: visit all those vertices

0∊C...:0: afterwards, if one of the vertices is not visited, the graph is no longer connected. The current path is invalid, so return 0.

Recursive case:

⍵∘~∘⊂¨⍵: For each edge, create the graph formed by removing that edge, along with any orphaned vertices, from the current graph.
∇¨: For each of those graphs, find its edge elimination number.
+/: Sum those.


Determine the Base where a Given Equation is True

APL (Dyalog Unicode), 30 bytesSBCS

⊢{3⊃e=×/2↑e←⍵⊥⍺:⍵⋄⍺∇⍵+1}1+⌈/∘,

Try it online!

Thanks to Adám for the help.

Explanation:

⊢{3⊃e=×/2↑e←⍵⊥⍺:⍵⋄⍺∇⍵+1}1+⌈/∘, ⍝
⊢                              ⍝ left argument ⍺: the vector (do nothing)
                        1+⌈/∘, ⍝ right argument ⍵: our starting base.
                             , ⍝             start by flattening the matrix of arguments                               ⌈/   ⍝             reduce by max (find the highest number)
                            ∘  ⍝             compose both of these together
                        1+     ⍝             increment by one
 {         ⍵⊥⍺         }       ⍝ convert inputs to the current base
 {       e←            }       ⍝ store the converted values in 3
 {      2↑             }       ⍝ take the first 2 values
 {    ×/               }       ⍝ multiply them together (reduce-multiply)
 {  e=                 }       ⍝ compare with e (the converted inputs)
 {3⊃                   }       ⍝ only keep the result of the comparison with the 3rd element (expected result)
 {             :⍵      }       ⍝ if truthy, return the current base.
 {               ⋄     }       ⍝ otherwise...
 {                ⍺∇⍵+1}       ⍝ ...recurse with the base incremented

We use a helper function, In, to receive the input into a more palatable format. Otherwise the input is received a matrix of 3 columns.

'3 9 42' would give, for example (read top-down then left-to-right):

0 0 4
3 9 2

And for 'aA bB 36jk' (same here. a is 10, b is 11, A is 36, etc)

 0  0  3
 0  0  6
10 11 19
36 37 20


PHP, 936 bytes

for($a=explode('-',gzinflate(base64_decode('dVTRbtswDPwV/YANKXZq+zFJ1wRts3VZtgB7Y2Mm1ipLAO0089+PtNIuHbAnAzySd+RRNkVZ6XxSJUsMdES1g66x/tgHn5iiKnSms+Q+NF7Nami7xJTajLFtE1ro1D0eDkidZJe6itnQYqfWUNsYNsV1OHgKyNHJ9G/rryfr98M7wyT2mfma8KzuYf8SG2Wx0Rqot179AK/mJ0JB8qhpZ52z0KoVehrUCoguEhjP38i2g0OS2PRK1kOqnoJ7kXAk/wn7BrjJFgYXJH2qdaHLZM0UQLW6428bSCaZZmPFHYF/cSzsySLtR+B68PmJG3oQNTdR7eyZoGG1jzx8cCMw1bnJ3wdntVH+TdT03Q1dx62+pWrJZD0jRaTYnPoG6RBY2DzlwQeUPZbmin/GRUAHi66OUGXKZNFg1yMJOKO+OcmgZdzLksIrIwuHr+jAj0VRxhz9L2h50KsFV9n/ii4n9GbNev9gvcMhMZUWDXJIGGrepNqE0EldL1j10dBwlqVv4SCgiWS7EGoKZ8VJo4hqcrkCloVeLWURVPMtC5RpPtxkAe6VhS9CcLY+ogCRaIX0jNQzkQzA8ewfU2/TD/pyccoksoFB/NjSqRVvKz4GY6rk9myPTS9Vn2yHvgnnsSs7L+h4h3epekDvsZZd3GTGTEzyOPg6ePHw3fyKzZeajZWDrNVn+3sMFzlPVPKrJXB8jmy9BIvY37btoBb8TkbWMrJugpfUDcJxlFrGxpd3v0rVLuUr7RqGqjjFnNfPZlovf4OJ1ua64C2b47HRHIifqvryDC1w1EQtfwA=')));$d=$a[+$i++];)date(Ymd,strtotime($argn))>$d?$m=$a[$i++]:die($m);echo'Donald Trump';

Try it online!

Tests:
Try it online!

The code for tests is the same logic but a little bit different to replace the die(...) with return... so I can loop over tests.

I have created a string having start date of presidency minus 1 day in format of YYYYMMDD and name of president in it, separated by -. Example: 17890429-George Washington-17970303-John Adams-18010303-Thomas Jefferson-...

This string is compressed using gzdeflate and also the compressed output is converted to base-64 so all characters are printable ASCII and I can post them here or use them in TIO.

In the script, the string is split by - and looped over. For each loop iteration:

$d is set to current iteration value (which is the president's start date -1 day) and the loop variable ($i) is increased by one.
If input date is larger than $d, then $m is set to next iteration value (which is the president name for $d) and the loop variable ($i) is increased by one again. This allows the loop to get president names but jump over them in iterations.
If input date is not larger than $d, then that means the previous iteration was the correct president, so $m is printed using die function, this will stop the whole program after printing the name.

At the end, if the loop is finished (which means no die was called), the last president's name is printed, since we know non of previous presidents have got a match (so basically anything after January 19, 2017) prints last president's name, even if it is January 1, 3999.


Python 2, 104 94 89 81 79 bytes

s=n=input()
while s:print' '*s,'/ '*(n-s)+'_'*(2*s+len(`n`));s-=1
print'\/'*n,n

Try it online!
Edit 1: Forgot I switched to python 2 lol
Edit 2: Thanks @ElPedro for the idea of switching to while loop!
Edit 3: Thanks @SurculoseSputum for saving 8 bytes!
Edit 4: Thanks @xnor for saving 2 bytes!


Find the area of the smallest rectangle to contain squares of sizes up to n

JavaScript (ES6), 172 bytes

Slower but shorter version suggestion suggested by @JonathanAllan (also saving 4 bytes in the original answer):

f=(n,A,S=(n,c)=>n>=0?c(n)||S(n-1,c):0)=>S(A,w=>(F=(l,n)=>n?S(w-n,x=>S(A/w-n,y=>l.some(([X,Y,W])=>X<x+n&X+W>x&Y<y+n&Y+W>y)?0:F([...l,[x,y,n]],n-1))):A%w<1)([],n))?A:f(n,-~A)

Try it online!

Original answer,  209 183 178  174 bytes

Returns the \$N\$th term of the sequence, 1-indexed.

f=(n,A,S=(n,c)=>n>=0?c(n)||S(n-1,c):0)=>S(A,w=>A%w?0:(F=(l,n)=>n?S(w-n,x=>S(A/w-n,y=>l.some(([X,Y,W])=>X<x+n&X+W>x&Y<y+n&Y+W>y)?0:F([...l,[x,y,n]],n-1))):1)([],n))?A:f(n,-~A)

Try it online!

Commented

Helper function

We first define a helper function \$S\$ which invokes a callback function \$c\$ for \$n\$ to \$0\$ (both included) and stops as soon as a call returns a truthy value.

S = (n, c) =>               // n = integer, c = callback function
  n >= 0 ?                  // if n is greater than or equal to 0:
    c(n) ||                 //   invoke c with n; stop if it's truthy
    S(n - 1, c)             //   or go on with n - 1 if it's falsy
  :                         // else:
    0                       //   stop recursion and return 0

Main function

We start with \$A=1\$.

For each pair \$(w,h)\$ such that \$w\times h = A\$, we try to insert all squares of size \$1\times1\$ to \$n\times n\$ (actually starting with the largest one) in the corresponding area, in such a way that they don't overlap with each other.

We keep track of the list of squares with their position \$(X,Y)\$ and their width \$W\$ in \$l[\text{ }]\$.

We either return \$A\$ if a valid arrangement was found, or try again with \$A+1\$.

f = ( n,                    // n = input
      A ) =>                // A = candidate area (initially undefined)
S(A, w =>                   // for w = A to w = 0:
  A % w ?                   //   if w is not a divisor of A:
    0                       //     do nothing
  : (                       //   else:
    F = (l, n) =>           //     F = recursive function taking a list l[] and a size n
      n ?                   //       if n is not equal to 0:
        S(w - n, x =>       //         for x = w - n to x = 0
          S(A / w - n, y => //           for y = A / w - n to y = 0:
            l.some(         //             for each square in l[]
            ([X, Y, W]) =>  //             located at (X, Y) and of width W:
              X < x + n &   //               test whether this square is overlapping
              X + W > x &   //               with the new square of width n that we're
              Y < y + n &   //               trying to insert at (x, y)
              Y + W > y     //
            ) ?             //             if some existing square does overlap:
              0             //               abort
            :               //             else:
              F([ ...l,     //               recursive call to F:
                  [x, y, n] //                 append the new square to l[]
                ],          //
                n - 1       //                 and decrement n
              )             //               end of recursive call
          )                 //           end of iteration over y
        )                   //         end of iteration over x
      :                     //       else (n = 0):
        1                   //         success: stop recursion and return 1
    )([], n)                //     initial call to F with an empty list of squares
) ?                         // end of iteration over w; if it was successful:
  A                         //   return A
:                           // else:
  f(n, -~A)                 //   try again with A + 1


NetLogo
to go
  type one-of [ "Print" "Calculate" "Find" "Determine" "Output" ]
  type " the "
  type one-of [ "sum" "mean" "average" "median" "standard deviation" "product" "geometric mean"]
  type " of all "
  type one-of [ "prime" "composite" "even" "odd" "perfect" "abundant" "deficient" "square" "triangular" "cubic" "lucky" "friendly" "strictly non-palindromic" ]
  type " numbers from "
  type random 100
  type " to "
  type 100 + random 10000
  type one-of [ " (inclusive)." " (exclusive)." ]
end

Sample output (obtained randomly):
Find the product of all friendly numbers from 60 to 3112 (inclusive).


I'm new to this whole golfing thing, this is what I got so far:

Use Closures not functions:

def a(b){print b}

is longer than

a={print it}

You can use a negative index in arrays and lists as an alias for size()-

c = "abc"
d = ["a", "b", "c"]

assert c[c.size()-1] == c[-1]
assert c[c.size()-2] == c[-2]
assert d[d.size()-1] == d[-1]
assert d.last() == d[-1]

The spread operator is a shortcut for collect:

assert d*.size() == d.collect{it.size()}

For sorting use the spaceship operator:

e = [54,5,12]
assert e.sort{a,b->a<=>b}==e.sort{a,b->a<b?-1:+1}
assert e.sort{a,b->a<=>b}==e.sort{a,b->if (a>b) {return(-1)} else {return(+1)}}

Edit Conversions:

assert "123" as int == "123".toInteger()


Python, 56
g=lambda a,b,m,u=0:u!=(a,b)and-~g(b,(a+b)%m,m,u or(a,b))


Boolfuck, 6 bytes

,,[;+]

  You can safely assume no N-Bonacci numbers will exceed the default number type in your language.

The default number type in Boolfuck is a bit. Assuming this also extends to the input numbers N and X, and given that N>0, there are only two possible inputs - 10 (which outputs nothing) and 11 (which outputs 1).

, reads a bit into the current memory location. N is ignored as it must be 1. If X is 0, the loop body (surrounded by []) is skipped. If X is 1, it is output and then flipped to 0 so the loop does not repeat.


In my answer to Loophole for other challenge, I deliberately exploit the fact that the poster didn't specify that the answer had to be responding to another question.  This made my answer recursive and self-referential.

I also golfed my answer (even though it was a popularity contest).  0 bytes of code.


Advent Challenge 3: Time to remanufacture the presents!


R, 104 bytes

function(s){m=matrix(" ",l<-nchar(s),l)
m[cbind(1:l,sample(l,l,T))]=el(strsplit(s,""))
write(m,1,l,,"")}

Try it online!

Input as a string; writes to stdout.


Python 3, 149 \$\cdots\$ 145 140 bytes

from datetime import*
def f(d):
 n,s=(date(*d)-date(1,1,1)).days+1137143,""
 for i in[144000,7200,360,20,1]:s+=f".{n//i}";n%=i
 return s[1:]

Try it online!

Takes Gregorian date as [year, month, day] list and returns Mayan date as f"{B'ak'tun}.{K'atun}.{Tun}.{Winal}.{Day}"(loosely as a python f-string).


ais523's answer - Blindfolded Arithmetic

(I hope my proof is understandable. I can't check my own proof e.g. with a Try it online! link so I'm not sure)

All code in this post will be Python pseudocode, with rep n: repeat n times. All conditionals must be either 0 or 1.

It's provable that the value of i is always >0 in the program execution, so i/i always give 1.

Define some building blocks:

if c: a = a + b is equivalent to d = b * c; a = a + d; assuming d is unused.
So, let (statement) be if c: statement where c can be some condition.

b = b * 2**N (where N is a compile-time constant) is equivalent to

rep N: b = b + b

b = a / 2**N is equivalent to

b = i / i
b = b * 2**N
b = a / b

b = a % 2**N is equivalent to

b = a / 2**N
b = b * 2**N
b = a - b

Any 2-symbol Turing machine with N states can be written like this:

while True:
    if state == 0:
        # process state 0
    if state == 1:
        # process state 1
    .
    .
    .
    if state == HALTING_STATE:
        0 / 0
    .
    .
    .
    if state == N-1:
        # process state N-1
    state = newstate

where each # process state block looks like this

# optional (not all states need this)
tape.move_left()

# optional
tape.move_right()

# optional
tape.flip()

new_state = a if tape.value() else b

This needs to be translated to BFA compatible code.

Two variables i and a will be used to represent the tape and state (and tape as well)

The content of i at each wraparound:

N least significant bits are equal to 2**state (i.e., the state'th significant bit is on, all other bits are off)
The rest of bits form the right half of the tape.

The content of a at each wraparound:

The left half of the tape.

The tape pointer is on the least significant bit of a.

At the beginning of each loop, N bits are inserted between the tape part and the state part in i:

d = i / 2**N
d = d * 2**N
i = i - d
d = d * 2**N
i = i + d

At each # process state i block, the structure of i is:

M-N least significant bits: the remaining part of the old value of state (state >> i). (where M = 2*N - i)
N next LSB: (partial) value of new_state (or 0 if it's not defined yet in that loop)
Rest: Tape.

Of course M is a compile time constant.

(as an exception, the "process halting state" block can be implemented as

if i%2: b = b - b; b = b / b;

or equivalently (assume c isn't used)

c = i % 2; b = i / i; if c: b = b - b; b = b / b;

)

More rewriting:

(tape.move_left()) (the outer () stands for conditional, as always)

# allocate a free bit on (i)
b = i / 2**M
(i = i + b)
# copy that bit from (a) to (i)
b = a % 2
b = b * 2**M
(i = i + b)
# remove a byte from (a)
b = i/i
(b = b + b)
a = a / b

(tape.move_right())

# allocate (M+1) bits at the end of (a)
(a = a * 2**(M+1))

# copy that from (i) to (a)
b = i % 2**(M+1)
(a = a + b)

# remove the (M) bits from (a) that is over-copied from (i)
b = i/i # now b==1
rep M: (b = b + b)
a = a / b # if the conditional fails a = a / 1 is a no-op.

# clear that bit on (i)
b = a % 2
b = b * 2**M
(i = i - b)

# remove the bit from (i)
b = i / 2**(M+1)
b = b * 2**M
(i = i - b)

(tape.flip())

b = a % 2
b = b * 2
(a = a - b)
b = i/i
(a = a + b)

(new_state = a if tape.value() else b)

  TODO

There are 2 remaining issues:

Only the bits to the left of the pointer is outputted, and
if not tape_value(): tape.move_left() (and the equivalent move_right) is not directly supported.

To solve those problems,

A TM with only a half of the tape is still TC.

  You can interlace the positive-index cells with the negative-index ones, and replace every movement with a double-movement (doubling the number of states). You'll also need to mark two cells at the left with special symbols so you know to shift by one and turn around (1 extra symbol; 1 extra state), and you'll need to have a reversed copy of every state for when you're in negative-land and every movement is backwards (again doubling the number of states).

(source)

So, it's possible to:

Make the tape from 2 interleaving infinite tapes.
One of them only have one 1 denoting the right end of the tape. The other is used to store data.
At program halt, instead of immediately exiting, move right until hit the end of the tape.

So the whole tape are stored in the right half (i.e., i) and readable at program termination.

  Am I still missing something?


Jelly, 21 20 19 18 bytes

R7ẋḌµ;ŒċP€⁹f€FµÐLḟ

Note that the output doesn't match the OP's. I've left a comment.

Try it online!

How it works

R7ẋḌµ;ŒċP€⁹f€FµÐLḟ  Main link. Left argument: n. Right argument: l

R                   Range; yield [1, ..., n].
 7ẋ                 Times; yield [[7], ..., [7] * n].
   Ḍ                Undecimal; yield s := [7, 77, ...].
    µ         µÐL   Begin a new chain with argument s and call the chain between
                    until the results no longer chain.
                    Return the last unique result.
      Œċ            Combinations; return all unordered pairs in integers in the
                    return value.
     ;              Concatenate the return value and its pairs.
        P€          Take the product of each individual integer and each pair in
                    the result.
          ⁹f€       Filter each; for each j in [1, ..., l], intersect [j] with the
                    array of products. The result is sorted and contains no
                    duplicates.
                 ḟ  Filterfalse; remove the elements of s from the result.


HTML + JavaScript, 20+105 = 125 bytes

<input id=I oninput=v=I.value;s='*'.repeat(l=v.length-1);I.value=s+v[l];clearTimeout(I.t);I.t=setTimeout(`I.value=s+'*'`,1e3)

The delay between the entry of k and the letter becoming * is one second.

JavaScript oninput, Formatted

v=I.value;
s='*'.repeat(l=v.length-1);
I.value=s+v[l];
clearTimeout(I.t);
I.t=setTimeout(`I.value=s+'*'`,1e3)

Test Snippet

Added the ending bracket (>) for better compatibility.

<input id=I oninput=v=I.value;s='*'.repeat(l=v.length-1);I.value=s+v[l];clearTimeout(I.t);I.t=setTimeout(`I.value=s+'*'`,1e3)>


C (gcc), 59 53 51 bytes
Saved 6 bytes thanks to the man himself Arnauld!!!
Saved 2 bytes thanks Dominic van Essen!!!

p;x;f(a,b,m){for(p=a,x=1;p-b&&++x<m;)p=p*a%m;x%=m;}

Try it online!
Inputs positive integers \$a,b,m\$ with \$a,b<m\$.
Outputs a positive integer \$x\$ such that \$a^x\equiv b\ (\text{mod}\ m)\$ or \$0\$ if no such \$x\$ exists.


Python, 200 characters

f=lambda a,b,c,d:min(2,sum((x-c)*(x-d)<=0for x in range(min(a,b),max(a,b)+1)))
for i in' '*input():z=map(int,raw_input().split());print('nothing','point','line',0,'rectangle')[f(*z[::2])*f(*z[1::2])]

f returns:

0 if the intervals [a,b] and [c,d] don't overlap
1 if the intervals [a,b] and [c,d] overlap in only one point
2 if the intervals [a,b] and [c,d] overlap in a range of points


Python 2 with numpy, 116 bytes

from numpy import*
def f(x,y):a=linalg.lstsq(hstack((x,y,ones_like(x))),(x*x+y*y)/2);return a[1]/sum((x-a[0][0])**4)

Takes x and y as 2d column vectors and returns an array containing the answer.  Note that this will give an empty array for a perfectly straight line or with 3 or fewer points.  I think lstsq gives no residuals if there's a perfect fit.

Explanation

Essentially, this finds the circle of best fit and gets the squared residuals.

We want to minimize (x - x_center)^2 + (y - y_center)^2 - R^2.  It looks nasty and nonlinear, but we can rewrite that as x_center(-2x) + y_center(-2y) + stuff = x^2 + y^2, where the stuff is still nasty and nonlinear in terms of x_center, y_center, and R, but we don't need to care about it.  So we can just solve [-2x -2y 1][x_center, y_center, stuff]^T = [x^2 + y^2].

We could then back out R if we really wanted, but that doesn't help us much here.  Thankfully, the lstsq function can give us the residuals, which satisfies most of the conditions.  Subtracting the center and scaling by (R^2)^2 = R^4 ~ x^4 gives us translational and scale invariance.

This is positive definite because the squared residuals are nonnegative, and we're dividing by a square.  It tends toward 0 for circles and lines because we're fitting a circle.
I'm fairly sure it's not surjective, but I can't get a good bound. If there is an upper bound, we can map [0, bound) to the nonnegative reals (for example, with 1 / (bound - answer) - 1 / bound) for a few more bytes.
We subtract out the center, so it's translationally invariant.
We divide by x**4, which removes the scale dependence.
It's composed of continuous functions, so it's continuous.


R, 124 118 bytes

function(n,i=(n+1)/2,j=n%/%2,m="[<-"(matrix(-letters,i,i),j-1,j-1,0:9-1))cbind(y<-rbind(m,m[j:1,]),y[,j:1])
`-`=sample

Try it online!

In R, things that look like operators are just functions that get special treatment from the parser.

If you redefine an operator (like -) to be some other function, it keeps the special treatment from the parser. Since - is both prefix and infix, and I need to call the sample function with both one and two arguments, I can use

`-`=sample

to get what I want.

So the code -letters is translated to sample(letters), which randomly shuffles the letters built-in. But j-1 is translated to sample(j,1), which randomly samples 1 item from the vector 1:j.

(This behaviour of the sample function depending on the number of parameters and what the first parameter is, is a huge pain in the butt in production code, so I'm happy to find a great use of its perverse nature here!)

Otherwise the code just makes the top left quadrant of the required result, replaces a random element (the j-1,j-1 bit) with a random digit (the 0:9-1 bit), and folds it out for the required symmetry. The i and the j are needed to deal with the even and odd cases.


Fix the Meeesesessessesseesseessedessed upp teeexexextext

CJam, 207

{_,1>{:E1<_0{:I2$,+E=:C+:R1>C'9>)*+:P,E,<{EP#{L0}{PRI)1}?}{PE#L{R8cP,E,-*+}?0}?}g}&}:U;LqS+'a+{_'[,_el^A,s+&,V={+}{s\V!:V{L{:BU_aL?B,,1>Bf{_2$<U_{_W=8>S8c+*+\@>j+}{?;}?}+{,}$0=}j}|\}?}%s'\8cN++'\"\bn"f+er-2<

Try it online

Explanation:

Almost forgot to write this :p

The problem is solved in several steps:

the text is separated into runs of alphanumeric characters (let's call them words) and runs of non-alphanumeric characters (non-words)
non-words are printed as they are, and words are fixed
fixing a word is done recursively (with memoization): split the word into 2 chunks in every possible way (including empty 2nd chunk), try to unmess the first chunk (see below), fix the 2nd chunk and join the results with a space-backspace if needed; take the shortest sub-solution
unmessing a chunk means finding a minimal string of alphanumeric characters possibly followed by some backspaces (but with no backspaces in the middle) that when messed up, result in the given chunk; it is done with a simple greedy algorithm, going from left to right, building the unmessed string and its messed version in parallel, and determining the next needed character at each step; some chunks can not be unmessed


Ruby, 15+26+17+26+17 = 101

Robot Finds Pickles!

Okay, here's a baseline to get people started, using the following super-naive algorithm:

Each tick, each robot will act in numeric order, performing the following steps:

Identify the closest (Manhattan distance) pickle that no other robots are targeting.
Figure out which adjacent squares are available to move to.
Choose one of those squares, preferring directions that move it closer to the selected pickle.

Here's what it looks like for Test Case #1:

Obviously this isn't very good but it's a start!

Code:

Tile = Struct.new(:world, :tile, :x, :y) do
    def passable?
        tile =~ /\.|P/
    end

    def manhattan_to other
        (self.x - other.x).abs + (self.y - other.y).abs
    end

    def directions_to other
        directions = []
        directions << ?U if self.y > other.y
        directions << ?D if self.y < other.y
        directions << ?L if self.x > other.x
        directions << ?R if self.x < other.x
        directions
    end

    def one_step direction
        nx,ny = case direction
            when ?U then [self.x, self.y - 1]
            when ?D then [self.x, self.y + 1]
            when ?L then [self.x - 1, self.y]
            when ?R then [self.x + 1, self.y]
        end

        self.world[nx,ny]
    end

    def move direction
        destination = one_step(direction)
        raise "can't move there" unless destination && destination.passable?

        destination.tile, self.tile = self.tile, ?.
    end
end

class World
    DIRECTIONS = %w(U D L R)

    def initialize s
        @board = s.split.map.with_index { |l,y| l.chars.map.with_index { |c,x| Tile.new(self, c, x, y) }}
        @width = @board[0].length
    end

    def [] x,y
        y >= 0 && x >= 0 && y < @board.size && x < @board[y].size && @board[y][x]
    end

    def robots
        tiles_of_type(/[0-9]/).sort_by { |t| t.tile }
    end

    def pickles
        tiles_of_type ?P
    end

    def tiles_of_type type
        @board.flatten.select { |t| type === t.tile }
    end

    def inspect
        @board.map { |l| l.map { |t| t.tile }*'' }*?\n
    end
end

gets(nil).split("\n\n").each do |input|
    w = World.new(input)
    steps = Hash[w.robots.map { |r| [r.tile, []] }]
    while (pickles_remaining = w.pickles).size > 0
        current_targets = Hash.new(0)

        w.robots.each do |r|
            target_pickle = pickles_remaining.min_by { |p| [current_targets[p], r.manhattan_to(p)] }

            possible_moves = World::DIRECTIONS.select { |d| t = r.one_step(d); t && t.passable? }
            raise "can't move anywhere" if possible_moves.empty?

            direction = (r.directions_to(target_pickle) & possible_moves).first || possible_moves[0]

            current_targets[target_pickle] += 1
            steps[r.tile] << direction
            r.move(direction)
        end
    end

    puts steps.values.map &:join
    p steps.values.map { |v| v.size }.max
end

Takes input on STDIN in exactly the format of the test case code-block in the original question.  Here's what it prints for those test cases:

DDLLDLLLLULLUUD
LDLRRDDLDLLLLDR
URDDLLLLLULLUUL
15
ULDLDDLDRRRURRURDDDDDDDLLL
UUULDDRDRRRURRURDLDDDDLDLL
ULUURURRDDRRRRUUUDDDDLDLLL
26
URRRDRUDDDDLLLDLL
RUUUDLRRDDDLLLDLL
LDRDDLDDLLLLLLLUU
RUUURDRDDLLLLLUUU
17
DULLUUUUULDLDLLLLLDDRUUUUR
UDLRRRURDDLLLUUUUURDRUUUUD
26
LDDLDUUDDDUDDDDDR
ULUULDDDDDRDRDDDR
LULLDUUDDDRDRDDDR
UUUURDUURRRRDDDDD
LDLLUDDRRRRRRUDRR
17


Python 2, 484 468 467 bytes

i=int;u=249.3
def Q(A,B):
 a=A*A+B*B+9e4;b=B*u+36e4;I=b*b-a*128e4
 if I>0:
    t=(-b+I**.5)/(5e2*a);F,G,H=A*t,B*t,u*t;J,K,M=F,G+.6,H+2.4;L=a**-.5;k=2*(A*J+B*K+u*M)*L;C,D,E=A*L-k*J,B*L-k*K,u*L-k*M;L=(C*C+D*D+E*E)**-.5;t=(-4e2-G)/D;return(D*D*L*L*u,((i(F+t*C)/200+i(H+t*E)/200)&1)*(u*D*L))[D>0]
 else:return(u*B*B/a,((i(-2e2/B*A)/200+i(-6e4/B)/100)&1)*u*B/a**.5)[B>0]
open("s.pgm","wb").write("P5 800 600 255 "+"".join(chr(i(Q(j%800-4e2,j/800-u)))for j in range(480000)))

Note: after if I>0: there is a newline followed by a single tab char before t=...

Running the program will create an 800x600 image named s.pgm

Started from a "real" ray tracer formulas (tweaked a bit for golfing).

Rendering takes about 3s on my dead old PC (0.7s with pypy).


Retina, 353 339 178 175 150 130 129 117 bytes

R
5$*r
T`aq\we\ds`so`r.+
)`r(.*)
$1
^
:
a
sq
e
wd
+`(.+)q
w$1
+`(.+)d
s$1
+`sw

(.*)(\1w?):
$0$2
+`sw|ws

w+
-$0
\w
1

Output is in unary, separated by a colon. That means you won't really see zeroes in the output (although the presence of a colon will tell you which of the two coordinates is zero, if there is only one).

Try it online!

This was really fun and ended up being surprisingly short. :)

Explanation

Some background first. There are several coordinate systems to describe hexagonal grids. The one asked for uses offset coordinates. That's essentially like rectangular grid coordinates, except that one axis "wobbles" a bit. In particular, the question asks for the "odd-q" layout shown on the linked page. This coordinate system is a bit annoying to work with, because how the coordinates change during a move depends not only on the direction of the move but also on the current position.

Another coordinate system uses axial coordinates. That's essentially imagining the hexgrid as a diagonal slice through a volume of cubes, and using two of the axes (e.g. x and z) to find a position on the 2D plane. On the hex grid, that means that the two axes form an angle of 60 (or 120) degrees. This system is a bit less intuitive but much easier to work with, since every direction corresponds to a fixed "delta" vector. (For a better explanation of how to arrive at this coordinate system, check out the link and the lovely diagrams and animations there.)

So here's what we'll do: we compute the movement in axial coordinates (taking care of rotation as suggested in the challenge, by remapping the meaning of the commands), and when we're done we convert axial to to odd-q offset coordinates.

The six moves map to the following delta vectors in (x-z) axial coordinates:

q => (-1,  0)
w => ( 0, -1)
e => ( 1, -1)
d => ( 1,  0)
s => ( 0,  1)
a => (-1,  1)

Wait, this is Retina, we'll have to work with unary numbers. How do we work with negative unary numbers? The idea is to use two different digits. One represents +1 and the other represents -1. That means regardless of whether we want add or subtract 1 from the current position, we can always do so by adding a digit. When we're done we collapse the result into its magnitude (of the corresponding digit) by cancelling balanced digits. Then we figure out the sign based on the remaining digit, and replace all digits with 1.

The plan is to build up the axial x and z components to the left and right of a : (as a separator), in front of the input. w and s will add to the right-hand side. q and d will add to the left-hand side, and e and a will add to both sides. Since w and s are already on the correct side of the : (which will go in front), we will use those as the -1 and +1 digits, respectively.

Let's go through the code.

R
5$*r

We start by turning each R into five rs. Of course, one left turn is the same as five right turns on a hex grid, and by doing so we can a lot of duplication on the remapping step.

T`aq\we\ds`so`r.+

This is a transliteration stage which rotates the six commands, if they are found after the first r (thereby processing the first r). w and d need to be escaped to prevent them from expanding into character classes. The o inserts the source set into the target set which saves a bunch of bytes for these rotation tasks. The character mapping is therefore:

aqweds
saqweds

where the last s in the second row can simply be ignored.

)`r(.*)
$1

This removes the first r from the string, because it's been processed (I wish I had already implemented substitution limits...). The ) also tells Retina to run all stages up to this one in a loop until the string stops changing. On subsequent iterations, the first stage is a no-op because there are no more Rs and the second stage will apply another rotation as long as there are rs left in the string.

When we're done, we've mapped all commands to the direction they correspond to on the unrotated grid and can start processing those. Of course this movement is just a sum of those delta vectors, and sums are commutative, so it doesn't really matter in which order we process them now that rotations have been eliminated.

^
:

Insert the coordinate delimiter at the front.

Now we don't really need to process s and w. They are our +1 and -1 digits and they're already on the correct side of the : so they'll just drop out as required in the end. We can make another simplification: a is simply s + q and e is w + d. Let's do that:

a
sq
e
wd

Again, those s and w will just drop out. All we need to do is move those qs and ds to the front and turn them into ws and ss themselves. We do that with two separate loops:

+`(.+)q
w$1
+`(.+)d
s$1

So that's done. Time for the conversion from axial to offset coordinates. For that we need to collapse the digits. However, for now we only care about the left-hand side. Due to the way we've processed the qs and ds, we know that all the ss in the left-hand side will appear in front of any ws, so we only need to check one pair for collapsing the them:

+`sw

Now the actual conversion. Here is the pseudocode, taken from link above:

# convert cube to odd-q offset
col = x
row = z + (x - (x&1)) / 2

Right, so the left-hand side is already correct. The right-hand side needs the correction term (x - (x&1)) / 2 though. Taking &1 is the same as modulo 2. This basically parses as x/2, integer division, rounded towards minus infinity. So for positive x, we add half the number of digits (rounded down), and for negative x, we subtract half the number of digits (rounded up). This can be expressed surprisingly concisely in regex:

(.*)(\1w?):
$0$2

Due to the greediness, for even x, group 1 will match exactly half the digits, \1 the other half and we can ignore the w?. We insert that half after the : (which is x/2). If x is even, then we need to distinguish positive and negative. If x is positive, then w? will never match, so the two groups will still have to match the same number of digits. That's no problem if the first s is simply skipped, so we round down. If x is negative and odd, then the possible match is with \1 (half of x rounded down) and that optional w. Since both of those go into group 2, we will write x/2 with the magnitude rounded up (as required).

+`sw|ws

Now we collapse the digits on the right-hand side. This time, we don't know the order of the s and w, so we need to account for both pairs.

w+
-$0

Both parts are now reduced to a single repeated digit (or nothing). If that digit is w, we insert a minus sign in front.

\w
1

And finally we turn both into w and s into a single reasonable unary digit. (I suppose I could save a byte by using w or s as the unary digit, but that seems like a bit of a stretch.)


JavaScript (ES6), 27 bytes
f=(n,k)=>k?n*f(n-1,k-1)/k:1


JavaScript (ES6), 136 bytes

f=
n=>"/\\"+(r=s=>s[0][0].repeat(n-1)+s)`_`+r`_`+r`___/\\
`+r` `.replace(/ /g,"$`\\ \\$`   $'$'$'/ /\n")+r` \\ \\`+r`_/ /
`+r`  \\`+r`___/`
<input type=number min=1 oninput=o.textContent=f(this.value)><pre id=o>

The whole pizza is very repetitious so the r function (designed as a tagged template literal) repeats the first character of its input n times. This handles the top and bottom two lines of the pizza. The middle is repeated by replacing a string of blanks; the $` and $' subsitutions automatically correspond to increasing and decreasing numbers of blanks thus positioning the \ \ and / / appropriately.


Splitting the string into rows of 16 and then using two nested loops to go over each pixel is taking a lot of bytes to do. It would be easier to just loop over the original string and use (index%16,index//16) to point at a specific row and column.
Also, instead of specifying a background color you can just draw every single pixel, which is shorter when using hyper-neutrino's advice to use a list of colors. You can also use #000 and #FFF instead of black and white (1 byte shorter each).
Bonus tip: (16,16) can become [16]*2 (1 byte shorter)
Combining this with knosmos huge save by using data compression and makonede's suggestion to use as imports we can get this down to 353 bytes:

import base64,zlib
from PIL import Image,ImageColor as C
i=Image.new('RGB',[16]*2)
for j in range(256):i.putpixel((j%16,j//16),C.getrgb(['#000','#000','#FFF','#FFC864','red'][int(zlib.decompress(base64.a85decode(b"Garp%d1+#J#QrG=W9sOr.gFe$difq+:dD#Fi'\\kVYS/be9`DBVETlH%2Un>#OH/p!dpQBq?eAD\\o?Ok%[FUW>EJ8;cLZ6ZbI2XaB#r3e")).decode("u8")[j])]))
i.show()


PowerShell, 209 213
'/**
    $'
($i="$input")-replace'.*\( *| *\).*'-split','-ne''|%{"@param $((-split$_)[1]) $"}
,'@return $'*!($i-clike'void *')
if($i-match'\) *t'){$i-replace'.*\) *throws *'-split' *, *'|%{"@throws $_ $"}}'*/'

bash and PowerShell test scripts. but I'm probably missing a few cases still. But 22 tests are better than only one example, I guess :-)


Python, 1342 / 349 = 50.02

If I have understood the rules correctly, this should be a valid submission.

from sys import *
stdout.write("""   ABCDEFGHIJKL
  ##############
1 #from   f  i #
2 #  r   not t #
3 #      write #
4 #  s   import#
5 #  y   False #
6 #  stdout    #
  ##############
A1 from 4+5
C1 or 2+5
H1 format 6+25
K1 iter 4+10
G2 not 3+5
G3 write 5+10
C4 sys 3+5
G4 import 6+10
G5 False 5+5
C6 stdout 6+10
TOTAL 134
""".format(not False or iter([])))

You can really just keep incrementing your score by adding more identifiers: the size of the program increases linearly (by approx. twice the identifier length), while the score increases approximately by the square of the identifier length. Then the challenge becomes more how to cram most keywords into the square instead of how to write a short program to do it.


Jelly, 12 9 bytes

=“e”µ<^\O

As a program, the above code requires quotes around the input. Since that is not allowed, this is a function submission. The output is 1-based. Try it online!

How it works

=“e”µ<^\O    Monadic link. Argument: s (string)

=“e”         Check each character for equality with 'e'. Yields a Boolean array.
    µ        Start a new, monadic chain.
      ^\     Compute the array of partial reductions by XOR, i. e., the parities
             of all prefixes of the Boolean array.
     <       Check if the Booleans are strictly smaller than the parities.
             A truthy outcome indicates an off-beat quarter note.
        O    Yield all indices of 1's.

Update

The above code doesn't work anymore in the latest version of Jelly, since we need a character e, but “e” yields a string. Fixing that saves a byte, for a total of 8 bytes.

=”eµ<^\O

This works as a full program. Try it online!


Python 3, 63 bytes

lambda s,c:''.join(map(min,s,s[0]+s.title()[1:])).replace(c,'')

Try it online!


Predict whether a message will be starred or not in 50 bytes

Retina, 50 bytes, 71.8% 72.15%

^.*([[CE;ಠ-ﭏ]|tar|ol|l.x|eo|a.u|pin|nu|o.f|"$)

Tried some regex golfing at @MartinBüttner's suggestion. This matches 704 starred messages and doesn't match 739 unstarred messages.

The ^.*( ... ) is to make sure that there is always either 0 or 1 match, since Retina outputs the number of matches by default. You can score the program on the input files by prepending m` for multiline mode, then running

Retina stars.retina < starred.txt

and likewise for unstarred.txt.

Analysis / explanation

I generated the above snippets (and many more) using a program, then selected the ones I wanted manually. Here's some intuition as to why the above snippets work:

C: Matches PPCG, @CᴏɴᴏʀO'Bʀɪᴇɴ
E: Matches @ETHproductions, @El'endiaStarman
;: Because the test cases are HTML, this matches &lt; and &gt;
ಠ-ﭏ: Matches a range of Unicode characters, most prominently for ಠ_ಠ and @Doorknob冰
tar: Matches variations of star, @El'endiaStarman (again) and also gravatar which appears in the oneboxes posted by new posts bots
ol: Matches rel="nofollow" which is in a lot of links and oneboxes
l.x: Matches @AlexA., @trichoplax
eo: Mainly matches people, but also three cases for @Geobits
a.u: Mainly matches graduation, status, feature and abuse
pin: Matches ping and words ending in ping. Also matches a few posts in a discussion about pineapple, as an example of overfitting.
nu: Matches a mixed bag of words, the most common of which is number
o.f: Matches golf, conf(irm|use)
"$: Matches a double quote as a last character, e.g. @phase He means "Jenga."

The [ is nothing special - I just had a character left over so I figured I could use it to match one more case.


Perl, 81 bytes

75 bytes code + 6 for -i -n0.
Note that the \e characters are ASCII \x1b but \e is used for ease of testing.

Please note that this solution uses ANSI escape sequences and requires a compatible terminal, as well as using the -i commandline argument to pass in the number of 'dimensions' you'd like.

$n=s/^//mg-1;s/ /\e[1C/g;print(s/^/\e[${^I}C/grm."\e[${n}A"),--$^I for($_)x$^I

Usage:

In a Linux compatible terminal, run PS1= first to ensure your prompt doesn't overwrite the displayed image.

perl -i10 -n0e '$n=s/^//mg-1;s/ /\e[1C/g;print(s/^/\e[${^I}C/grm."\e[${n}A"),--$^I for($_)x$^I' <<< '
ROFL:ROFL:ROFL:ROFL
         _^___
 L    __/   [] \
LOL===__        \
 L      \________]
         I   I
        --------/
'

          ROFL:ROFL:ROFL:ROFL
         ROFL:ROFL:ROFL:ROFL
        ROFL:ROFL:ROFL:ROFL
       ROFL:ROFL:ROFL:ROFL\
      ROFL:ROFL:ROFL:ROFL\_]
     ROFL:ROFL:ROFL:ROFL\_]
    ROFL:ROFL:ROFL:ROFL\_]/
   ROFL:ROFL:ROFL:ROFL\_]/
  ROFL:ROFL:ROFL:ROFL\_]/
 ROFL:ROFL:ROFL:ROFL\_]/
   LOL==___^___]_\_\_]/
  LOL==__/ \_[]_\_\_]/
 LOL===__ \______\_]/
  L      \________]/
          I---I---/
         --------/

perl -i3 -n0e '$n=s/^//mg-1;s/ /\e[1C/g;print(s/^/\e[${^I}C/grm."\e[${n}A"),--$^I for($_)x$^I' <<< 'X X DD
 X  D D
X X DD
'
   X X DD
  X X DD D
 X X DDDD
  X XDDD
 X X DD


C (gcc), 172 bytes
#define D double
i;D f(D x){unsigned a[]={0,0};D*A=&a;D c=0;do{for(i=0;i<32;++i){*a=*a&~(1<<i)|!!(a[1]&1<<(31-i))<<i;};c=fabs(x-*A)<fabs(x-c)?*A:c;}while(++a[1]);return c;}

(Almost) purely brute-force; takes about 24 minutes per run on my machine.
f is a function that takes a double and returns the closest palindromic double. It iterates over every palindromic 64-bit sequence (as a double), storing the closing one, and returns it at the end.
This solution uses gcc on Ubuntu 16.04 32-bit, on a little-endian 32-bit single-core Pentium 4 2.8 GHz CPU.
Explanation/Ungolfed:
int i;
double f(double x) {
    unsigned int a[]={0, 0}; // a 2-array of ints is much easier to maipulate bitwise
    double *A = &a; // than a double, so refer to the same memory
    // in two different ways, a as int[2], A as double*
    double current = 0.0;
    do {
        for(i = 0; i < 32; ++i) {
            *a = ( *a&~(1<<i) )|( (!!( (a[1]&1)<<(31-i) ))<<i);
            // reverse the bits of the second half into the first half
            // (*a is shorter than a[0])
        }
        current = fabs(x-*A)<fabs(x-current) ? *A : current;
        // if *A is closer to x than current, replace c with *A
    } while (++a[1]);
    // do-while instead of while to ensure each value is tried
    // at UINT32_MAX, overflows to 0, ending the loop.
    return current;
}

A C float (binary32) version that takes ~0.0015% as long to run (about 0.02 seconds on my machine) because it checks 1/65536 as many values: (185 179 bytes)
#define F float
i;F f(F x){unsigned short a[]={0,0};F*A=&a;F c=0;do{for(i=0;i<16;++i){*a=*a&~(1<<i)|!!(a[1]&1<<(15-i))<<i;};c=fabsf(x-*A)<fabsf(x-c)?*A:c;}while(++a[1]);return c;}


05AB1E, 19 18 16 bytes
Code:
žH+b¦2äøC’c‰±’sè

Uses the CP-1252 encoding. Try it online!
Explanation:
First, we add 65536 to the number (žH is a constant defined to 65536), which is also 10000000000000000 in binary. This is to pad the number with zeroes. Let's take the number 14234 as an example. 14234 + 65536 is equal to 79770. Which in binary is:
10011011110011010

We remove the first character, resulting in:
0011011110011010

We split the string into two pieces using 2ä:
00110111, 10011010

After that, we zip the array with ø:
01, 00, 10, 11, 01, 10, 11, 10

Converting them back into decimal (using C) results in:
1, 0, 2, 3, 1, 2, 3, 2

Now, we only need to index it with the string cbad. The compressed version for this string is ’c‰±’, which can also be tested here. Finally, we get the characters at the index of the above array. For the above example, this results in:
1, 0, 2, 3, 1, 2, 3, 2
b  c  a  d  b  a  d  a


Pyth, 63 bytes
V_Q aY?}rN0"aeiou"=hZ?}N"     "=tZZ;Jh.mbYKh.MZYjC.b++*d+JNY*dK_YQ
                         ^^^^^
                         |||||
                         |tabs
                        space

The spaces in the middle is actually a single tab character, but StackExchange renders it as four spaces.
Try it online!


Implement an IEEE 754 64-bit binary floating point number through integer manipulation

C++, ~1500 chars

Expands the floats into an 8000-binary-digit fixed-point representation, does the operations on that, then converts back.

// an "expanded" float.
// n is nan, i is infinity, z is zero, s is sign.
// nan overrides inf, inf overrides zero, zero overrides digits.
// sign is valid unless nan.
// We store the number in fixed-point, little-endian.  Binary point is
// at N/2.  So 1.0 is N/2 zeros, one, N/2-1 zeros.
#define N 8000
struct E {
  int n;
  int i;
  int z;
  long s;
  long d[N];
};
#define V if(r.n|r.i|r.z)return r
// Converts a regular floating-point number to an expanded one.
E R(F x){
  long i,e=x.k<<1>>53,m=x.k<<12>>12;
  E r={e==2047&&m!=0,e==2047,e+m==0,x.k>>63};
  if(e)m+=1L<<52;else e++;
  for(i=0;i<53;i++)r.d[2925+e+i]=m>>i&1;
  return r;
}
E A(E x,E y){
  int i,c,v;
  if(x.s>y.s)return A(y,x);
  E r={x.n|y.n|x.i&y.i&(x.s^y.s),x.i|y.i,x.z&y.z,x.i&x.s|y.i&y.s|~x.i&~y.i&x.s&y.s};V;
  if(x.s^y.s){
    c=0;
    r.z=1;
    for(i=0;i<N;i++){
      v=x.d[i]-y.d[i]-c;
      r.d[i]=v&1;c=v<0;
      r.z&=~v&1;
    }
    if(c){x.s=1;y.s=0;r=A(y,x);r.s=1;}
  }else{
    c=0;
    for(i=0;i<N;i++){
      v=x.d[i]+y.d[i]+c;
      r.d[i]=v&1;c=v>1;
    }
  }
  return r;
}
E M(E x, E y){
  int i;
  E r={x.n|y.n|x.i&y.z|x.z&y.i,x.i|y.i,x.z|y.z,x.s^y.s};V;
  E s={0,0,1};
  for(i=0;i<6000;i++)y.d[i]=y.d[i+2000];
  for(i=0;i<4000;i++){
    if(x.d[i+2000])s=A(s,y);
    y=A(y,y);
  }
  s.s^=x.s;
  return s;
}
// 1/d using Newton-Raphson:
// x <- x * (2 - d*x)
E I(E d){
  int i;
  E r={d.n,d.z,d.i,d.s};V;
  E t={};t.d[4001]=1;
  for(i=N-1;i>0;i--)if(d.d[i])break;
  E x={0,0,0,d.s};x.d[N-i]=1;
  d.s^=1;
  for(i=0;i<10;i++)x=M(x,A(t,M(d,x)));
  return x;
}
// Convert expanded number back to regular floating point.
F C(E x){
  long i,j,e,m=0;
  for(i=N-1;i>=0;i--)if(x.d[i])break;
  for(j=0;j<N;j++)if(x.d[j])break;
  if(i>0&x.d[i-53]&(j<i-53|x.d[i-52])){E y={0,0,0,x.s};y.d[i-53]=1;return C(A(x,y));}
  if(i<2978){e=0;for(j=0;j<52;j++)m+=x.d[j+2926]<<j;}
  else if(i<5024){e=i-2977;for(j=0;j<52;j++)m+=x.d[i+j-52]<<j;}
  else x.i=1;
  if(x.z)e=m=0;
  if(x.i){e=2047;m=0;}
  if(x.n)e=m=2047;
  F y;y.k=x.s<<63|e<<52|m;return y;
}
// expand, do op, unexpand
F A(F x,F y){return C(A(R(x),R(y)));}
F S(F x,F y){y.k^=1L<<63;return A(x,y);}
F M(F x,F y){return C(M(R(x),R(y)));}
F D(F x,F y){return C(M(R(x),I(R(y))));}

I'm too lazy to remove all the spaces and newlines to get an exact golfed count, but it is about 1500 characters.


Python 2, 126 101 94 bytes
In the process of making this, I found that Python code may not contain literal NUL bytes.

lambda i,s='''i=%r;s=%r
try:print s%%(i[1:],s,i[0])
except:0
exit(ord(%r))''':s%(i[1:],s,i[0])

Try it online (shows the exit code in the Debug info)

Note that each of the non-empty programs below has a trailing linefeed.
For input Hello, the above outputs:
i='ello';s='i=%r;s=%r\ntry:print s%%(i[1:],s,i[0])\nexcept:print s%%(0,s,"\\0")*(i>0)\nexit(ord(%r))'
try:print s%(i[1:],s,i[0])
except:0
exit(ord('H'))

which prints
...
which prints
i='o';s='i=%r;s=%r\ntry:print s%%(i[1:],s,i[0])\nexcept:print s%%(0,s,"\\0")*(i>0)\nexit(ord(%r))'
try:print s%(i[1:],s,i[0])
except:0
exit(ord('l'))

which prints
i='';s='i=%r;s=%r\ntry:print s%%(i[1:],s,i[0])\nexcept:print s%%(0,s,"\\0")*(i>0)\nexit(ord(%r))'
try:print s%(i[1:],s,i[0])
except:0
exit(ord('o'))

which prints nothing (the empty program)

which prints nothing and exits with code 0.


Ruby, 162 bytes

->a{b=[*a=a.reduce{|x,y|[*x,*[(n=y.ord+~x[-1].ord)+n%2]*(n<1?0:2-n%2),y]}];i=-1;b.map{|x|d=-~i+=1;a.map!{|y|(z=x.to_i-(d-=1)*s=d<=>0)<1||x==b[i-s]?y:z+y.to_i}};a}

Try it online!

Takes input as an array of chars, returns a mixed array of chars/ints. (I'm still not sure whether this is allowed after reading the comments to the original post. If not allowed, it's +3 bytes to fix).

Explanation

First, we apply a reduce operation, where we aren't actually reducing anything, but rather reconstruct the array a as [*x,*[...],y], where the middle part contains the numbers inserted at ground zero.

We also make a copy of the array: b=[*a] to serve as a reference, so that we don't get confused which numbers are at the center of the explosion, and which ones are introduced later on.

Then we iterate through b and for each element x, iterate through a to record, what effect x will have on each element y of a.

Conveniently, to_i method returns 0 for non-numeric chars, so that we don't have to worry about distinction between numbers and text.

In my initial code, arrays were indexed by i and j, but this was golfed down to use a "delta" value d=i-j.

Another helper variable is the sign of the delta: s=d<=>0. At the first occurrence it performs the same function as abs, and at the second - it helps us to block the other side of one-sided explosions as in 12344321.

Ultimately, if z is estimated to be positive, we add it up with the integer equivalent of y and store in a, otherwise, y remains intact.


Solve a Diagonal Burrows-Wheeler transform

CJam, (4 + 8 = ) 12 bytes

Encoding program:

q2/z

Try it online here

Decoding program:

q_,2/)/z

Try it online here

How (or rather, why) they work:

The Diagonal Burrows-Wheeler transform is basically every other character of the string, with wrapping from the end. If we treat the String as a 2D matrix of 2 columns, it simply boils down to taking the transform of the matrix. Example:

Hello World

Is represented as 2D matrix as

He
ll
o
Wo
rl
d

Now, simply reading it column wise, give:

HloWrdel ol

Which is the Burrows-Wheeler transform.

Decoding is simply reverse of the process, write the string as a 2 row 2D matrix and read column wise.

Code expansion:

Encoder:

q          "Read the input";
 2/        "divide it into sub arrays of 2 characters";
   z       "Take transform";

Decoder:

q_,        "Read the input, take copy and get length of copy";
   2/      "Divide the length by 2";
     )/    "Increment and split the input into two rows";
       z   "Take transform";


Python, O(n log n)

I didn't golf this, because I'm competing primarily on the fastest code side of things. My solution is the heaviest_subseq function, and a test harness is also included at the bottom.

import bisect
import blist

def heaviest_subseq(in_list):
    best_subseq = blist.blist([(0, 0)])
    for new_elem in in_list:

        insert_loc = bisect.bisect_left(best_subseq, (new_elem, 0))

        best_pred_subseq_val = best_subseq[insert_loc - 1][1]

        new_subseq_val = new_elem + best_pred_subseq_val

        list_len = len(best_subseq)
        num_deleted = 0

        while (num_deleted + insert_loc < list_len
               and best_subseq[insert_loc][1] <= new_subseq_val):
            del best_subseq[insert_loc]
            num_deleted += 1

        best_subseq.insert(insert_loc, (new_elem, new_subseq_val))

    return max(val for key, val in best_subseq)

tests = [eval(line) for line in """[]
[3]
[3, 2, 1]
[3, 2, 5, 6]
[9, 3, 2, 1, 4]
[3, 4, 1, 4, 1]
[9, 1, 2, 3, 4]
[1, 2, 4, 3, 4]
[9, 1, 2, 3, 4, 5, 10]
[3, 2, 1, 2, 3]""".split('\n')]

for test in tests:
    print(test, heaviest_subseq(test))

Runtime analysis:

Each element has its insertion position looked up once, is inserted once, and is possibly deleted once, in addition to a constant number of value lookups per loop. Since I am using the built-in bisect package and the blist package, each of those operations are O(log n). Thus, the overall runtime is O(n log n).

The program works by maintaining a sorted list of best possible increasing subsequences, represented as a tuple of ending value and sequence sum. An increasing subsequence is in that list if there are no other subsequences found so far whose ending value is smaller and sum is at least as large. These are maintained in increasing order of ending value, and necessarily also in increasing order of sum. This property is maintained by checking the successor of each newly found subsequence, and deleting it if its sum is not large enough, and repeating until a subsequence with a larger sum is reached, or the end of the list is reached.


JavaScript (ES6), 43 bytes, 622 630 633

Just to get the ball rolling. Returns 1 for nouns, 0 for non-nouns.

s=>2552>>s.length&/^[bcdf-mp-tvwy]/.test(s)

How?

We bet on noun if both following conditions are met:

The word length is 3, 4, 5, 6, 7, 8 or 11. This is done by right-shifting the binary number 100111111000 (2552 as decimal).
The word starts with one of these letters: bcdfghijklmpqrstvwy


Mathematica, 221 bytes

f=(A=Pi.01Length@#2/#;l=m/.Solve[Norm[{a,b}-m{Cos@t,Sin@t}]==.1,m];k=(l/.{a->#,b->#2})&@@@#2;d=1.*^-5;For[Print[h=B=0];n=1,n<#,h+=d,(B+=If[Im@#<0,0,d(Max[#2,0]^2-Max[#,0]^2)/2])&@@@(k/.{t->h});If[B>A,n+=1;Print@h;B-=A]])&

Ungolfed:

f = (
   A = Pi .01 Length@#2/#;
   l = m /. Solve[Norm[{a, b} - m {Cos@t, Sin@t}] == .1, m];
   k = (l /. {a -> #, b -> #2}) & @@@ #2;
   d = 1.*^-5;
   For[Print[h = B = 0]; n = 1, n < #, h += d,
    (
      B += If[Im@# < 0, 0, d (Max[#2, 0]^2 - Max[#, 0]^2)/2]
    ) & @@@ (k /. {t -> h});
    If[B > A, n += 1; Print@h; B -= A]
   ]
) &

This defines a function which takes as parameters the number of slices and a list of pairs for the peperoni coordinates, like

f[8, {{0.4, 0.2}, {-0.3, 0.1}, {-0.022, -0.5}, {0.3, -0.32}}]

It will print the slices to the console as it traverses the pizza.

On most pizzas, this is fairly slow, because (to achieve the required precision) I'm integrating the peperoni area from 0 to 2π in steps of 1e-5. To get a slightly less precise result in a reasonable amount of time, you can change the 1.*^-5 at the end to 1.*^-3.

How it works

The idea is to sweep out the slices of pizza while integrating over the area of the peperoni pieces covered. Whenever that area hits the required amount of peperoni per person, we report the current angle and reset the area counter.

To obtain the peperoni area swept out, we intersect the line with the peperoni to give use the two distances from the origin, where the line intersects with the peperoni. Since a line extends to infinity in both directions, we need to clamp these distances to non-negative values. This solves two problems:

Counting intersections with each peperoni twice, once positive and once negative (which would actually yield to an overall area of 0).
Counting only wedges of peperoni pieces which include in the origin.

I'll include some diagrams later.


Ruby

I was going more for the "unorthodox" part. ;)

10;a=    gets.   split
.  map  {|       x|  #x
"%02X"  %(  x.   to_i)
}; $>   <<   ?#  <<  a[
00  ..   1+2].   join;

The font (on my web browser) is a bit tall, so it looks distorted, but it looks better in Courier New:

Sample run:

c:\a\ruby>rgb2hex
255 100 0
#FF6400


Elixir, 69 bytes

import String
&valid? replace replace(&1,<<0>>,"\xFF"),"\xC0\x80","0"

Try it online!

Makes use of built-in string validation function. Takes input as Elixir binary.


MATL, 16 bytes
tZv=Gq:"t5BZ+]vs

Try it online!
Explanation
This repeatedly applies convolution to generate the rows. For example, for input n=5 we start with the first row
0 0 0 0 1 0 0 0 0

Convolving with [1 0 1] gives
0 0 0 1 0 1 0 0 0

Repeating the operation gives
0 0 1 0 2 0 1 0 0

then
0 1 0 3 0 3 0 1 0

etc. Concatenating these arrays vertically and computing the sum of each column gives the result.
t       % Input n implictly. Duplicate
Zv      % Symmetric range. Gives [1 2 3 4 5 4 3 2 1] for input 5
=       % Equal to (element-wise). Gives [0 0 0 0 1 0 0 0 0]. This is the first row
Gq:     % Push [1 2 ... n-1]
"       % For each. This executes the following code n-1 times
  t     %   Duplicate
  5B    %   Push 5 in binary, that is, [1 0 1]
  Z+    %   Convolution keeping size
]       % End
v       % Concatenate all results vertically
s       % Sum. Display implicitly.


Python 2, 148 142 87 bytes
n=input()
p=l=1
t=1
h=2
while t!=h:
 if p==l:t,l,p=h,0,p*2
 h=h/2^h*2%2**n;l+=1
print l

Uses Brent's cycle detection algorithm, and thus actually runs fast.

I have also written an animation in Python (both 2 & 3 work). It needs pyglet to run. You can view the animation by running:
python -m pip install --user pyglet
curl -s https://gist.githubusercontent.com/orlp/f32d158130259cbae0b0/raw/ | python

(Feel free to download the gist and inspect the code before running.) You can press the + and - keys to increase/decrease the n being visualized.

And finally, for those interested in exploring this number sequence further, here is a readable version (this was used to generate the test cases above):
# Brent's cycle detection, modified from wikipedia.
def electron_period(n):
    wire_mask = (1 << n) - 1
    power = lam = 1
    tortoise, hare = 1, 2
    while tortoise != hare:
        if power == lam:
            tortoise = hare
            power *= 2
            lam = 0
        hare = ((hare << 1) ^ (hare >> 1)) & wire_mask
        lam += 1
    return lam


Haskell, 95… 93 bytes

a#n|s<-show=minimum[sum[1|(x,y)<-s a`zip`s b,x/=y]|b<-mapM(mapM(:s(56^7)))a,n==sum(read<$>b)]

Try it online!
The relevant function is (#), which takes as input the array a and the integer n and returns the minimum number of moves. Elements of a are represented as strings of digits.
How?
Standard bruteforce, we try all the possible substitutions and return the minimum number of changes. The only things I'm vaguely proud of are the show tricks I've found while working on this answer.

First of all, mapM(:show(56^7)) is shorter than mapM(\_->['0'..'9']) for enumerating all the possible digits substitutions of a single number. We save 3 bytes and we gain an exponentially slower solution.
Moreover, using show a`zip`show b instead of zip(a>>=id)$b>>=id saves another byte.
With the two previous tricks, we use the show function often enough that defining an alias for it saves an additional byte.


APL (Dyalog Extended), 39 bytes

7 7{3::0⋄(⍋,(⊢⊃⍨⍵⍳⍨⊃∘⍸¨∘=)¯1⌂kt⍺)⊇,⍳⍺}⊂

Try it online!

A version provided by @Adám.

Dyalog Extended has a shortcut to the dfns library ⌂, and a few convenience functions e.g. monadic = which is equivalent to 0∘=, and dyadic ⊇ for multiple indexing. Unfortunately an inner assignment is buggy, so we use a tacit inner function to reference the value of ¯1⌂kt⍺ twice. Otherwise we'd have a 38 byte solution:

7 7{3::0⋄(⍋,w⊃⍨⍵⍳⍨⊃∘⍸¨=w←¯1⌂kt⍺)⊇,⍳⍺}⊂

How the inner tacit function (⊢⊃⍨⍵⍳⍨⊃∘⍸¨∘=) works

This tacit function has 5 terms: `⊢`  `⊃⍨`  `⍵`  `⍳⍨`  `⊃∘⍸¨∘=`
A tacit function is grouped by 3 terms from the right:
  ⊢ ⊃⍨ (⍵ ⍳⍨ ⊃∘⍸¨∘=)
A group of 3 terms is interpreted as follows:
  (f g h)w → (f w) g (h w)     ⍝ f, g, h are functions
  (A g h)w → (A  ) g (h w)     ⍝ A is an array
Then we can interpret the above tacit function as
  (⊢ ⊃⍨ (⍵ ⍳⍨ ⊃∘⍸¨∘=))w
  → (⊢ w) ⊃⍨ (⍵ ⍳⍨ (⊃∘⍸¨∘= w))   ⍝ Expand tacit function
  → w ⊃⍨ ⍵ ⍳⍨ ⊃∘⍸¨∘= w           ⍝ ⊢ is identity function; simplify parens
  → w ⊃⍨ ⍵ ⍳⍨ ⊃∘⍸¨ = w           ⍝ (f∘g)w simply expands to f g w
So the code `(⊢⊃⍨⍵⍳⍨⊃∘⍸¨∘=)w` is equivalent to `w⊃⍨⍵⍳⍨⊃∘⍸¨=w`.

APL (Dyalog Unicode), 53 49 bytes

⎕CY'dfns'
7 7{3::0⋄(,⍳⍺)[⍋,w⊃⍨⍵⍳⍨⊃∘⍸¨0=w←¯1kt⍺]}⊂

Try it online!

Golfed 4 bytes by extracting some terms out of the dfn using a tacit form.

Original submission: APL (Dyalog Unicode), 53 bytes

⎕CY'dfns'
{3::0⋄(,⍳7 7)[⍋,w⊃⍨(⊃∘⍸¨0=w←¯1 kt 7 7)⍳⊂⍵]}

Try it online!

Because we've got a language that has a Knight's tour solver built in.

Since ¯1 kt 7 7 tries to find all solutions, it's infeasible to actually run the code as-is. For demonstration purposes, the TIO link uses 3x4 board instead.

How it works

The function dfns.kt finds a (possibly open) Knight's tour, where the right argument is the board's dimensions, and the optional left argument is the number of solutions to find. Giving -1 on the left causes the function to search all possible solutions.

⎕CY'dfns'  ⍝ Import the 'dfns' workspace

{3::0⋄(,⍳7 7)[⍋,w⊃⍨(⊃∘⍸¨0=w←¯1 kt 7 7)⍳⊂⍵]}  ⍝ ⍵←starting coordinates
                          w←¯1 kt 7 7        ⍝ Find ALL solutions of 7x7 knight's tour
                   (⊃∘⍸¨0=           )       ⍝ Extract the starting coordinates from each solution
                                      ⍳⊂⍵    ⍝ Find the index of the solution that starts at ⍵
               ,w⊃⍨                          ⍝ Fetch the solution and flatten it
      (,⍳7 7)                                ⍝ Take the flattened list of coordinates on 7x7 board
             [⍋                          ]   ⍝ Sort the coordinates by flattened solution
 3::0⋄                                       ⍝ If there's no solution starting with ⍵,
                                             ⍝ catch the Index Error and return 0 instead

Every black square on 7x7 board can be the starting location of a Knight's tour.

The following isn't directly related to the code above, but nevertheless here is a proof by example.

Starting at (0,0), Ending at (5,1)

0  11 22 45 2  13 24
21 46 1  12 23 44 3
10 27 34 39 36 25 14
47 20 37 26 33 4  43
28 9  40 35 38 15 32
19 48 7  30 17 42 5
8  29 18 41 6  31 16

Starting at (1,3), Ending at (6,4)

20 27 10 33 44 1  12
9  32 21 0  11 34 45
26 19 28 43 40 13 2
31 8  41 22 29 46 35
18 25 30 39 42 3  14
7  38 23 16 5  36 47
24 17 6  37 48 15 4

Starting at (2,2), Ending at (3,3)

30 19 40 3  28 17 38
41 2  29 18 39 4  27
20 31 0  13 10 37 16
1  42 11 48 15 26 5
32 21 14 9  12 47 36
43 8  23 34 45 6  25
22 33 44 7  24 35 46

By swapping heads and tails, reflection, and rotation, all black squares can be the starting point of some Knight's tour.

I found these three tours by splitting the board into four groups that can form a continuous loop:

O O O . O O O  |  . . . O . . .  |  . . . . . . .  |  . . . . . . .
O . O O O . O  |  . O . . . O .  |  . . . . . . .  |  . . . . . . .
O O . . . O O  |  . . . . . . .  |  . . O O O . .  |  . . . . . . .
. O . . . O .  |  O . . . . . O  |  . . O . O . .  |  . . . O . . .
O O . . . O O  |  . . . . . . .  |  . . O O O . .  |  . . . . . . .
O . O O O . O  |  . O . . . O .  |  . . . . . . .  |  . . . . . . .
O O O . O O O  |  . . . O . . .  |  . . . . . . .  |  . . . . . . .

and breaking and gluing the chains whenever needed. It's kind of a heuristic, so it would be usually shorter to hardcode the three boards or just run naive DFS.


Ruby, 176 172 205 characters
Here is another version (several chars longer) which will also run for large input in reasonable time.
q=(gets.split<<$_[/\d+$/]).map &:to_i
r=Hash.new{|h,i|h[i]=Hash.new{|h,j|h[j]=1e12;h[j]=i==j ?[0,[]]:(i...j).map{|k|a,c=r[i][k];b,d=r[k+1][j];[a+b+q[i-1]*q[k]*q[j],c+d+[k]]}.min}}
$><<r[1][q.size-1][1]*' '

First version: straight recursive implementation in Ruby. It does a complete search and thus might be slow on large inputs.
k=->m{m[2]?(1..m.size-2).map{|l|s=k[m[0,l]+m[l+1..-1]];[m[l-1]*m[l]*m[l+1]+s[0],[l]+s[1].map{|u|u<l ?u:u+1}]}.min: [0,[]]}
$><<k[(gets.split<<$_[/\d+$/]).map &:to_i][1]*' '