MATL, 152 bytes
'!Q%:5-aeo\!=XBf=H]3|X"Pj7#UGj{r_DH&!+.eFc;u4 kG9Q[rQA(^D1dW- @[E8{Ul0!AXC|MDi8}:&D(j&1_zMU.`[^HQvWoi5}*1UApz %Ld3A)N<$A*7!wBgm'F4Y2'- .;e'hZaU1&Z)i&1Yn

Output is in the same order as described in the challenge
Try it online! Or verify all test cases.
Explanation
Most of the code, '!Q%:5...!wBgm', is a compressed string containing the table. F4Y2'- .;e'hZa decompresses this into the string -611 19 ... 6.961e-6. Note that some decimals have been removed, as they are not needed to fulfill the 0.1% accuracy criterion.
The decompressed string is interpreted as an array with U. This produces the 8×4 table with the required data. The first column shown in the challenge is not needed. Then 1&Z) separates the first column from the rest.
i takes a number as input, and &1Yn applies linear interpolation using the three types of data: first column of the table, remaining columns, input. The result of the interpolation is implicitly displayed.
The input can also be a column vector, and then each row of the output refers to one of the input values. This is used for verifying all test cases at once.


Haskell, 25 bytes

zipWith(*)$scanl(*)1[1..]

Try it online!
Pretty straightforward: Generates the list of factorials [1,1,2,6,...] with a scanl, then does zipWith(*) to multiply each element of the input by the corresponding value.
32 bytes

foldr(\(i,x)r->x:map((i+1)*)r)[]

Try it online!
A pretty folding-based solution. Takes inputs as (exponent, coefficient) pairs.


Python 2, 133 119 bytes

-3 thanks to Ovs

-5 thanks to Lynn

1-indexed

j=i=0
n=input()
while n:
 j+=1;l=[];N=i
 while N:l+=N%j,;N/=j
 if{i%j}<set(l)>l==l[::-1]or j>i:n-=j<i;i+=1;j=1
print~-i

Try it online!


Brachylog, 25 bytes

⟦₂ᵐkᵐcoḅlᵒlᵍthᵐ~c{~k~⟦₂}ᵐ

Try it online!

There's an obvious structure to this answer, which becomes even more obvious if you write it like this:

{⟦₂k}ᵐc oḅ lᵒlᵍ thᵐ ~c{~k~⟦₂}ᵐ

Unfortunately, Brachylog's evaluation order makes it so that the program goes into an infinite loop if you try to take advantage of the structure in question. Still, it's certainly possible to imagine a Brachylog-like language in which this is much shorter.


As the code is rather long, it can be found here (Java 8): http://pastebin.com/Q5Buuqfx

How I did it:

Instead of brute-force creating the possible word combinations and then try to find a match I instead did the reverse and tried to collapse the target word to find the starting point. As a result the path the algorithm has to traverse is much less branched, and the words from the example can all be verified in about 35 ms (on my machine).

As a side-effect of the reverse-search I do not need the first two lines of each task (variables, terminals).

In addition I utilize the Java 8 streaming technology, which allows to easily activate parallel processing with just a single change in one line of code.

Usage: java Grammar <inputFile>

Edit: Did some code cleanup and further speed tests and it ironically turned out, that the algorithm is so fast, that setting up the parallel stream takes longer than the actual task. I now use a single-CPU stream() instead and the complete example input set is processed in ~35 ms on my machine instead of ~80 ms if I use parallelStream().

Edit2: Further testing reveals some strange effects with parallelStream and certain types of Collections. A TreeSet seems to work best in both single and parallel processing. I did some tests on your extended input set and it seems to work fine, except for the task with the looping rules (CD->DC,DC->CD). Detecting and removing those would cause the search to verify instantly.


Count characters in lo..ol and print a phrase

GolfScript, 82 characters
"What does "\,2-,{)..10/10%1=!\10%`"123"\?)*"thstndrd"2/=+}%", "*" 'o' stand for?"

Works even for >100 'o's, test it online.


Pyth, 21 bytes

#++Jw*4d.rJ".,?*&$@!%

Try it online: Demonstration

Finally a use-case for .r.

Explanation

#++Jw*4d.rJ".,?*&$@!%
#                       infinite loop
   Jw                   read a string from input and store it in J
     *4d                4 spaces
        .rJ".,?*&$@!%   rotate the chars of J using this char order
 ++                     combine the 3 strings (J, spaces, rotated) and print

The infinite loop breaks, when there is no more input available.


Check the validity of a 10-digit telephone number

APL (Dyalog Unicode), 30 29 bytesSBCS

'^\d{3}(\D*)\d{3}\1\d{4}$'⎕S⍬

It simply ⎕Searches for the PCRE regex and returns a dummy value (the empty numeric list) for each match. If none are found, it returns a single empty numeric list.

Try it online! The effect of printing a list of empty lists is to print two spaces on a line, while the effect of printing an empty list is to print an empty line. Select all contents in the Output field to reveal the spaces, or use this to lead each printed line with → and each space with ·.


Tic-tac-toe with only crosses as quick as possible

Java, 14m 31s

This is essentially the program which I posted to OEIS after using it to extend the sequence, so it's a good reference for other people to beat. I've tweaked it to take the board size as the first command-line argument.

public class A181018 {
    public static void main(String[] args) {
        int n = Integer.parseInt(args[0]);
        System.out.println(calc(n));
    }

    private static int calc(int n) {
        if (n < 0) throw new IllegalArgumentException("n");
        if (n < 3) return n * n;

        // Dynamic programming approach: given two rows, we can enumerate the possible third row.
        // sc[i + rows.length * j] is the greatest score achievable with a board ending in rows[i], rows[j].
        int[] rows = buildRows(n);
        byte[] sc = new byte[rows.length * rows.length];
        for (int j = 0, k = 0; j < rows.length; j++) {
            int qsc = Integer.bitCount(rows[j]);
            for (int i = 0; i < rows.length; i++) sc[k++] = (byte)(qsc + Integer.bitCount(rows[i]));
        }

        int max = 0;
        for (int h = 2; h < n; h++) {
            byte[] nsc = new byte[rows.length * rows.length];
            for (int i = 0; i < rows.length; i++) {
                int p = rows[i];
                for (int j = 0; j < rows.length; j++) {
                    int q = rows[j];
                    // The rows which follow p,q cannot intersect with a certain mask.
                    int mask = (p & q) | ((p << 2) & (q << 1)) | ((p >> 2) & (q >> 1));
                    for (int k = 0; k < rows.length; k++) {
                        int r = rows[k];
                        if ((r & mask) != 0) continue;

                        int pqrsc = (sc[i + rows.length * j] & 0xff) + Integer.bitCount(r);
                        int off = j + rows.length * k;
                        if (pqrsc > nsc[off]) nsc[off] = (byte)pqrsc;
                        if (pqrsc > max) max = pqrsc;
                    }
                }
            }

            sc = nsc;
        }

        return max;
    }

    private static int[] buildRows(int n) {
        // Array length is a tribonacci number.
        int c = 1;
        for (int a = 0, b = 1, i = 0; i < n; i++) c = a + (a = b) + (b = c);

        int[] rows = new int[c];
        int i = 0, j = 1, val;
        while ((val = rows[i]) < (1 << (n - 1))) {
            if (val > 0) rows[j++] = val * 2;
            if ((val & 3) != 3) rows[j++] = val * 2 + 1;
            i++;
        }

        return rows;
    }
}

Save to A181018.java; compile as javac A181018.java; run as java A181018 13. On my computer it takes about 20 minutes to execute for this input. It would probably be worth parallelising it.


Python 2, 388 392 388 346 342 336 331 bytes

z=k=input();l=len(k);v=range;u=v(l)
while l<z:
 r="";o=[r]*l;z=l
 for h in v(l):
    if r:o[h-1]=o[m]=r;m=h;r=""
    for j in v(h+1,l):
     p=k[h];q=k[j];t=u[j];n=(1.0*q*t-p*u[h])/(q-p)if q-p else""if p>0 else t
     if t<=n<r<()>o[j]>=n<=o[h]:r=n;m=j
 i=0;s=o and min(o)
 while i<l:
    if o[i]==s!="":del k[i],o[i],u[i];l-=1
    else:i+=1
print l

My god this thing is huge, but I believe it actually does work. Once you see all the intricacies of it, this challenge is ridiculously hard.

I'm not sure if I can explain how it works in detail without typing for hours, so I'll just give an executive summary.

The big main while loop is looping until the input list does not shrink.

The nested for loop (can you believe a nested for loop is actually the shortest here?) loops over each bullet speed and uses numpy.roots to calculate calculates at which time that bullet will collide with each bullet that comes after. Here, "" is being used to mean infinity (no intersection). An extra conditional has to be included to ensure that stopped bullets are marked as colliding the moment they appear rather than at time zero.

For each number we keep track of which bullet it will hit soonest, if any, and then o is updated with the minimum collision times for the involved bullets.

After this double loop terminates, we iterate over the input list and delete any bullet that will collide at the minimum of all collision times, if any. This allows us to simultaneously delete large numbers of bullets if they all happen to collide at the same moment.

Then we repeat the entire process on the remaining bullets, since they may be able to get by now that the bullets that they would have collided with have been destroyed.

As soon as no bullets are deleted (indicated by the list not shrinking), we escape the while loop and print the length of the remaining list. Thus, this program not only prints truthy if bullets survive, it actually prints exactly the number of bullets that survive.

EDIT: Special thanks to feersum for generating test cases to help me find bugs.

EDIT 2: Saved 42 bytes by solving the linear equation by hand instead of using numpy, and splitting out the starting times into a separate list and restructuring a conditional.

EDIT 3: Saved 4 bytes by renaming range

EDIT 4: Saved 6 more bytes by replacing double spaces with tabs.
Also, feersum was kind enough to provide his implementation using fractions and sets for comparison. I've golfed it a bit and it comes out to 331 bytes, tying my solution.

EDIT 5: saved 5 bytes by removing an unnecessary initialization and rewriting a conditional


Python 3, generates Stax

This uses a variety of strategies.  Most strategies only apply under certain conditions, but there's one fallback strategy that is always usable.  At the end, the smallest candidate program is selected.

from functools import reduce
from math import sqrt

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

def uncycle(arr):
    for size in range(1, len(arr)):
        if all(e == arr[i % size] for (i, e) in enumerate(arr)):
            return arr[:size]
    return arr

def constant(val):
    return "A" if val == 10 else str(val)

def shift(val):
    if not val: return ""
    return constant(abs(val)) + "+-"[val < 0]

def encode(a, offsetMode):
    result = "";
    if offsetMode:
        for i in range(len(a) - 1, 0, -1):
            a[i] -= a[i - 1]
    for i in range(len(a)):
        parts = []
        signBit = (a[i] < 0) * 2
        continuing = (offsetMode and i == len(a) - 1) * 1
        remain = abs(a[i])
        while remain > 22:
            parts.insert(0, remain % 46 * 2 + continuing);
            remain //= 46
            continuing = 1

        parts.insert(0, remain * 4 + signBit + continuing)
        result += "".join(symbols[p] for p in parts)

    return result

def cram(arr):
    flat = encode(arr, False)
    offset = encode(arr, True)
    return offset if len(offset) < len(flat) else flat;

def issquare(num):
    root = int(sqrt(num))
    return root * root == num

def isgeometric(arr):
    r = arr[0]
    return all(r ** (i + 1) == e for (i,e) in enumerate(arr))

def generateProgram(arr):
    candidates = []
    rotated = uncycle(arr)
    rotated = rotated[-1:] + rotated[:-1]

    deltas = [b - a for a,b in zip(arr, arr[1:])]

    # single constant strategy
    if len(arr) == 1:
        candidates.append(constant(arr[0]))

    # repeated constant
    elif len(set(arr)) == 1:
        num = arr[0]
        if num == 10: candidates.append("A")
        if num % 2 == 0: candidates.append(constant(num // 2) + "H")
        if issquare(num): candidates.append(str(int(sqrt(num))) + "J")
        candidates.append(constant(num - 1) +  "^")

    # repdigit
    if len(arr) == 2 and 10 < arr[1] == arr[0] * 11 < 100:
        candidates.append(str(arr[0]) + "p")

    # single digits
    if max(arr) < 10:
        candidates.append("".join(map(str, rotated)) + "E|X@")

    # max 10
    if max(arr) == 10 and rotated[0] != 1:
        candidates.append("".join(str(e - 1) for e in rotated) + "E|X@^")

    fns = [
        ("", lambda x: x),
        ("H", lambda x: 2 * x),
        ("^", lambda x: x + 1),
        ("J", lambda x: x * x),
        ("Hv", lambda x: 2 * x - 1),
        ("H^", lambda x: 2 * x + 1),
        ("^H", lambda x: 2 * x + 2),
        ("HJ", lambda x: 4 * x * x),
        ("JH", lambda x: 2 * x * x),
        (":T", lambda x: x * (x + 1) / 2),
        ("|F", lambda x: reduce(lambda a, b: a*b, range(1, x+1))),
        ("J^", lambda x: x * x + 1),
        ("^J", lambda x: x * x + 2 * x + 1),
    ]
    for (stax, fn) in fns:
        if all(fn(i + 1) == e for (i,e) in enumerate(arr)):
            candidates.append("|X" + stax)

    # fixed delta
    if len(set(deltas)) == 1:
        delta = deltas[0]
        start = arr[0] - delta
        if start == 0:
            candidates.append(shift(delta))
        if delta == 1:
            candidates.append("|X" + shift(start))
        elif delta == -1:
            candidates.append("|x" + shift(start))
        elif delta > 1:
            candidates.append("|X" + constant(delta) + "*" + shift(start))
        elif delta < -1:
            candidates.append("|x" + constant(-delta) + "*" + shift(start))

    # geometric series
    if isgeometric(arr):
        candidates.append(constant(arr[0]) + "*")

    # prefix
    if len(arr) == 2 and arr[1] // 10 == arr[0] < 10:
        candidates.append("." + str(arr[1]) + "|X(")

    # suffix
    if len(arr) == 2 and arr[0] % 10 == arr[1] < 10:
        candidates.append("." + "".join(map(str, arr)) + "|X)")

    # uncycled cram
    candidates.append('"' + cram(rotated) + '"!|X@')

    candidates.sort(key=len)
    return candidates[0]

while True:
    arr = eval(input())
    prog = generateProgram(arr)
    print(prog)

Try it online!

Update: Validation  It will be time consuming to execute each multiplicity of each program separately.  It's possible to run them all at the same time.  In order to do this, a small piece of code must be used.  It's responsible for a few things.

Do implicit output if any.  Normally, at the end of a stax program, the top of stack is printed if there has been no other output.  When running multiple programs in the same source file, this must be done explicitly.
Clear both stacks.
Reset registers.  For these programs only the x register is used.

This boilerplate should be applied after every individual program to be executed.

|d{P}{zP}?0XLd

For example, the input [5,2,7,3] produces the stax program 3527E|X@.  All four multiplicities can be tested at once.

3527E|X@
|d{P}{zP}?0XLd

3527E|X@3527E|X@
|d{P}{zP}?0XLd

3527E|X@3527E|X@3527E|X@
|d{P}{zP}?0XLd

3527E|X@3527E|X@3527E|X@3527E|X@
|d{P}{zP}?0XLd

Try it online!

In this way, it's possible to test all the multiplicities of all the program in the same run, assuming nothing breaks.  It would probably be the largest stax program ever executed if all 500 are done.


Perl: 46 → 36 or 27 characters

perl -pe's|((.)\2*)|@x=split//,$1;@x.$x[0]|eg'

All hail @ardnew for coming up with the idea of using the tr///c operator to count the number of characters in the matched string instead of splitting:

perl -pe's|((.)\2*)|$1=~y///c.$2|eg'

Degolfed:

while(defined($_ = <>)) {
  $_ =~ s{((.)\2*)}           # match 1 or more consecutive identical non-newlines
         {
           ($1 =~ y///c )     # count the number of characters in $1
           .                  # and concatenate it
           $2                 # with the first matched character
         }eg;                 # execute substitution, match "global"
  print $_;                   # print the modified line
}

Usage:

$ perl -pe's|((.)\2*)|$1=~y///c.$2|eg' infile

or via STDIN

$ perl -pe's|((.)\2*)|$1=~y///c.$2|eg'
heeeello

prints

1h4e2l1o


Special Character Coding Challenge - Check string for validity (Lots of rules)

Raku, 41 bytes

{?/^[\s*\!?\s*\d+\.?\d*\s*]+%<[%&#$!]>$/}

Try it online!

Checks if the input matches against a regex.

Explanation:

{?/^                                 $/}  # Check if the input is
    [                     ]+  # A series of
        \!?                   # An optional ! followed by
              \d+\.?\d*       # A number
     \s*   \s*         \s*    # Interspersed with optional whitespace
                            %           # Joined by
                             <[    ]>   # Any of
                               %&#!     # The special characters


MATL, 15 14 10 bytes
3#fbb+y=*s

The input has rows separated by ;. For example: [1 5 2; 9 4 2; 5 9 6]. 1-based indexing is used.
Try it online! Or verify all test cases.
Explanation
I'll use the example with input [3 -1 3 3; 3 -1 3 1] in the explanation.
3#f    % Three-output find: for all nonzero values of implicit input matrix, pushes
       % three column vectors with row indices, column indices, and values
       %   Stack contains: [1;2;1;2;1;2;1;2], [1;1;2;2;3;3;4;4], [3;3;-1;-1;3;3;3;1]
bb     % Bubble up twice: move vectors of row and column indices to top
       %   Stack contains: [3;3;-1;-1;3;3;3;1], [1;2;1;2;1;2;1;2], [1;1;2;2;3;3;4;4]
+      % Element-wise sum of top two arrays
       %   Stack contains: [3;3;-1;-1;3;3;3;1], [2;3;3;4;4;5;5;6]
y      % Duplicate the vector of nonzero values onto the top of the stack
       %   Stack contains: [3;3;-1;-1;3;3;3;1], [2;3;3;4;4;5;5;6], [3;3;-1;-1;3;3;3;1]
=      % Element-wise equality test of top two arrays
       %   Stack contains: [3;3;-1;-1;3;3;3;1], [0;1;0;0;0;0;0;0]
*      % Element-wise multiply of top two arrays
       %   Stack contains: [0;3;0;0;0;0;0;0]
s      % Sum of array
       %   Stack contains: 3


Convert Magic the Gathering colours to a Colour based deck name

05AB1E, 136 135 133 132 bytes
“ƒÏˆ¨†¾‡—„¸ ŽÌ“#'Î×ì.•вO₁ŸĀ0Ðëœ´0+Eм/#‰TôbHüÆΣÇÐζfβq₅([²åOÇηB₂È¥ƶ]9í$µÅ–tå(h0!Ãα9½êT₄Ì€+µxΩ;'Äçî9©ÙÝ“R_Ÿ U„δ
ÅíÂu•#5ǝ˜.•Iλβ•æé¦Il{kè

Outputs in full lowercase; uses the shortest outputs if multiple are allowed.
Try it online or verify all test cases (uses a random permutations for each test case input).
Explanation:

“ƒÏˆ¨†¾‡—„¸ ŽÌ“ # Push dictionary string "black green red blue white  brown"
 #              # Split it on spaces: ["black","green","red","blue","white","","brown"]
  'Î×ì         '# Prepend dictionary string "mono" to each string
.•вO₁ŸĀ0Ðëœ´0+Eм/#‰TôbHüÆΣÇÐζfβq₅([²åOÇηB₂È¥ƶ]9í$µÅ–tå(h0!Ãα9½êT₄Ì€+µxΩ;'Äçî9©ÙÝ“R_Ÿ U„δ\nÅíÂu•
                # Push compressed string "golgari rakdos gruul dimir simic izzet orzhov selesnya boros azorius jund ana grixis rug abzan dega naya esper bant raka chaos dune witch yore ink domain"
 #              # Split on spaces as well
  5ǝ            # Insert this list at 0-based index 5
    ˜           # And flatten the list to complete the list of deck-names
.•Iλβ•          # Push compressed string "bgruw"
      æ         # Pop and push all its permutations
       é        # Sort them by length: ["","b","g","r","u","w","bg","br","gr","bu","gu","ru","bw","gw","rw","uw","bgr","bgu","bru","gru","bgw","brw","grw","buw","guw","ruw","bgru","bgrw","bguw","bruw","gruw","bgruw"]
        ¦       # Remove the first empty string
I               # Push the input-string
 l              # Convert it to lowercase
  {             # Sort its characters
   k            # Get the index of this string in the list of permutations,
                # or -1 if it isn't present in the case of input "c"/"C"
    è           # And use that index to index into the list of deck-names
                # (0-based, where -1 will wrap around to the end)
                # (after which the result is output implicitly)

See this 05AB1E tip of mine (sections How to use the dictionary? and How to compress strings not part of the dictionary?) to understand how the compressed strings work.


Build interpreter for non-existent language


Python 2, 67 bytes

f=lambda l:l and[l[:x]for i,x in enumerate(l)if-~i==x][:1]+f(l[1:])

Try it online!


Python 2, 476 bytes

import re
c=[[i]*9for i in range(6)]
r=lambda f:[f[a+b]for a in(0,1,2)for b in(6,3,0)]
U=lambda c:[r(c[0])]+[c[j+1][:3]+c[j or 4][3:]for j in(1,2,3,0)]+[c[5]]
y=lambda c:[r(c[0])]+c[2:5]+[c[1],r(r(r(c[5])))]
z=lambda c:[c[2],r(r(r(c[1]))),c[5],r(c[3]),c[0][::-1],c[4][::-1]]
s=input()
exec("c="+"(c);c=".join("".join("zzzUz U zzUzz yyyzUzzzy zUzzz yzUzzzyyy".split()[ord(t)%11%7]*sum(map(int,n))for t,n in re.findall("([BUDLFR])(\d*)",s[:-2])))+"(c)")
print sum(c[int(s[-1])])

Try it online!
A port from my Simulate A Rubik's Cube answer. The revisit prompted me to golf that by 47 bytes.


Java, 1093 1058 1099 1077 chars

public class F{double r,i,a,b;F(double R,double I){r=R;i=I;}F a(F c){return
new F(r+c.r,i+c.i);}F m(F c){return new F(r*c.r-i*c.i,r*c.i+i*c.r);}F
r(){a=r*r+i*i;return new F(-r/a,i/a);}double l(F c){a=r-c.r;b=i-c.i;return
Math.sqrt(a*a+b*b);}public static void main(String[]a){int
n=a.length,i=0,j,x,K=1024,r[]=new int[n];String o="P3\n"+K+" "+K+"\n255 ",s[];F z=new
F(0,0),P[]=new F[n],R[]=new F[n],c,d,e,p,q;for(;i<n;)P[i]=new
F((s=a[i++].split("i"))[0].isEmpty()?0:Float.parseFloat(s[0]),s.length==1?0:Float.parseFloat(s[1]));double
B=Math.pow(P[n-1].m(P[0].r()).l(z)/2,1./n),b,S;for(i=1;i<n;){b=Math.pow(P[i].m(P[i-1].r()).l(z),1./i++);B=b>B?b:B;}S=6*B/K;for(x=0;x<K*K;){e=d=c=new
F(x%K*S-3*B,x++/K*S-3*B);for(j=51;j-->1;){p=P[0];q=p.m(new
F(n-1,0));for(i=1;i<n;){if(i<n-1)q=q.m(c).a(P[i].m(new
F(n-1-i,0)));p=p.m(c).a(P[i++]);}c=c.a(d=q.r().m(p));if(d.l(z)<S/2)break;}i=j>0?0:n;for(;i<n;i++){if(R[i]==null)R[i]=c;if(R[i].l(c)<S)break;}i=java.awt.Color.HSBtoRGB(i*1f/n,j<1||e.l(c)<S&&r[i]++<1?0:1,j*.02f);for(j=0;j++<3;){o+=(i&255)+" ";i>>=8;}System.out.println(o);o="";}}}

Input is command-line arguments - e.g. run java F 1 0 0 -1. Output is to stdout in PPM format (ASCII pixmap).

The scale is chosen using the Fujiwara bound on the absolute value of the complex roots of a polynomial; I then multiply that bound by 1.5. I do adjust brightness by convergence rate, so the roots will be in the brightest patches. Therefore it's logical to use white rather than black to mark the approximate locations of the roots (which is costing me 41 chars for something which can't even be done "correctly". If I label all points which converge to within 0.5 pixels of themselves then some roots come out unlabelled; if I label all points which converge to within 0.6 pixels of themselves then some roots come out labelled over more than one pixel; so for each root I label the first point encountered to converge to within 1 pixel of itself).

Image for the example polynomial (converted to png with the GIMP):


Find all diagonal counts in only one direction

Jelly, 41 37 bytes

æ.µṬ+ḢṬ$+⁴²x@0¤s⁴µŒD;UŒD$ṣ€1Ẏ=2Ẹ$ƇF¬S

Try it online!

A dyadic link that takes as its left argument the zero-indexed positions of the queen and any soldiers as a list (queen first, any subsequent entries a solider) and as right argument the board size. Returns an integer that represents the number of squares available for moves on the diagonal.

Explanation

æ.                                    | dot product of piece positions with board size, right-padded with 1
  µ                                   | start new chain with this as input
   Ṭ                                  | make a boolean array with 1 at the position of each piece
    +ḢṬ$                              | and add the same again for the Queen so the Queen has a 2
        +⁴²x@0¤                       | expand to the board dimension square with zeroes
               s⁴                     | split into lists the length of the board dimension
                 µ                    | start a new chain
                  ŒD;UŒD$             | concatenate the diagonals and the diagonals of the flipped board
                         ṣ€1          | split at soldiers
                            Ẏ         | tighten (make a single list of lists)
                             =2Ẹ$Ƈ    | filter keeping only those diagonals with the Queen in
                                 F¬S  | count the number of zeroes


Mathematica, 50 bytes
1-indexed
(Riffle@@(#&@@RealDigits[#,10,5!]&/@{Pi,E}))[[#]]&


APL (Dyalog Extended), 28 25 24 bytes

Anonymous tacit prefix function. Argument and result are 2-column matrices of day numbers since an epoch, each row representing a range.

1 ¯1+⍤1∘{⍵⌿⍨1<-⍨/⍵}1⌽⍢,∧

Try it online! The In pre-processor function converts from a list of pairs of 3-element lists (dates in ISO order) to a 2-column matrix of IDNs, International Day Numbers (days since 1899-12-31). The Out post-processor function converts from a matrix of IDNs to a matrix of 3-element lists.

∧ sort rows ascending

1⌽ cyclically rotate the dates one step left
 ⍢, while ravelled (flattened) — afterwards, reshape back to original shape

1 ¯1+ add one and negative one
⍤1 using that list for each row
∘ of the result of
{…} the following lambda:
 ⍵ the argument
 -⍨/ subtract left-hand date from right-hand date, row-wise
 1< mask where differences exceed one (i.e. where ranges are not adjacent)
 ⍵⌿⍨ filter the rows by that mask


Mathematica, 25 bytes

<<Combinatorica`
GraphicQ

Yeah, another builtin. (Takes the input as a list of positive integers.) Requires loading the Combinatorica package.


JavaScript
Work in progress. Unfortunately the maze is not always solvable - the limit on back-forward is the real hurdle.
Edit 1 Cosmetic
Edit 2 Better gameplay, but the big problem is still there

var rows, columns, rowOfs, maze, plPos, points, playing

$('#BNEW').on('click', function() {
    NewMaze();
});
$('#BREP').on('click', function() {
    Start();
});

$(document).on('keydown', function(e) {
    var ok, move, pxy, mz, $td
    switch (e.which)
    {
    case 37:
        (move = -1, ok = maze[plPos+move] < 9 && maze[plPos+move*2] < 9);
        break;
    case 39:
        (move = 1, ok = maze[plPos+move] < 9 && maze[plPos+move*2] < 9);
        break;
    case 38:
        (move = -rowOfs, ok = maze[plPos+move] < 9 && maze[plPos+move*2] < 9);
        break;
    case 40:
        (move = rowOfs, ok = maze[plPos+move] < 9 && maze[plPos+move*2] < 9);
        break;
    }
    if (playing && ok)
    {
        pxy = getXY(plPos)
        mz = maze[plPos] < 8 ? 8 : 9;
        $td = $('#Field table tr').eq(pxy.y).find('td').eq(pxy.x)
        $td.addClass("m"+mz);
        maze[plPos] = mz;
        maze[plPos+move] = mz;
        plPos += move*2;
        mz = maze[plPos];
        PTS.value = mz==7 ? points += 20 : mz==6 ? points += 50 : mz == 8 ? points -= 1 : points;

        pxy = getXY(plPos)
        $td = $('#Field table tr').eq(pxy.y).find('td').eq(pxy.x)
        $td.removeClass("m6 m7")
        $('#Player').finish().animate(playerCss(pxy.x,pxy.y));
        CheckEndGame();
    }
    return !move
});

function CheckEndGame()
{
  var msg = ''
  if (maze[plPos] == 5)
  {
      msg = "Maze completed!";
  }
  else if (maze[plPos+1]==9 && maze[plPos-1]==9
        && maze[plPos+rowOfs]==9 && maze[plPos-rowOfs]==9)
  {
      msg = "You are stuck, try again!";
  }
  if (msg) {
    $("#Msg").text(msg).show();
    playing=false
  }
}

function seed(s) {
    return function() {
        s = Math.sin(s) * 10000; return s - Math.floor(s);
    };
};

function Build()
{
    var i
    var Fill = function(p)
    {
        var d=[rowOfs,-rowOfs,1,-1], i, s, l
        maze[p] = 1
        while(d[0])
        {
            i = random()*d.length|0
            s = d[i]
            if (s != (l=d.pop())) d[i]=l
            if (maze[p+s+s]>8) {
                maze[p+s] = 1, Fill(p+s+s)
            }
        }
    }
    rowOfs = (columns + 1) * 2
    maze = Array(rowOfs * (rows*2+1))
    for (i=0; i < maze.length; i++)
        maze[i] = i % rowOfs? 9 : 0
    Fill(rowOfs+2)
}

function NewMaze()
{
    SEED.value = Math.random()*65536 | 0
    Start()
}

function Start()
{
    var sd = SEED.value || 1
    columns = COLS.value |0 || 18
    rows = ROWS.value | 0 || 12
    COLS.value = columns
    ROWS.value = rows
    random = seed(sd)
    PTS.value = points = 0
    $("#Msg").hide();

    Build()

    plx = random()*columns|0;
    ply = random()*rows|0;
    setPlayer(plx,ply);
    plPos = getPos(plx,ply);
    BlockTriples(plPos);
    AddItems(plPos);
    Draw();
    playing = true;

}

function AddItems(p)
{
    var d=[rowOfs,-rowOfs,1,-1]
    var cells=[]
    // scan all reachable cells and calc distance from start
    var Go = function(p,l)
    {
        var i,t,mark,r
        ++l
        cells.push([p,l])

        maze[p] = 8;
        for(i=0; d[i]; i++)
        {
            t = d[i]
            if (maze[p+t]<2 && maze[p+t+t]<2)
            {
                Go(p+t+t, l)
            }
        }
        maze[p] = 0;
    }
    Go(p,0)
    cells.sort(function(a,b){return a[1]-b[1]})
    cells=cells.slice(10) // cut the shortest distances
    r = random()*10|0; //exit
    r = cells.length-r-1
    maze[cells[r][0]] = 5;
    console.log(r)
    cells = cells.slice(0,r)
    var ncr = rows, nnu = columns
    for(i = ncr+nnu; i; i--)
    {
        r = random()*cells.length|0
        maze[cells[r][0]] = (i > ncr ? 7 : 6);
        cells[r] = cells.pop();
    }

}

function BlockTriples(p)
{
    var d=[rowOfs,-rowOfs,1,-1]
    var Go = function(p)
    {
        var i,t,size=[0,0,0,0],s=1,nw=0,min,minp
        maze[p] = 8
        for(i=0; d[i]; i++)
        {
            t = d[i]
            if (maze[p+t]<9 && maze[p+t+t]<8)
            {
                ++nw
                s += size[i] = Go(p+t+t)
            }
        }
        if (nw > 2) // triple way, block the smallest
        {
            for(i=0,min=1e6; d[i]; i++)
                size[i] && size[i] < min && (min = size[minp = i])
            maze[p + d[minp]] = 5;
        }
        maze[p]=0
        return s
    }
    Go(p)
}

function Draw()
{
    var q=[], i, x, y;
    for(i = rowOfs+2, y = 0; y < rows; y++)
    {
        q.push('
')
        for (x = 0; x < columns; i += 2, x++)
        {
            tcl = 'm'+(maze[i]|0)
            maze[i-1]>8 && (tcl += ' wl')
            maze[i+1]>8 && (tcl += ' wr')
            maze[i-rowOfs]>8 && (tcl += ' wu')
            maze[i+rowOfs]>8 && (tcl += ' wb')
            q.push('	')
        }
        q.push('
')
        i += rowOfs+2
    }
    $("#TOUT").html(q.join(''));
    $("#Field").show();
}

function setPlayer(posx, posy)
{
    $('#Player').css(playerCss(posx, posy));
}

function getXY(pos)
{
    return { x: (plPos % rowOfs)/2-1, y: plPos / rowOfs / 2 | 0}
}

function getPos(x, y)
{
   return (x+y*rowOfs)*2 + rowOfs+2;
}

function playerCss(posx, posy)
{
    return{ left: 6+posx*21, top: posy*21+2};
}
input { width: 3em; margin-right:1em }
table {
  border: 2px solid #000;
  border-collapse: collapse;
  font-size: 8px }
#Field {
  margin: 10px;
  position: relative;
  display: none;
}
td {
    width: 19px; height: 19px;
    padding: 0; margin: 0;
    text-align: center;
}
td.wl { border-left: 2px solid #444; background: #fff }
td.wr { border-right: 2px solid #444; background: #fff }
td.wt { border-top: 2px solid #444;; background: #fff }
td.wb { border-bottom: 2px solid #444; background: #fff }
td.m7 { background: #ffd url(http://i.stack.imgur.com/QUInh.png) -21px 0}
td.m6 { background: #efe url(http://i.stack.imgur.com/QUInh.png) -1px 0}
td.m5 { background: #ddf url(http://i.stack.imgur.com/QUInh.png) -40px 0}
td.m8 { background: #eed }
td.m9 { background: #f55 }
#Player { position: absolute; top:0; left:0; color: #007; background: #fcb; font-size:12px }
#Msg { color: red; font-size:40px; display:none;  }

ID:<input id=SEED>
Rows:<input id=ROWS>
Columns:<input id=COLS>
<button id=BNEW>New</button>
<button id=BREP>Replay</button>

⛄

Score: <input readonly id=PTS>


Cardinal Numbers in Standard American English

R - 54

sum(nchar(gsub("[^o]","",english::english(1:scan()))))

I get 41 for n=101. I hope someone can confirm.


JavaScript (E6) 336 344 356 369 424 478 522 570
Edit 6 Last edit was buggy. Bug fix and shortened. That's all I hope.
Edit 5 Finally found a way to get rid of multiply by 23 - bothered me from start. Plus another change to the input (@William shout when it's too much). Now the function expects one array parameter, containing 2 subarrays. Without this change it's 349 - still an improvement
Edit 4 Shaved some more bytes and a little change to input format.
With the new input format a missing class is represented as an empty array element. So D([1,,2,3,1],[,3,1,1,2]) instead of D([1,0,2,3,1],[0,3,1,1,2]). I think it still obeys the rules.
Edit 3 Golfed more. No changes to the algorithm, but abusing a lot of array.map and local functions to avoid for loops.
Edit 2 String compression, the right way ...
Edit Added string compression, a lot of work and not much gained. Now the mirror stickmen are generated from a template, not stored.
Made a few tries, first running. To be golfed.
NB Kolmogorow-business still to be tackled.
Test In FireFox console. Change 'return' with Add 'alert(...)' to have an output statement (albeit not useful at all)
console.log(D([[1,,2,3,1],[,3,1,1,2]]))
Output
         .       .                                                                 .
       .' *.   .' *.                                                             .* '.
       ' O *   ' O *      O  /   O  /   O  /    O A        A O  A O    \  O      * O '     O   O   O
 O    ' \|/ . ' \|/ .   |/|\/  |/|\/  |/|\/    /|\|        |/|\ |/|\    \/|\|   . \|/ '   /|\ /|\ /|\
/|\   .  |  * .  |  *   | |    | |    | |       | |        | |  | |       | |   *  |  .    |   |   |
/ \   './ \*. './ \*.    / \    / \    / \     / \|        |/ \ |/ \     / \    .*/ \.'   / \ / \ / \
¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯

Golfed Code
D=a=>
  (J=v=>v.join(''))((l=[r=n=' ',3,6,13,19,23]).map(_=>f=(F=f=>J(a[f].map((c,q)=>
  ("9.299.' *.87O2' O *3O21 O A O 1|0' 0|1 .|1|01 1|0|1|0 | .2|2*| |4| |1 01 0'.1 0*. 1 021 0|"[R='replace'](/[2-9]/g,x=>n.repeat(x))
   .slice(l[q]-r,l[q+1]-r)[R](/\d/g,x=>'\\/'[x^f])+n).repeat(c)+n+n
  ))+n)(0)+J([...F(1)].reverse(r-=23))+'\n'))+f[R](/./g,'¯')

Code (edit 2)
D=(a,b)=>{
  F=(s,f)=>(s=s[R](/\d/g,x=>'/\\'[x^f]),f?s:[...s].reverse().join('')),
  v="9.299.' *.87O2' O *3O21 O A O 1|0' 0|1 .|1|01 1|0|1|0 | .2|2*| |4| |1 01 0'.1 0*. 1 021 0|"
    [R='replace'](/\d/g,x=>x>1?' '.repeat(x):x),
  l=[0,3,6,13,19,23];
  for(o='',r=0;v[r];r+=23,f=F(z,1)+'  '+F(w,0),o+=f+'\n',f=f[R](/./g,'¯'))
    for(z=w=p='';p<10;++p)
      if(c=(p<5?a:b)[q=p%5])x=(v.slice(r+l[q],r+l[q+1])+' ').repeat(c)+'  ',p<5?z+=x:w+=x
  return o+f
}

Ungolfed code (1st version)
D=(a,b)=>{
  v="         .                .                    .' *.            .* '.               O  ' O *   O  / O A * O ' \\  O  A O  O /|\\' \\|/ .|/|\\/ /|\\|. \\|/ ' \\/|\\||/|\\/|\\ | .  |  *| |    | |*  |  .   | || | / \\/ \\'./ \\*. / \\  / \\|.*/ \\'.  / \\ |/ \\"
  l=[0,3,6,13,19,23,30,36,40]
  o=''
  for(r=0;r<6;++r)
  {
    z=w=''
    for(p=0;p<10;p++)
    {
      c=a[p]||b[p-5];
      if (c)
      {
        q = p<7 ? p%5 : p-2
        x = (v.slice(r*40+l[q],r*40+l[q+1])+' ').repeat(c)
        if (p<5)
          z+=x+'  ';
        else
          w=x+'  '+w
      }
    }
    f = z + '     ' + w
    o += f + '\n'
    f = '¯'.repeat(f.length-3)
  }
  return o+f
}


C, 796 754 712 703 692 685 682 670 666 662 656 648 chars

Changelog:

754->712: Added return to the #define, replacing if with ? statements (thanks @FUZxxl), removing int from the functions parameter list.
712->703: Shameless copy from bunnit again :) Moved the whole image creation into the #define
703->692: Merged p[] and h[], some more ?: improvements
692->685: Incrementing b so i isn't needed anymore. m=b instead of m=11 and n<2e3 instead of i<356 - these are close to undefined behaviour/memory corruption, but it seems I'm lucky :)
685->682: k is now (32,16,8,4,2,1,0) instead of (5,4,3,2,1,0). Gotcha, D C ;)
682->670: Split p[] and h[], converted h[] to a char* - awwww, there's a sleepy kitty in it ^<+_=>-
670->666: while => for, l=l*2+... => l+=l+...
666->662: m=m>9?... => c[n++]=m>9?...
662->656: Reversed bit order in b[], so we can map to 64-127 instead of 0-63 and don't need bit index k anymore. Thanks @Piotr Tarsa. Replaced ?: (GCC extension) with ||. Thanks @JamesB
656->648: Shameless copy from Shelwien :) (multi-character constants for p[])

Image is converted to a Base64-like string (ASCII 37-100), using huffman coding to encode colors 0-9 using 3-6 bits and a special color 10 (pixel is same as previous one) using only 1 bit.

#define P (x,y){for(;n<2e3;j/=2){j>1||(j=*b+++27);l+=l+(j&1);for(m=0;m<11;m++)l-h[m]+32||(c[n++]=m>9?c[n-1]:m,l=0,m=b);}return 255&p[c[x+y*32]]
char*h="$^<+_=>-,* ",*b="F0(%A=A=%SE&?AEVF1E01IN8X&WA=%S+E+A-(,+IZZM&=%]U5;SK;cM84%WE*cAZ7dJT3R.H1I2@;a^/2DIK&=&>^X/2U*0%'0E+;VC<-0c>&YU'%],;]70R=.[1U4EZ:Y=6[0WU4%SQARE0=-XDcXd_WW*UAF&cFZJJ0EV*(a(P05S3IXA>51cH:S5SAE6+W%/[]7SF(153UM]4U()(53DA+J:]&5+5KX,L6>*4I,/UMBcML9WKLa9%UYIHKWW(9-*):(-ZW(9%T'N&9;C,C/Ea/Y7(JJ\\6CD9E,2%J*,ac]NIW8(M=VFac)/^)?IS-;W&45^%*N7>V,,C-4N35FMQaF,EaWX&*EJ4'";p[]={0,'R@+','aXL',7783255,'4k`',16354410,'NNv',5295994,4671418,9975021},c[1024],j,l,m,n;red P;}blue P>>16;}green P>>8;}

Copied two things from bunnit's answer, the #define and the whole image being decoded completely every time red/green/blue are called. There's some room for additional improvement, so expect some updates :) I'm not sure about code compliance, used GCC 4.6.1 to compile and test.

Compression-wise, I think arithmetic coding would help as the distribution is pretty skewed, but maybe code overhead would be too heavy in this case. LZW also should do a very good job. Colors are quite local, so adaptive coding might be an idea.

More readable 754 character version with some comments:

#define P 255&p[c[x+y*32]]
// Base64 coded image bitstream, ASCII 37-100
// Huffman codes: 100, 111110, 11100, 1011, 111111, 11101, 11110, 1101, 1100, 1010, 0
char b[]="FYU%3+3+%B&E;3&HF1&Y1.JWXE83+%B=&=3)U]=.PP*E+%,('?B>?D*Wa%8&MD3P7dNbARIV1.Q[?4L9Qc.>E+EKLX9Q(MY%5Y&=?HC_)YDKE0(5%,]?,7YR+I@1(a&PO0+G@Y8(a%B23R&Y+)XcDXd<88M(3FEDFPNNY&HMU4UZY'BA.X3K'1DVOB'B3&G=8%9@,7BFU1'A(*,a(U-U'Ac3=NO,E'='>X]^GKMa.]9(*SD*^/8>^4/%(0.V>88U/)M-OU)P8U/%b5JE/?C]C9&4907UNN`GCc/&]Q%NM]4D,J.8WU*+HF4D-9L-;.B)?8Ea'L%MJ7KH]]C)aJA'F*24F]&48XEM&Na5";
// Colors, order GBR (one char shorter than all the others)
p[]={0,5390379,6379596,7783255,3435360,16354410,5131894,5295994,4671418,9975021};
// Huffman codes for colors 0-10
h[]={4,62,28,11,63,29,30,13,12,10,0};
// Array for image data
c[1024];
i,j,k,l,m,n;
red(int x,int y){
  while(i<356){
    k--;
    if (k<0) {
      j=b[i++]-37;
      k=5;
    }
    l*=2;
    if (j&(1<<k)) l++;
    for(m=0;m<11;m++){
      if(l==h[m]){
        if (m>9) m=c[n-1];
        c[n++]=m;
        l=0;
        m=12;
      }
    }
  }
  return P;
}
blue(int x,int y){return P>>16;}
green(int x,int y){return P>>8;}


Lost, 29 27/2 = 13.5 bytes

%?\>>>>>>>>>>
>>\"*"@"

Try it online! or verify that it is deterministic

Seemed like the right language to use.

Explanation:

Lost is a 2D language where the pointer starts anywhere, going in any direction. This generally leads to a lot of double checking that the pointer hasn't entered a section early.

...>>>>>>>>>>  These arrows filter all pointers that appear on the top line
.............  Or going vertically

%............  This flips the flag so that the program can end
.............  This stops premature termination

.?\..........  Clear the stack by skipping if a value popped from the stack is positive
.............  When the stack is empty, the \ directs the pointer down

.............  The \ directs the pointer right
..\"*"..  The string literal pushes all the Lost values to the stack

..\..........  The @ terminates the program if the % flag is switched
>>\........@.  Otherwise it clears the stack and repeats

.............  The quote here is to prevent the pointer getting stuck
............"  This happens when the pointer starts between the other quotes


Python + requests, 128 bytes

from requests import*
lambda n:get('http://api.stackexchange.com/questions?sort=hot&site=codegolf').json()['items'][n-1]['link']


Python, 76 chars

def S(n,a,b):
 if n:S(n-1,a,6-a-b);print n,a,b;S(n-1,6-a-b,b)
S(input(),1,3)

For instance, for N=3 it returns:

1 1 3  (move disk 1 from peg 1 to peg 3)
2 1 2  (move disk 2 from peg 1 to peg 2)
1 3 2  (move disk 1 from peg 3 to peg 2)
3 1 3  ...
1 2 1
2 2 3
1 1 3


Python 3.6, 159 131 128 bytes

1 byte saved thanks to @Zacharý

3 bytes saved thanks to @VаlueInk

28 bytes saved thanks to @Rod

lambda s:len(s)<2and f"{s}"or s[0]==s[1]and"ℂℍℕℙℚℝℤ"[ord(s[0])-65]or[f"{s[0]}",s[1]][s[0]=='_']

Try it online!


Java 8, 742 bytes
Could reduce by another 3 bytes naming the function s instead of sort or another 16 bytes if not counting class-definition.

public class H{String d="cs|dzs?|gy|ly|sz|ty|zs";void sort(java.util.List<String>l){l.sort((a,b)->{String o="-a-á-b-cs-dzs-e-é-f-gy-h-i-í-j-k-ly-m-ny-o-ó-ö-ő-p-q-r-sz-ty-u-ú-ü-ű-v-w-x-y-zs-";int i=c(r(a),r(b),r(o));return i!=0?i:(i=c(a,b,o))!=0?i:b.charAt(0)-a.charAt(0);});}String r(String a){for(int i=0;i<8;i++)a=a.toLowerCase().replace("ááéíóőúű".charAt(i),"aaeioöuü".charAt(i));return a;}int c(String a,String b,String o){a=n(a);b=n(b);while(!"".equals(a+b)){int i=p(a,o),j=p(b,o);if(i!=j)return i-j;a=a.substring(i%4);b=b.substring(j%4);}return 0;}int p(String a,String o){a=(a+1).replaceAll("("+d+"|.).*","-$1");return o.indexOf(a)*4+a.length()-1;}String n(String a){return a.toLowerCase().replaceAll("(.)(?=\\1)("+d+")| |-","$2$2");}}

Can be used like this:
new H().sort(list);

Test-suite:
public static void main(String[] args) {
    test(Arrays.asList("cudar", "cukor", "cuppant", "csalit", "csata"));
    test(Arrays.asList("kasza", "kaszinó", "kassza", "kaszt", "nagy", "naggyá", "nagygyakorlat", "naggyal",
            "nagyít"));
    test(Arrays.asList("jácint", "Jácint", "Zoltán", "zongora"));
    test(Arrays.asList("Eger", "egér", "író", "iroda", "irónia", "kerek", "kerék", "kérek", "szúr", "szül"));
    test(Arrays.asList("márvány", "márványkő", "márvány sírkő", "Márvány-tenger", "márványtömb"));
}

private static void test(final List<String> input) {
    final ArrayList<String> random = randomize(input);
    System.out.print(input + " -> " + random);
    new H().sort(random);
    System.out.println(" -> " + random + " -> " + input.equals(random));
}

private static ArrayList<String> randomize(final List<String> input) {
    final ArrayList<String> temp = new ArrayList<>(input);
    final ArrayList<String> randomOrder = new ArrayList<>(input.size());
    final Random r = new Random();
    for (int i = 0; i < input.size(); i++) {
        randomOrder.add(temp.remove(r.nextInt(temp.size())));
    }
    return randomOrder;
}

yielding
[cudar, cukor, cuppant, csalit, csata] -> [csata, cudar, cuppant, csalit, cukor] -> [cudar, cukor, cuppant, csalit, csata] -> true
[kasza, kaszinó, kassza, kaszt, nagy, naggyá, nagygyakorlat, naggyal, nagyít] -> [naggyá, kassza, kaszinó, nagygyakorlat, nagyít, nagy, kaszt, kasza, naggyal] -> [kasza, kaszinó, kassza, kaszt, nagy, naggyá, nagygyakorlat, naggyal, nagyít] -> true
[jácint, Jácint, Zoltán, zongora] -> [Zoltán, jácint, zongora, Jácint] -> [jácint, Jácint, Zoltán, zongora] -> true
[Eger, egér, író, iroda, irónia, kerek, kerék, kérek, szúr, szül] -> [egér, Eger, kerék, iroda, író, kerek, kérek, szúr, irónia, szül] -> [Eger, egér, író, iroda, irónia, kerek, kerék, kérek, szúr, szül] -> true
[márvány, márványkő, márvány sírkő, Márvány-tenger, márványtömb] -> [márványtömb, márványkő, Márvány-tenger, márvány sírkő, márvány] -> [márvány, márványkő, márvány sírkő, Márvány-tenger, márványtömb] -> true

Ungolfed:
public class HungarianOrder {

    String d = "cs|dzs?|gy|ly|sz|ty|zs";

    void sort(java.util.List<String> l) {
        l.sort((a, b) -> {
            String o = "-a-á-b-cs-dzs-e-é-f-gy-h-i-í-j-k-ly-m-ny-o-ó-ö-ő-p-q-r-sz-ty-u-ú-ü-ű-v-w-x-y-zs-";
            int i = c(r(a), r(b), r(o));
            return i != 0 ? i
                    : (i = c(a, b, o)) != 0 ? i
                            : b.charAt(0) - a.charAt(0);
        });
    }

    // toLower + remove long accent
    String r(String a) {
        for (int i = 0; i < 8; i++)
            a = a.toLowerCase().replace("ááéíóőúű".charAt(i), "aaeioöuü".charAt(i));
        return a;
    }

    // iterate over a and b comparing positions of chars in o
    int c(String a, String b, String o) {
        a = n(a);
        b = n(b);
        while (!"".equals(a + b)) {
            int i = p(a, o), j = p(b, o);
            if (i != j)
                return i - j;
            a = a.substring(i % 4);
            b = b.substring(j % 4);
        }
        return 0;
    }

    // find index in o, then looking if following characters match
    // return is index * 4 + length of match; if String is empty or first character is unknown -1 is returned
    int p(String a, String o) {
        a = (a+1).replaceAll("("+d+"|.).*", "-$1");
        return o.indexOf(a) * 4 + a.length() - 1;
    }

    // expand ddz -> dzdz and such
    String n(String a) {
        return a.toLowerCase().replaceAll("(.)(?=\\1)("+ d +")| |-", "$2$2");
    }
}

I am using Java's List-type and the order()-function of it, but the comparator is all mine.


Find the largest independent set in a high-dimensional lattice-like graph

2, 4, 10, 16, 31, 47, 76, 111, 166, 235

Notes

If we consider a graph G with vertices 0 to n and edges joining two numbers which match, then the tensor power G^n has vertices (x_0, ..., x_{n-1}) forming the Cartesian power {0, ..., n}^n and edges between matching tuples. The graph of interest is the subgraph of G^n induced by those vertices which correspond to the possible "counting arrays".

So the first subtask is to generate those vertices. The naïve approach enumerates over 2^{2n-1} strings, or on the order of 4^n. But if we instead look at the array of first differences of the counting arrays we find that there are only 3^n possibilities, and from the first differences we can deduce the range of possible initial values by requiring that no element in the zeroth differences is less than 0 or greater than n.

We then want to find the maximum independent set. I'm using one theorem and two heuristics:

Theorem: the maximum independent set of a disjoint union of graphs is the union of their maximum independent sets. So if we break a graph down into unconnected components we can simplify the problem.
Heuristic: assume that (n, n, ..., n) will be in a maximum independent set. There's a fairly large clique of vertices {m, m+1, ..., n}^n where m is the smallest integer which matches n; (n, n, ..., n) is guaranteed to have no matches outside that clique.
Heuristic: take the greedy approach of selecting the vertex of lowest degree.

On my computer this finds 111 for n=8 in 16 seconds, 166 for n=9 in about 8 minutes, and 235 for n=10 in about 2 hours.

Code

Save as PPCG54354.java, compile as javac PPCG54354.java, and run as java PPCG54354.

import java.util.*;

public class PPCG54354 {
    public static void main(String[] args) {
        for (int n = 1; n < 20; n++) {
            long start = System.nanoTime();

            Set<Vertex> constructive = new HashSet<Vertex>();
            for (int i = 0; i < (int)Math.pow(3, n-1); i++) {
                int min = 0, max = 1, diffs[] = new int[n-1];
                for (int j = i, k = 0; k < n-1; j /= 3, k++) {
                    int delta = (j % 3) - 1;
                    if (delta == -1) min++;
                    if (delta != 1) max++;
                    diffs[k] = delta;
                }

                for (; min <= max; min++) constructive.add(new Vertex(min, diffs));
            }

            // Heuristic: favour (n, n, ..., n)
            Vertex max = new Vertex(n, new int[n-1]);
            Iterator<Vertex> it = constructive.iterator();
            while (it.hasNext()) {
                Vertex v = it.next();
                if (v.matches(max) && !v.equals(max)) it.remove();
            }

            Set<Vertex> ind = independentSet(constructive, n);
            System.out.println(ind.size() + " after " + ((System.nanoTime() - start) / 1000000000L) + " secs");
        }
    }

    private static Set<Vertex> independentSet(Set<Vertex> vertices, int dim) {
        if (vertices.size() < 2) return vertices;

        for (int idx = 0; idx < dim; idx++) {
            Set<Set<Vertex>> p = connectedComponents(vertices, idx);
            if (p.size() > 1) {
                Set<Vertex> ind = new HashSet<Vertex>();
                for (Set<Vertex> part : connectedComponents(vertices, idx)) {
                    ind.addAll(independentSet(part, dim));
                }
                return ind;
            }
        }

        // Greedy
        int minMatches = Integer.MAX_VALUE;
        Vertex minV = null;
        for (Vertex v0 : vertices) {
            int numMatches = 0;
            for (Vertex vi : vertices) if (v0.matches(vi)) numMatches++;
            if (numMatches < minMatches) {
                minMatches = numMatches;
                minV = v0;
            }
        }

        Set<Vertex> nonmatch = new HashSet<Vertex>();
        for (Vertex vi : vertices) if (!minV.matches(vi)) nonmatch.add(vi);
        Set<Vertex> ind = independentSet(nonmatch, dim);
        ind.add(minV);
        return ind;
    }

    // Separates out a set of vertices which form connected components when projected into the idx axis.
    private static Set<Set<Vertex>> connectedComponents(Set<Vertex> vertices, final int idx) {
        List<Vertex> sorted = new ArrayList<Vertex>(vertices);
        Collections.sort(sorted, new Comparator<Vertex>() {
                public int compare(Vertex a, Vertex b) {
                    return a.x[idx] - b.x[idx];
                }
            });

        Set<Set<Vertex>> connectedComponents = new HashSet<Set<Vertex>>();
        Set<Vertex> current = new HashSet<Vertex>();
        int currentVal = 0;
        for (Vertex v : sorted) {
            if (!match(currentVal, v.x[idx]) && !current.isEmpty()) {
                connectedComponents.add(current);
                current = new HashSet<Vertex>();
            }

            current.add(v);
            currentVal = v.x[idx];
        }

        if (!current.isEmpty()) connectedComponents.add(current);
        return connectedComponents;
    }

    private static boolean match(int a, int b) {
        return a <= 2 * b && b <= 2 * a;
    }

    private static class Vertex {
        final int[] x;
        private final int h;

        Vertex(int[] x) {
            this.x = x.clone();

            int _h = 0;
            for (int xi : x) _h = _h * 37 + xi;
            h = _h;
        }

        Vertex(int x0, int[] diffs) {
            x = new int[diffs.length + 1];
            x[0] = x0;
            for (int i = 0; i < diffs.length; i++) x[i+1] = x[i] + diffs[i];

            int _h = 0;
            for (int xi : x) _h = _h * 37 + xi;
            h = _h;
        }

        public boolean matches(Vertex v) {
            if (v == this) return true;
            if (x.length != v.x.length) throw new IllegalArgumentException("v");
            for (int i = 0; i < x.length; i++) {
                if (!match(x[i], v.x[i])) return false;
            }
            return true;
        }

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

        @Override
        public boolean equals(Object obj) {
            return (obj instanceof Vertex) && equals((Vertex)obj);
        }

        public boolean equals(Vertex v) {
            if (v == this) return true;
            if (x.length != v.x.length) return false;
            for (int i = 0; i < x.length; i++) {
                if (x[i] != v.x[i]) return false;
            }
            return true;
        }

        @Override
        public String toString() {
            if (x.length == 0) return "e";

            StringBuilder sb = new StringBuilder(x.length);
            for (int xi : x) sb.append(xi < 10 ? (char)('0' + xi) : (char)('A' + xi - 10));
            return sb.toString();
        }
    }
}


Convert any number (up to 1e3000) to text

To get the ball rolling then, this is my version. Only the final number is converted to a float so there is no problem with large numbers if they're within range.
In terms of speed, it takes about 0.85 seconds to calculate 1000 random integers between -1e3000 and 1e3000.
Python 2 (574)
N=str(X).split('.');K=len;E=min(1000,(K(str(abs(int(N[0]))))-1)/3);P=N[0][:(-E*3if E else K(N[0]))];L=K(P);B=''.join(N);O='%.2f'%float((P+'.'+((B[L:L+3])or'0')));m,n,o,p,q,r,s,t,u,v,w,x,y,z='illion quadr quin sex sept oct non ing ag g tre duo c t'.split();a=[''];l=a+['thousand']+[i+m for i in['m','b','tr',n,o+z,p+z,q,r,s]]+[i+j+k for i in a+[i+'en'for i in[y,x+y,w+y,n+t,o+v,'sesc',q+t,r+t,s+v]]for k in[C+m for C in[z,'dec']+[B+'int'for B in['vig','trig',n+u,o+'quag',p+u,q+'uag',r+'og',s+u]]][not i:]for j in a+['un',x,w,'quattor',o,p,q+'en',r+'o','novem']];print O,l[E]

Then with some test cases:
>>> X = 100
100.0
>>> X = '100.0'
100.0
>>> X = '1037093920'
1.04 billion
>>> X = '-1540420004036040042.400642'
-1.54 quintillion
>>> X = '1540420' + '0'*153
1.54 duoquinquagintillion
>>> X = '1540496' + '0'*1553
154.05 quingenoctodecillion

Past the limit (just to show it doesn't throw an error and still handles negative value):
>>> X = '-10935' + '6'*3005
-1093566666.67 nongennovemnonagintillion
>>> X = '10935' + '6'*3250
1.09356666667e+254 nongennovemnonagintillion
>>> X = '10935' + '6'*3500
inf nongennovemnonagintillion


Windows PowerShell, 61 65 70 72 73 82
Evil alternative approach. It becomes apparent if you desperately search for patterns in the input.
Be sure to also check out Ventero's Ruby and Golfscript solutions which use the same technique which was sort of a joined work :-)
(7..3+1..5)[($x=($a="$args")[0..2]|sort)[2]-$x[0]]*($a-ne495)

A little explanation might be in order for this, I guess. Suppose you have a number consisting of three digits. For convenience they are labeled a, b and c here with c being the largest. You then are going to subtract abc from cba.
If we picture that, we are going to get (c − a − 1), 9 and (10 + a - c) as the individual digits. This will always hold, no matter the input digits. This also means that the middle digit get no say in how long the sequence will be, simply because it always is 9.
So basically the first and last digit of the sorted digits suffice in determining the length of the sequence. One can easily make a list with every conceivable combination of first and last digit (there are only 45) to search for patterns there.
As it turns out, there are at least two. Both play with the first few results of the different digits: [6 5 4 3 1 2 3 4 5]. First, taking the difference between the largest and the smallest digit and subtracting one gives the appropriate index in the aforementioned list of results. Second, interpreting the smallest and largest digit as a single number and doing modulo 11 yields the same, except that one has to prepend another 6 to the list.


Python 3, 534 bytes

import itertools as t
import operator as o
I=float("inf")
e=lambda p,A:sum([i[0]*i[1]for i in zip(p,A[:-1])])+A[-1]
def w(x,j):
	d=len(x[0])-1;C=[0]*d;v,w=I,I
	while 1:
		L={(*n,):(sum([0 if e(n,A)<=0 else e(n,A)for A in x[:-1]]),j*e(n,x[-1]))for n in [[sum(a) for a in zip(C,c)]for c in t.product(*[[-1,0,1]]*d)]};C,P=min(L.items(),key=o.itemgetter(1))[0],C;v,w,p,q=L[C][0],L[C][1],v,w
		if(all([e(C,A)<=e(P,A)for A in x[:-1]]))*(j*(e(C,x[-1])-e(P,x[-1]))<0)+(p==v>0):return I
		if(p==v)*(q<=w):return j*q
f=lambda x:(w(x,1),w(x,-1))

Try it online!

Overview

It is an iterative algorithm, starting from the origo. It collects the neighbour positions and assigns a potential function: x:(a,b) where x is the position, a is the sum of the position's distances from the half-spaces of each linear inequality, b is the value of the objective at that position.

x:(a,b) < y:(c,d) iff a<c or a=c and b<d

The iteration stops, when:

the first coordinate of the potential hasn't decreased and positive: the system is infeasible
the distance from every half-space has decreased just like the objective: the system is unbounded.
none of previous and the potential hasn't decreased: it is the optimal value.


Jelly,  20  19 bytes

-1 byte using the quick ` to avoid a link, as suggested by Erik the Outgolfer.

H»þ`€Ḣ>Ð€HSUṚm€0m0Y

A full program taking a list [a,b,c] printing the boxes using a:2 b:1 c:0
... in fact, as is, it will work for up to 10 boxes, where the innermost box is 0 (for example).

Try it online!

How?

H»þ`€Ḣ>Ð€HSUṚm€0m0Y - Main link: list of boxes, B = [a, b, c]
H                   - halve B = [a/2, b/2, c/2]
    €               - for €ach:
   `                -   repeat left argument as the right argument of the dyadic operation:
  þ                 -     outer product with the dyadic operation:
 »                  -       maximum
                    - ... Note: implicit range building causes this to yield
                    -       [[max(1,1),max(1,2),...,max(1,n)],
                    -        [max(2,1),max(2,2),...,max(2,n)],
                    -        ...
                    -        [max(n,1),max(n,2),...,max(n,n)]]
                    -       for n in [a/2,b/2,c/2]
     Ḣ              - head (we only really want n=a/2 - an enumeration of a quadrant)
         H          - halve B = [a/2, b/2, c/2]
       Ð€           - map across right with dyadic operation:
      >             -   is greater than?
                    - ...this yields three copies of the lower-right quadrant
                    -    with 0 if the location is within each box and 1 if not
          S         - sum ...yielding one with 0 for the innermost box, 1 for the next, ...
           U        - upend (reverse each) ...making it the lower-left
            Ṛ       - reverse ...making it the upper-right
             m€0    - reflect €ach row (mod-index, m, with right argument 0 reflects)
                m0  - reflect the rows ...now we have the whole thing with integers
                  Y - join with newlines ...making a mixed list of integers and characters
                    - implicit print - the representation of a mixed list is "smashed"


Order function parameters to minimize whitespace
Instead of
(defun f(a b)(...))
...
(f x(1+ y))

try something like
(defun f(b a)(...))
...
(f(1+ y)x)


Perl, 120 bytes

Includes +6 for -Xapi (- and space are counted too because both the -i and the $' in the code make it impossible to combine the options with -e)

Run with the input on STDIN and the platform length after the -i option, e.g.

perl -Xapi3 trains.pl <<< "1 4 5 6 3 8 7 2 9"

Prints -2 if there is no solution

trains.pl:

1until$_=$n++*$z{pack"W*",@F}||-!grep!$z{$_}++&&/.{$^I}(??{!\$z{$`.reverse($&).$'}})$/s,keys%z,pack"W*",1..@F;$_--

if N <= 9 then you can gain 5 more bytes:

1until$_=$n++*$z{join"",@F}||-!grep!$z{$_}++&&/.{$^I}(??{!\$z{$`.reverse($&).$'}})$/,keys%z,join"",1..@F;$_--


Haskell, 102 bytes

Function 1 (102 bytes):

l=length
[]#i=[[]]
(r:s)#i=id=<<[(splitAt j r:)<$>s#j|j<-[i-1..i+1],j>=0,j<l r]
f r=(r#)=<<[0..l$r!!0]

Function 2 (90 bytes):

g::[[([Int],[Int])]]->Int
g a=minimum$map(\(x,y)->abs$sum(sum<$>x)-sum(sum<$>y))$unzip<$>a

Missing boilerplate for F1 to make it a full program, including the hardcoded integer array to check:

main = print $ f [[164,187,17,0,277],[108,96,121,263,211],[166,6,57,49,73],[90,186,26,82,138],[173,60,171,265,96]]

and for F2:

main = print . g . read =<< getContents

Now you can call runhaskell f1.hs | runhaskell f2.hs which outputs 8.

How it works: f takes a list of list of integers.

f r = (r#)=<<[0..l$r!!0]          -- for each index [0 .. length r] call # with
                                  -- the first parameter being r and
                                  -- collect the results in a single list

[]#i=[[]]                         -- base case. If the list of lists is empty, stop
(r:s)#i                           -- else let r be the first list, s all others
           j<-[i-1..i+1],         -- foreach possible index j for the next line
                 j>=0,j<l r       --    (skipping out of range indices)
     (splitAt j r:)<$>            -- split the current line at j into a pair of
                                  -- lists and prepend it to every element of
                      s#j         -- a recursive call with s and j
id=<<                             -- flatten into a single list

Now we have a list of all possible splits, for example the first one and a random one from the middle

[([],[164,187,17,0,277]),                  [([164,187],[17,0,277]),
 ([],[108,96,121,263,211]),                 ([108,96],[121,263,211]),
 ([],[166,6,57,49,73]),                     ([166],[6,57,49,73]),
 ([],[90,186,26,82,138]),                   ([90,186],[26,82,138]),
 ([],[173,60,171,265,96])]                  ([173,60,171],[265,96])]

Function g takes such a list and

                    unzip<$>a       -- turn every pair of lists into a list of pairs
  map(\(x,y)->                      -- foreach such pair
      abs$sum(sum<$>x)-sum(sum<$>y) -- calculate the score
minimum                             -- and find the minimum

Note: the second function can be golfed a little bit more, but it doesn't change the score.


T-SQL

Print 'Hello, World!' -- she said.

Looks like English.


Polyphonic, Haskell, 2826 3177 4719

Audio output:
https://www.dropbox.com/s/nba6489tfet740r/hs-golf-turca.ogg

Features:

All notes from the right hand. I could of course add the left hand, too (done that).
Proper articulation of the staccato notes etc.
Reasonably nice sound with dynamics. Not just simple volume modulation, but proper morphing of the attack character and overtone content, like you get on a real piano actually, rather more... hey this piece is supposed to be imitating Turkish Janissary bands, right?
Reverb. Doesn't sound amazingly great, but not too bad, either.
Dynamic compression. Don't ask...
Dithering of the output. This is kind of ridiculous: with proper 16-bit resolution, hardly anybody would hear the quantisation artifacts, but to avoid including the binary library, I effectively use only 7-bits resolution, which I can cover with ASCII output. The dither itself is rather loud, no noise-shaping...
Multithreaded calculation of polyphonic chords.

import Control.Parallel
main=mapM_ (\(d,s)->(\p->p>>p>>p>>p).putChar.toEnum.round.(+d).(*62).min 2.abs$s+1).zip(dθ 1).lim.rev.hgp 9. pl 9e6 (\_->0) . ä
 $[mT%8.1,t2%16.1,t3(∡7)%8,t4%8,t5%16,t3(∡7)%8,mT%8.1,t2%16.1,t3(tev arp8)%8,cdT%99] >>= \e->[e,e]
mM=ä[2-^8,1-^8,0-^8,1-^8,3-^4]
cM=ä[7-^20,8-^20,9.^4,F[(7,0),(6,1)](map((∡2).(.^4))[6,5,6])%0.75]
cMv=ä[10-^2,8.^4,9.^4,hom(.^4)[[24,5],[23,8,12],[22,4],[21,6,9],[22,3],[19,5,8],[20,4],[18,6,9],[17]]#7&(-14)%2.5,tr 2%0.4,1-^9,2-^12,1-^1]%4.5
 ⋎(ä[6-^4,lp(8.^4∡3)%(3/4),sil%2,lp(5.^4∡3)%h,lp(5.^4∡2)%h,1-^1∡7]&(-14)#7#4%5)
mMa f=ä[(1-3*f).^4,lp(5.^4∡(-2-f))%0.75,mMa f%1.5,mMa(f*2)%h,mMa f%1]#7
mTm=ä[mM%1,mM&2%1,mM#4&4%h,mM&7%h,mM&7%1,8.^4,ä[10.^4]%0.2,cM%1,cM%1,cM%0.85,ä[4.^4∡2,5.^2]#6#4%2]#7
mT=p$ä[mTm%8.1⋎(ä[sil%h,mMa 0%4,mMa 1%2.75,2.^4,(-2)-^2]&(-7)%8)]
m2=ä[ä(map((∡2).(.^4))[1,2,3,3]++[es[6,5,4,3]%h]++[0-^2∡2])%2
 ⋎(ä[sil%h,1.^4,8.^4,3.^4,10.^4,5-^2]⊿1.3&(-14)%2)]
t2=p$ä[m2&2%1.8,0-^5,m2&2%2,m2#7%1.8,(-2)-^5,m2#7%2,mT%3.5,cMv]
m3=ä$[3-^4,4-^4,5-^2]++map(-^4)[3,4,5,4,3,2,1,2,3,4,2,0]
m3a=ä[(ä[sil%(1/8),lp(8.^4)%1]:zw(\d n->ä[sil%(d/24),n-^1]⊿cos d)[0..][1,3,5],s),m3a%1]
m3ra=(map((%1). \[a,b,c]->es[a,c,b,c,a,c,b,c])[[1,3,5],[1,4,6],[-2,0,5]]!!)
t3 o=ä[ä[o$ḋ[m3%4,m3%2.5,1-^4,4-^4,2-^4,0-^4]&(-2)%7.5,1-^2∡7]%8
 ⋎(ḋ[sil%(3/8),m3a&4%2,m3a%h,m3a#4%h,m3a&1%1,m3a&4%2,m3a%h,m3a&1%(5/8),5-^2]&(-18)%8)]
mQ=es[2,1,0,2]
m4=mM⇆4
i4 e=ḋ[m4⇅11%h,m4⇅9%h,mQ⇆4⇅8%h,F[(5,e),(4,1)][mQ⇅7%h,mQ⇅5%h,m4&5%h,m4&7%h]%2,es[10,9,10,9]#2%h ]
mla[b,c,d]=ä[b-^4,lp(c-^4⋎(d-^4))%1]%1
i4a=ḋ[sil%h,ä(map mla[[1,3,5],[2,4,5],[1,3,5],[0,2,5]])#5%4,ä(map mla[[1,3,5],[2,5,7],[2,6,8]])#4%3,5-^2⋎(7-^2)]
t4=p$ä[ḋ[i4 1%4,i4 0%2.5,ä[mQ⇅6%h,mQ⇅4%h]#4#2%1,3-^2]%8⋎(i4a&(-9)%8)]
mlaa=mla[1,3,5]
m5=ä$map(-^8)[1..4]
i5=ḋ[m5⇅6%h,m5%h,m5&4%h,m5⇅9%h]
i5d=hom(-^4)[[2],[4,5],[0],[4,5]]%1
i5a=ḋ[sil%h,mlaa,i5d,mlaa,mla[-2,0,4],mlaa,i5d,sq 4[1,-1,-3,-2,-6,1]%2]&(-7)
t5=ḋ[ḋ[i5%2,i5%1.5,ä[8-^4,9-^4]#1%h,i5%2,ḋ[es[5,4,3,2,3,5,1,3,2,4,0,2]%2]%1.5,1-^2]%8⋎(i5a%8)
 ,p(ä[ä[i4 1%4,es[3,2,3,1,4,3,4,3,4,3,4,3]#2#1&7%1.5,m5⇅13%h,mQ⇅8%h,m5&7%(3/8),6-^8,mQ⇅7#5%h,6-^2]%8
 ⋎(ä[i4a%3.5,F[(1,-1),(7,0),(6,1)][hom(-^4)[[-2],[3,5],[2,5],[1,5]]%1]%1,mla[-3,1,4],mla[-3,2,4],hom(-^4)[[-2],[1,3],[-2],[2,4],[1,3]]%1.5]&(-9)%8)])%8]⊿0.8
am d=3-^d∡2∡5
amf=1-^υ∡2⋎(5-^1∡3)
vh v(c,d)=lp(ä[v-^12]:map(\t->ä[t⊿0%0.04,t%d])c,d)
aam=vh 11.am
aar=ä[1-^10,4-^10,6-^1]&4
eam=vh 10.em
dm=6-^1∡2⋎(11-^1)
em d=5-^d∡2⋎(9-^1)
cdM=ḋ[4-^8,3-^8,2.^8,3.^8,cdM%1]
cdT=ḋ[ä[3-^(8/3)∡7,10-^6,am 1,am 1,cdM&7%1,dm,aam 4.05%1,em(4/3),12-^4,am 1,am 1,cdM&7%1,dm,aam 1%1,eam 4%1]%12.5⋎(ä(sil%(11/24) : map((%1).(m3a&))[4,4,4,0,4,1,4,4,4,0,4,1])&(-18)%13.1)
 ,p(ä[ä[ä[8-^2]⊿2%h,aar%(3/8),10-^8,aar%1,aar%1,cdM&7%1,11-^1,vh 11(10-^4)%1,9-^(4/3)]%7⋎(ä(map m3ra[0,0,0,0,1,0,2])&(-7)%7)])%6.75
 ,ä[p(ä[12-^4])%(1/4),am 1,am 1,cdM&7%1,dm,aam 1%1,eam 4%1,amf,ä[3-^4,1-^υ,5-^4,1-^υ,3-^4,1-^4,3-^4,1-^4,5-^4,1-^2]%3.75∡7,ä[amf∡(-14)]%0.56,ä[amf∡(-14)]⊿0.8%1]%12⋎(ä(sil%(1/8):map((%1).(m3a&))[4,4,4,0,4,1,4,4,4]++[m3a&4%h,m3a&4%h,5-^(8/5)])&(-18)%12)]
type D=Double
data F=N Int D|F[(Int,D)][([F],D)]
φ⇸F a fs=F a$map(\(f,d)->(map φ f,d))fs
_⇸N i d=N i d
i##c
 |i<1=(i+7)##c/2
 |i>7=(i-7)##c*2
 |1>0=1.06**(c i+case i of{1->0;3->3;4->5;5->7;6->8;7->10;_->fri i})
pl dur acc(N n v)=(\ω η->map(sin.(\x->x+τ x^2/η). \i->v*exp(-i*η/s)*τ(i*v)*(0.8-τ((i-dur)/90))*sin(i*ω))[1..dur])(n##acc/15.5).exp$fri n/9
pl dur acc(F accm fs)=pl' dur (foldr(\(q,m)f i->if q==i then m else f i)acc accm) fs
pl' dur _ _|dur<=0 = []
pl' dur _ []=map(\_->0)[1..dur]
pl' dur acc((f,dr):fs)|n<-min dr dur=trans(round n)(foldr1(\a b->sum a`par`sum b`pseq`zw(+)a b)(map(pl(n+99)acc)f))$pl'(dur-dr)acc fs
trans n a b|(f,ol)<-splitAt n a,(or,l)<-splitAt 99 b=f++zw(+)ol or++l
fri=fromIntegral
F a fs#q=F((q,1):a)fs
N i d&n=N(n+i)d
f&n=(&n)⇸f
N i d⇅n=N(n-i)d
f⇅n=(⇅n)⇸f
N i d⇆_=N i d
F a fs⇆n=F a.reverse$take n fs
N i d⊿v=N i$d*v
f⊿v=(⊿v)⇸f
p=(⊿0.3)
n.^q=([F[][([N n 1],s/2/q)]],s/q)
n-^q=([N n 1],s/q)
(l,d)⋎(r,_)=(l++r,d)
(l,d)∡j=(l++map(\h->ä[h⊿0%0.01,h&j%100])l,d)
f%t=([f],s*t)
tr n=F[]$cycle[n-^15,(n+1)-^20]
ä=F[];ḋ=F$zip[6,3,7][1,1,1]
lp=ä.repeat
sil=N 0 0
tev f(l,d)=(map f l,d)
h=1/2
υ=4/3
s=4e+4
sq d=ä.map(-^d)
es=sq 8
arp8 n@(N i v)=F[][([n,ä[n⊿0%(1/8),n&7⊿(v/υ)%100]],s)]
arp8 f=arp8⇸f
hom q=ä.map(foldr((⋎).q)$sil%1)
dθ l=2*asin l/pi:dθ(abs.sin$l*1e+9)
rev ls=(\z->z id(foldr(\m sg->(\v->z(*v)(map(*0)[0..m*14349]++sg)sg)$abs(cos$(m*3)^2)-0.6)ls.take 9$dθ 1)ls)$(.lwp 3 0).zw.((+).)
lwp ω c(x:l)=c:lwp ω((x+c*ω)/(ω+1))l
lwp _ _ _=[]
hgp ω l=zw(-)l$lwp ω 0 l
lime e(x:l)
 |abs(e*x)>1,e'<-((e*8+abs(1/x))/9)=e':lime e' l
 |1>0=e:lime((e*49999+1)/5e4)l
lime _[]=[]
lim ls=zw(\a u->τ$a/9+max(-2)(min 2$a*u)/6)(map(*0)[0..500]++ls).lwp 9 0.lime 1$hgp 9 ls
zw=zipWith
τ=tanh

  $ make
  ghc -o bin/def0-hs def0.hs -O2 -fllvm -threaded
  [1 of 1] Compiling Main             ( def0.hs, def0.o )
  Linking bin/def0-hs ...
  time sh -c 'bin/def0-hs +RTS -N4 > hsoutp.pcm'
  189.39user 138.41system 2:06.62elapsed 258%CPU (0avgtext+0avgdata 6440240maxresident)k
  0inputs+0outputs (0major+403037minor)pagefaults 0swaps
  ffmpeg -loglevel panic -y -f s16le -ar 44.1k -ac 2 -i hsoutp.pcm hsoutp.ogg

Here's a partially ungolfed and commented version: https://gist.github.com/leftaroundabout/5517198.


C# - 463

Accepts input via STDIN, and should produce an optimal path, tested for the given test case, but not otherwise. Assumes there is always a solution.

I'm in a bit of a hurry, I have a deadline in 7 hours, but this just looked like too much fun to miss out on. I'm also out of practice. It could be very embarrassing if this goes wrong, but it's reasonably golfed.

using C=System.Console;class P{static void Main(){var S=C.In.ReadToEnd().Replace("\r","").Replace('X','+');int s=S.IndexOf('S'),e=S.IndexOf('+'),w=S.IndexOf('\n')+1,L=S.Length,i,j=L;var K=new int[L];for(K[s]=s+2;j-->0;)for(i=0;i<L;i+=2){System.Action<int>M=z=>{if((z+=i)>=0&z<L&&S[z]<=S[i]&K[z]<1&K[i]>0&(i%w==z%w|i/w==z/w))K[z]=i+1;};M(2);M(-2);M(w);M(-w);}for(w=e;w!=s+1;w=i){i=K[w]-1;K[w]=-1;}for(;++j<L;)C.Write(j%2<1?K[j]<0?j==s?'S':j==e?'X':'.':'#':S[j]);}}

Code with comments:

using C=System.Console;

class P
{
    static void Main()
    {
        var S=C.In.ReadToEnd().Replace("\r","").Replace('X','+'); // read in the map, replace X with + because + < 0
        int s=S.IndexOf('S'),e=S.IndexOf('+'),w=S.IndexOf('\n')+1,L=S.Length,i,j=L; // find start, end, width, length

        var K=new int[L]; // this stores how we got to each point as loc+1 (0 means we havn't visited it)

        for(K[s]=s+2; // can't risk this being 0
            j-->0;) // do L passes
            for(i=0;i<L;i+=2) // each pass, look at every location
            {
                // if a whole load of bouds checks, point new location (i+z) at i
                System.Action<int>M=z=>{if((z+=i)>=0&z<L&&S[z]<=S[i]&K[z]<1&K[i]>0&(i%w==z%w|i/w==z/w))K[z]=i+1;};
                // try and move in each direction
                M(2);
                M(-2);
                M(w);
                M(-w);
            }

        for(w=e;w!=s+1;w=i) // find route back
        {
            i=K[w]-1; // previous location
            K[w]=-1; // set this so we know we've visited it
        }

        for(;++j<L;) // print out result
            C.Write(j%2<1?K[j]<0?j==s?'S':j==e?'X':'.':'#':S[j]); // if K < 0, we visit it, otherwise we don't
    }
}


First sequence with no square differences

Ruby, 72 62 57 50 47 bytes

0.step{|x|$*<<p(x)if$*.all?{|i|(x-i)**0.5%1>0}}

Try it online!
Prints all terms of the sequence indefinitely.
7 bytes saved by Dingus and further 3 by Sisyphus.
Ruby 2.7+, 45 bytes

0.step{|x|$*<<p(x)if$*.all?{(x-_1)**0.5%1>0}}


Python - 101

To get started I basically golfed your example code...

def c(n,f,t,x=0,r=""):
 for d in n:x=x*len(f)+f.index(d)
 while x:l=len(t);r=t[x%l]+r;x//=l
 return r


GolfScript - 67 chars

~17.'_'*n+*\153:|;{|/()[124^.2/6+:6.1&17*)\2&(*|+:|;]@++}*|/();'@'@

hallvabo's Python solution is the most similar to this, so I'll only describe the main differences.

The board is stored as a string instead of an array. This is so we can update a value on the board with less characters (as strings are always flat), and so getting it to the desired output format is easy.

The ant position is incremented by the formula ((d&1)*17+1)*((d&2)-1) (i.e. .1&17*)\2&(*), where d is the direction. We use the variable 6 so we can skip initialization.


Haskell, 167 165 characters
c p=o p:c(o p:p)
o p=[(a,b)|a<-[0..],b<-[0..a],(a,b)?p==[]]!!0
(a,b)?p=[y|y@(c,d)<-p,c==a||c==b||d==b||a+d==b+c]
f x@(a,b)|a<b=f(b,a)|x?c[]!!0==x=(0,-1)|1>0=x?c[]!!0

The algorithm is inefficient, but it still runs within a second (though not in the interactive console) for inputs < 100.
Explanation:
c p=o p:c(o p:p)

The list of cold positions given a set of previous cold positions is one cold position followed by the list of cold positions given this position and the previous ones (Inefficiency: this position is generated twice)
o p=[(a,b)|a<-[0..],b<-[0..a],(a,b)?p==[]]!!0

One cold position is the first pair such that there are no cold positions reachable from that pair (Inefficiency: we should search from the previous pair instead)
(a,b)?p=[y|y@(c,d)<-p,c==a||c==b||d==b||a+d==b+c]

Positions reachable from a pair are those such that their first elements match, their second elements match, their difference matches, or the smaller heap before removal is the larger heap after removal.
f x@(a,b)|a<b=f(b,a)
         |x?c[]!!0==x=(0,-1)
         |1>0=x?c[]!!0

(main method) If the heaps are in the wrong order, swap them. Else, if the first cold position reachable from a position is the position itself, indicate failure (ideally, one would return Maybe (Int,Int) instead). Else return that cold position (Inefficiency: said pair is looked up twice. Worse, the list of cold positions is generated twice)


Retina, 45 bytes

A`-
$
,;BliNClyde,INPiN
N
nky,
D`\w+,
.*;|,$

The trailing linefeed is significant. Input and output are comma separated.

Try it online! (The first line enables a linefeed-separated test suite.)

Explanation

I did not expect to be able to show off Retina's latest addition (deduplication stages) so soon, but it's really helpful for this challenge. :)

Stage 1: Anti-Grep

A`-

Anti-grep stages discard all lines that match the given regex. The regex is just - and the input is always a single line, so this discards all ghosts if the input contains Pac-Man.

Stage 2: Substitution

$
,;BliNClyde,INPiN

This simply appends the fixed string ,;BliNClyde,INPiN. This will be the list of ghosts in the output after some clean-up.

Stage 3: Substitution

N
nky,

Note that we've written the three *nky ghosts with an N in the previous stage (and omitted the comma after them), and we now expand this shorthand, which saves a couple of bytes. There is now a comma after every single ghost, and we've got the input ghosts and list of all ghosts separated by a semicolon.

Stage 3: Deduplication

D`\w+,

This is the new part. Deduplication stages find all instances of the given regex and discard all matched substrings which are equal to an earlier matched substring. The regex simply matches all the ghosts, both in the input and in the list of potential outputs. If the input contains a ghost, then the same ghost will be matched again in the second list and is discarded. Otherwise, the ghost is matched for the first time in the second list and kept. So after this, the list after the semicolon is our desired output. All that's left is a bit of clean-up:

Stage 5: Substitution

.*;|,$

We simply match everything up to the semicolon as well as the comma at the end of the string and remove them.


Detect the newest file and pass it to a process

Zsh - 15

Only tested on Linux, but it should work on other platforms too.

$2 $1/*(.om[1])


Haskell - 1493 bytes

In this version, there are no detailed error messages and the output is much more basic. The major change was replacing Either String a with Maybe a and since they are both monads, this was acheived by simply swapping Right a with Just a and Left String with Nothing.

{-# LANGUAGE OverloadedStrings #-}
import Prelude hiding ((>>=),concatMap,filter,foldl,head,last,map,null,replicate)
import Control.Applicative hiding (empty)
import Control.Monad hiding (replicateM)
import Data.Vector hiding ((++),concat,foldM,reverse,zip)
main=getLine>>= \s->h$t<$>(zip$cycle[w,v])<$>b s>>= \m->u(\b(c,x)->case d b x c of r@(Just _)->r;Nothing->if not$null$findIndices(\y->e$d b y c)$t[(x,y)|x<-[0..7],y<-[0..7]];then é;else d b x$not c)k$n m
 where b(x:y:s)=(:)(read [x],read [y])<$>b s;b(_:_)=é;b[]=è[];d b z c=let d=join$m(f b z c)$m(\v->(head v,last v))$replicateM 2$t[-1,0,1];in if null d;then Nothing;else u(\b (x,y)->case b!?y of Just r->(case r!?x of Just _->è$b//[(y,r//[(x,è c)])];Nothing->é);Nothing->é)b$n$d`snoc`z;e(Nothing)=w;e(Just _)=v;f b(x,y)c z@(u,v)=let r=x+u;s=y+v;t=(r,s);in (case g b t of Just(Just d)->if d==c;then l;else (case g b (r+u,s+v) of Just(Just _)->t`cons`f b t c z;_->l);Just(Nothing)->l;Nothing->l);g b(x,y)=(case b!?y of Just col->col!?x;Nothing->é);h(Just b)=p$(o$n$m(\r->o(n$m(\c->case c of Just False->"B";Just True->"W";Nothing->".")r)++"\n")b)++i(q(\(w,b)(rw,rb)->(w+rw,b+rb))(0,0)$m(\r->q(\s@(w,b)c->case c of Just True->(w+1,b);Just False->(w,b+1);_->s)(0,0)r)b);h Nothing=p"e";i(w,b)|w>b="W"++s w|b>w="B"++s b|v="N"++s(w+b);j=r 8 é;k=r 8 j//[(3,j//[(3,è v),(4,è w)]),(4,j//[(3,è w),(4,è v)])];l=empty;m=map;n=toList;o=concat;p=putStrLn;q=foldl;r=replicate;s=show;t=fromList;u=foldM;v=True;w=False;é=Nothing;è=Just

$ printf "232425140504032627" | ./nano-rve
........
........
........
B.BBB...
BBBWW...
B.B.....
..B.....
..B.....
B11

Original version - 4533 bytes

I will golf when there will be competition!
edit It has arrived

{-# LANGUAGE OverloadedStrings #-}
import Prelude hiding ((>>=),concatMap,filter,foldl,map,null,replicate)
import Control.Applicative hiding (empty)
import Control.Monad
import Data.Either
import Data.Vector hiding ((++),concat,foldM,reverse,zip)

type Case = Maybe Bool
type Board = Vector (Vector Case)
type Coord = (Int,Int)

-- fmap (toList) $ replicateM 2 [-1,0,1] -- minus (0,0)
directions :: Vector Coord
directions = fromList [(-1,-1),(-1,0),(-1,1),(0,-1),(0,1),(1,-1),(1,0),(1,1)]

--  [(x,y) | x <- [0..7], y <- [0..7]]
allCoords :: Vector Coord
allCoords = fromList [(0,0),(0,1),(0,2),(0,3),(0,4),(0,5),(0,6),(0,7),(1,0),(1,1),(1,2),(1,3),(1,4),(1,5),(1,6),(1,7),(2,0),(2,1),(2,2),(2,3),(2,4),(2,5),(2,6),(2,7),(3,0),(3,1),(3,2),(3,3),(3,4),(3,5),(3,6),(3,7),(4,0),(4,1),(4,2),(4,3),(4,4),(4,5),(4,6),(4,7),(5,0),(5,1),(5,2),(5,3),(5,4),(5,5),(5,6),(5,7),(6,0),(6,1),(6,2),(6,3),(6,4),(6,5),(6,6),(6,7),(7,0),(7,1),(7,2),(7,3),(7,4),(7,5),(7,6),(7,7)]

initBoard :: Board
initBoard = vs // [(3,v1),(4,v2)]
    where va = replicate 8 Nothing
          v1 = va // [(3,Just True),(4,Just False)]
          v2 = va // [(3,Just False),(4,Just True)]
          vs = replicate 8 va

showBoard :: Board -> String
showBoard b = (concat $ toList $ map (showRow) b) ++ (showScore b)
    where showCase :: Case -> String
          showCase c = case c of
              Just False -> "░B"
              Just True -> "▓W"
              Nothing -> "██"
          showRow :: Vector Case -> String
          showRow r = concat (toList $ map (showCase) r) ++ "\n"

showScore :: Board -> String
showScore b = winner score ++ "\n"
    where scoreCase :: (Int,Int) -> (Maybe Bool) -> (Int,Int)
          scoreCase (w,b) (Just True) = (w+1,b)
          scoreCase (w,b) (Just False) = (w,b+1)
          scoreCase s _ = s
          scoreRow :: Vector Case -> (Int,Int)
          scoreRow r = foldl (scoreCase) (0,0) r
          score :: (Int,Int)
          score = foldl (\(w,b) (rw,rb) -> (w+rw,b+rb)) (0,0) $ map (scoreRow) b
          winner :: (Int,Int) -> String
          winner (w,b) | w > b = "White with " ++ show w ++ " against Black with " ++ show b ++ "."
                       | b > w = "Black with " ++ show b ++ " against White with " ++ show w ++ "."
                       | otherwise = "Nobody with " ++ show (w+b) ++ "."

printBoard :: Board -> IO ()
printBoard b = putStrLn $ showBoard b
pm :: Either String Board -> IO ()
pm (Right b) = printBoard b
pm (Left s)  = putStrLn s

lookupBoard :: Board -> Coord -> Either String Case
lookupBoard b (x,y) = case b !? y of
    Just col -> case col !? x of
        Just c -> Right c
        Nothing -> Left "x is out of bounds"
    Nothing -> Left "y is out of bounds"

updateBoard :: Board -> Coord -> Bool -> Either String Board
updateBoard b (x,y) c = case b !? y of
    Just r -> case r !? x of
        Just _ -> Right $ b // [(y,r // [(x,Just c)])]
        Nothing -> Left "x is out of bounds"
    Nothing -> Left "y is out of bounds"

makePath :: Board -> Coord -> Bool -> Coord -> Vector Coord
makePath b (x,y) c (px,py) = case lookupBoard b (nx,ny) of
        Right (Just pc) -> if pc == c
            then empty
            else case lookupBoard b (nx+px,ny+py) of
                Right (Just _) -> (nx,ny) `cons` makePath b (nx,ny) c (px,py)
                _ -> empty
        Right (Nothing) -> empty
        Left _ -> empty
    where nx = x+px
          ny = y+py

makeMove :: Board -> Coord -> Bool -> Either String Board
makeMove b xy@(x,y) c = if null cases
        then Left $ "impossible move " ++ show xy ++ "."
        else foldM (\ob (cx,cy) -> updateBoard ob (cx,cy) c) b $ toList $ cases `snoc` (x,y)
    where cases = join $ map (makePath b (x,y) c) directions

makeMoves :: Board -> Vector (Bool,Coord) -> Either String Board
makeMoves b ms = foldM (\ob (c,xy) -> case makeMove ob xy c of
    rb@(Right _) -> rb
    Left _ -> if not $ null $ findIndices (\xy -> isRight $ makeMove ob xy c) allCoords
        then Left $ "wrong move " ++ show xy ++ "."
        else makeMove ob xy (not c)) b $ toList ms

movesFromString :: String -> Either String (Vector (Bool,Coord))
movesFromString cs = fromList <$> (zip $ cycle [False,True]) <$> coords cs
    where coords (x:y:cs) = (:) (read [x],read [y]) <$> coords cs
          coords (_:cs) = Left "invalid coordinates string"
          coords [] = Right []

isRight :: Either a b -> Bool
isRight (Left _) = False
isRight (Right _) = True

main=getLine>>= \s->pm$movesFromString s>>=makeMoves initBoard

Note : Your second example should be 232425140504032627.

Tests

With screenshots to prevent eye burns.

$ printf "232425140504032627" | ./rve

$ printf "2324" | ./rve

$ printf "1" | ./rve
invalid coordinates string

$ printf "24" | ./rve
wrong move (2,4).

Is is possible to get impossible move (x,y) when you use innardics (functions from the innards of the program and that you should not use) and x/y is out of bounds.


Choose from an existing set of weights to make a target sum

MATL, 29 28 bytes
4t:qEZ^!"[l2.5AX]@Y*10+G=?@.

For inputs that have no solution this produces an empty output (without error).
Try it online!
Explanation
4           % Push 4
t:q         % Duplicate 4 and transform into range [0 1 2 3]
E           % Multiply by 2: transform into [0 2 4 6]
Z^          % Cartesian power. Each row is a "combination" of the four numbers
!           % Transpose
"           % For each column
  [l2.5AX]  %   Push [1 2.5 5 10]
  @         %   Push current column
  Y*        %   Matrix multiply. Gives sum of products
  10+       %   Add 10
  G=        %   Compare with input: are they equal?
  ?         %   If so
    @       %     Push current column, to be displayed
    .       %     Break loop
            %   Implicit end
            % Implicit end
            % Implicit display


Python 2, 115 112 bytes

x,y,z=input().split()
d=y<""
f=lambda a,b:a+b and(b%2+5&4-d)*f(a/2,b/2)+(a%2*2+b%2)/3**d
print f(int(x),int(z))

The string on the second line contains a single unprintable character \x7d, the next char after ~.

All hopes of a nice, single lambda get crushed by the input format. There's probably a better way to read in input. Input like "51234 ¢ 60003" via STDIN.

The function f combines the following two recursive functions:

g=lambda a,b:a+b and 4*g(a/2,b/2)+a%2*2+b%2    # ¢
h=lambda a,b:a+b and(b%2+1)*h(a/2,b/2)+a*b%2   # ~

(-3 bytes with the help of @xnor)


Python 2, 50 bytes

l=input()
while l:s=set(l);print s;map(l.remove,s)

Try it online!

Repeatedly prints the unique of elements of the list, then removes one of each such element. A rare imperative use of map.


SageMath, 108 bytes

def f(s):p=map('{:+} '.format,numerator(minpoly(sage_eval(s)/1)));return'*'+p[-1][1:]+'*x '.join(p[-2::-1])

Try it on SageMathCell.

Explanation:

Evaluate the string symbolically as an algebraic number (sage_eval()).  Every algebraic number is a zero of some polynomial a[0] + a[1] x^1 + a[2] x^2 + ⋯ + a[n] x^n with rational coefficients a[0], …, a[n] (minpoly()). Multiply all the coefficients by their common denominator to turn them into integers (numerator()), then write this polynomial in the desired output format,

*a[n] +a[n-1] *x +a[n-2] *x … *x +a[1] *x +a[0]

SageMath, 102 bytes, almost

lambda s:(lambda a,*p:'*%d'%a+'*x'.join(map(' {:+} '.format,p)))(*numerator(minpoly(1/sage_eval(s))))

This works for all inputs except 0, because a polynomial for 1/α is a polynomial for α with the coefficients reversed.  :-(


Python, 100 92 89 bytes

lambda I:sum(reduce(lambda(a,s),i:(a+(a>0)*(-1,.5)[i=='Fly'],s+(a>0)),I.split(),(2.5,0)))

try it online


Befunge, 138 117 104 bytes

p&1v
%2:_v#:/2p9p00+1:g00
3\9g<>$\:!v!:<
9g!v ^,"}"_1-\1-:
"0"_2\"1{",,:|:,
`#@_\:#v_"}",>$\:8
,"0":-1<^

Try it online!

Explanation

Line 1 reads a number from stdin, and line 2 converts that number to a binary sequence which it stores in the playfield on line 10. Lines 3 to 5 then iterate over those binary digits, outputting the appropriate tree representation as each digit is processed. The Befunge stack is used to keep track of the depth into the tree and how much leaf space is left at each level so we know when to create a new branch. Lines 6 and 7 handle the final 0 padding to fill up any empty leaves.

In order to golf this as much as possible, I removed the commas from the output as well as the extraneous outer braces. This still hasn't beat the Mathematica solution, but it's been fun trying.

If you want to see what it looked like with the original verbose output format, I saved an earlier version of the code here (131 bytes).


Ruby -0p, 38 37 32 bytes
Saved 5 bytes thanks to a comment by @Sisyphus on another answer.

eval s="1until$_!='eval s=%p'%s"

Try it online!
The -0 flag sets the null byte as the input record separator. Without -0, a loop would also be entered if the input consisted of the code repeated on more than one line.


Which is better - Emacs or Vim? (Google fight)

Ruby, 203 180 bytes

->*s{s.map{|x|[(open("http://www.google.com/search?nord=1&q=#{URI.escape x}&nfpr=1").read.match(/s">(About )?([\d,]+) result/)||[?0])[-1].split(?,).join.to_i,x]}.max[1]}

+11 bytes for the -ropen-uri flag (plus space).

Input is taken as two arguments.

URL explanation:

?nord=1: prevent auto-redirect from HTTP to HTTPS
&q=#{URI.escape x}: escape the query so "s work
&nfpr=1: no autocorrect

The whole map turns ['emacs','vim'] into [[2150000, 'emacs'], [14900000, 'vim']]. (You can see this by changing the .max[1] at the end to .inspect.) Then, the max is taken, which will grab the one with the most results, and [1] is used to get the search term.


Vim, 16, 12 bytes/keystrokes

#<C-v>Nj*yggVGp

Try it online! in the V interpreter

  Modern text editors are very good at manipulating text. Are modern programming languages up to the task?

I bet old text editors are even better! :D

Even though it doesn't necessarily have to, this answer does work with both of the given "invalid" inputs, outputting

 rectangular (
) which is ill

and

(The lines must already be square
so this line that is too short
relative to this end, is illegal)

Explanation:

#               " Move backward to the previous occurrence of the word (or in this case, character) under the cursor
 <C-v>          " Start a visual block selection
      N         " Go to the next occurrence of the last searched term (guaranteed to be line 1)
       j        " Move down a line
        *       " Move forward to the next occurrence of the character under the cursor
         y      " Yank (copy) the whole visually selected block
          gg    " Go to line 1
            VG  " Select every line
              p " And paste what we last copied over it, deleting the whole buffer and replacing it with the block


MATL, 4 bytes
BSXB

Try it at MATL Online
Explanation
    % Implicitly grab input as an array
    %   STACK: [10, 17, 19, 23]
B   % Convert each element to binary where each decimal number results in a row
    %   STACK: [0 1 0 1 0;
    %           1 0 0 0 1;
    %           1 0 0 1 1;
    %           1 0 1 1 1]
S   % Sort each column, placing all of the 1's at the bottom of each column
    %   STACK: [0 0 0 0 0;
    %           1 0 0 1 1;
    %           1 0 0 1 1;
    %           1 1 1 1 1]
XB  % Convert each row from its binary representation to its decimal number
    %   STACK: [0, 19, 19, 31]
    % Implicitly display the result


APL, score 3

Task 7: 3 / 1

∪

This is a built-in that – according to this discussion – can be considered an unnamed function.

Try it online on TryAPL.


Jelly, 57 + 32 = 89 bytes (cracked)

“¡ḟċ⁷Ḣṡ⁵ĊnɠñḂƇLƒg⁺QfȥẒṾ⁹+=?JṚWġ%Aȧ’
O‘ḅ256b¢*21%¢ḅ¢ḃ256’Ọ

Encrypted message:

EªæBsÊ$Ê³¢?r×Q4e²?ò[Ý6

As a hex-string:

4518AAE6421973CA
9724CAB3A23F72D7
AD18855134651810
B23F1CF25BDD9036

Explanation:

O‘ḅ256b¢*21%¢ḅ¢ḃ256’Ọ
O                     convert each into codepoint
 ‘ḅ256                convert from bijective base 256 to integer
      b¢              convert from integer to base N
        *21           map each to its 21th power
           %¢         modulo N
             ḅ¢       convert to integer from base N
               ḃ256’  convert from integer to bijective base 256
                    Ọ convert each from codepoint

Where N is encoded by the string “¡ḟċ⁷Ḣṡ⁵ĊnɠñḂƇLƒg⁺QfȥẒṾ⁹+=?JṚWġ%Aȧ’, which is the number 105587021056759938494595233483151378724567978408381355454441180598980268016731.

Also, this is the RSA method with N given above and public key 21. Cracking this is equivalent to finding the two prime factors of N.


gawk, 161 bytes

BEGIN{
    for(split("0 10 2 2 1 1 1 1",a);c=c<11;n=o=_){
        while(++$c>a[c]+1)$(c++)=0;
        for(i in a)n=$i?n$i i-1:n;
        for(i=10;i--;)if(d=gsub(i,i,n))o=d i o;
        if(n==o)print n
    }
}

(line breaks and tabs for clarity)

It's a simple counter which uses the fact that each number has a limited occurrence. For instance is 0 no more than one time in any number, 1 no more than 11 times, 2 no more than 3 times ... and so on.

This way there are only 124415 numbers to check.

It then creates all numbers and checks their validity.

Completes in a few seconds.


Smallest integers after N divisible by 2, 3, and 4

Python 2, 32 bytes

lambda n:[n+2&-2,n/3*3+3,n+4&-4]

Bit arithmetic for 2 and 4, modular arithmetic for 3.
I found four 7-byte expressions for the next multiple of k above n but none shorter:
n-n%k+k
~n%k-~n
n/k*k+k
~n/k*-k

Any gives 34 bytes when copies for k=2,3,4, and 33 bytes if combined:
[n/2*2+2,n/3*3+3,n/4*4+4]
[n/k*k+k for k in 2,3,4]

But, 2 and 4 are powers of 2 that allow bit tricks to zero out the last 1 or 2 bytes.
n+2&-2
n+4&-4

This gives 6 bytes (instead of 7) for getting the next multiple, for 32 bytes overall, beating the for k in 2,3,4.
Unfortunately, the promising-looking n|1+1 and n|3+1 have the addition done first, so incrementing the output takes parentheses.


Ruby, histocrat

Description

Changed x to be an array instead of scalar by adding *

Changed the last 9 to be a string instead of a number by adding ?

The result is made of an array with a single element ([9]) multipled 9 times then imploded with "9" as separator.

Code

x=*9;puts x*9*?9