Build a 2-way universal logic processor using NAND logic gates

11 NANDs

Define the gate MUX (cost 4) as

MUX(P, Q, R) = (P NAND Q) NAND (NOT P NAND R)

with truth table

P Q R    (P NAND Q)   (NOT P NAND R)    MUX
0 0 0        1               1           0
0 0 1        1               0           1
0 1 0        1               1           0
0 1 1        1               0           1
1 0 0        1               1           0
1 0 1        1               1           0
1 1 0        0               1           1
1 1 1        0               1           1

Then this is the familiar ternary operator MUX(P, Q, R) = P ? Q : R

We simply have

2ULP = MUX(A, MUX(B, L_ab, L_a), MUX(B, L_b, L_))

for a cost 12, but there's a trivial one-gate saving by reusing the NOT B from the two inner MUXes.


Python 3, 289 263 bytes

Found a more complete library on Pypi: mendeleev

from mendeleev import*
Z={element(i).symbol for i in range(1,119)}
L,R='[]'
def f(h,r=''):t=h.title();return((Z&{t[0]}and f(h[1:],r+L+t[0]+R)or[])+(Z>{(t+L)[:2]}and f(h[2:],r+L+t[:2]+R)or[])+(not{(r[-1:]+t[0]).title(),t[0]}&Z and f(h[1:],r+h[0])or[]))if h else[r]

Old answer:

from elements import*
Z={e.symbol for e in ELEMENTS}|{*'Cn Ds Fl Lv Mc Nh Og Rg Ts'.split()}
L,R='[]'
def f(h,r=''):t=h.title();return((Z&{t[0]}and f(h[1:],r+L+t[0]+R)or[])+(Z>{(t+L)[:2]}and f(h[2:],r+L+t[:2]+R)or[])+(not{(r[-1:]+t[0]).title(),t[0]}&Z and f(h[1:],r+h[0])or[]))if h else[r]

Uses a library elements.py from http://www.lfd.uci.edu/~gohlke/code/elements.py.html.  It is missing elements 110 to 118, but it was the most up to date library I could find. Cost 40 bytes to add the missing elements.

The trickiest part was the logic for when a character can be passed through without being part of an element symbol.


Determine the lexicographical permutation your code is in

brainfuck, bytes = score

...

Try it online!

How it works: this program only has one distinct permutation and it outputs 0. It trivially satisfies all the other restrictions. The score can be made arbitrarily large by adding more ..


Jelly, 10 bytes

Zœṗ@+\€Ẏð/

Try it online! and The Last Test Case
 (With a G at the end for readability).

Input is taken as a list [M, H, V].

Explanation

Zœṗ@+\€Ẏð/  Input: [M, H, V]
        ð/  Insert the previous (f) as a dyadic link
            Forms f( f(M, H) , V)
            For f(x, y):
Z             Transpose x
 œṗ@          Partition the rows of x^T at each true in y
    +\€       Compute the cumulative sums in each partition
       Ẏ      Tighten (Joins all the lists at the next depth)


American Gothic in the palette of Mona Lisa: Rearrange the pixels

Java - GUI with progressive randomized transformation
I tried a LOT of things, some of them very complicated, then I finally came back to this relatively-simple code:
import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.Timer;

@SuppressWarnings("serial")
public class CopyColors extends JFrame {
    private static final String SOURCE = "spheres";
    private static final String PALETTE = "mona";
    private static final int COUNT = 10000;
    private static final int DELAY = 20;
    private static final int LUM_WEIGHT = 10;

    private static final double[] F = {0.114, 0.587, 0.299};
    private final BufferedImage source;
    protected final BufferedImage dest;
    private final int sw;
    private final int sh;
    private final int n;
    private final Random r = new Random();
    private final JLabel l;

    public CopyColors(final String sourceName, final String paletteName) throws IOException {
        super("CopyColors by aditsu");
        source = ImageIO.read(new File(sourceName + ".png"));
        final BufferedImage palette = ImageIO.read(new File(paletteName + ".png"));
        sw = source.getWidth();
        sh = source.getHeight();
        final int pw = palette.getWidth();
        final int ph = palette.getHeight();
        n = sw * sh;
        if (n != pw * ph) {
            throw new RuntimeException();
        }
        dest = new BufferedImage(sw, sh, BufferedImage.TYPE_INT_RGB);
        for (int i = 0; i < sh; ++i) {
            for (int j = 0; j < sw; ++j) {
                final int x = i * sw + j;
                dest.setRGB(j, i, palette.getRGB(x % pw, x / pw));
            }
        }
        l = new JLabel(new ImageIcon(dest));
        add(l);
        final JButton b = new JButton("Save");
        add(b, BorderLayout.SOUTH);
        b.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(final ActionEvent e) {
                try {
                    ImageIO.write(dest, "png", new File(sourceName + "-" + paletteName + ".png"));
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

    protected double dist(final int x, final int y) {
        double t = 0;
        double lx = 0;
        double ly = 0;
        for (int i = 0; i < 3; ++i) {
            final double xi = ((x >> (i * 8)) & 255) * F[i];
            final double yi = ((y >> (i * 8)) & 255) * F[i];
            final double d = xi - yi;
            t += d * d;
            lx += xi;
            ly += yi;
        }
        double l = lx - ly;
        return t + l * l * LUM_WEIGHT;
    }

    public void improve() {
        final int x = r.nextInt(n);
        final int y = r.nextInt(n);
        final int sx = source.getRGB(x % sw, x / sw);
        final int sy = source.getRGB(y % sw, y / sw);
        final int dx = dest.getRGB(x % sw, x / sw);
        final int dy = dest.getRGB(y % sw, y / sw);
        if (dist(sx, dx) + dist(sy, dy) > dist(sx, dy) + dist(sy, dx)) {
            dest.setRGB(x % sw, x / sw, dy);
            dest.setRGB(y % sw, y / sw, dx);
        }
    }

    public void update() {
        l.repaint();
    }

    public static void main(final String... args) throws IOException {
        final CopyColors x = new CopyColors(SOURCE, PALETTE);
        x.setSize(800, 600);
        x.setLocationRelativeTo(null);
        x.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        x.setVisible(true);
        new Timer(DELAY, new ActionListener() {
            @Override
            public void actionPerformed(final ActionEvent e) {
                for (int i = 0; i < COUNT; ++i) {
                    x.improve();
                }
                x.update();
            }
        }).start();
    }
}

All the relevant parameters are defined as constants at the beginning of the class.
The program first copies the palette image into the source dimensions, then repeatedly chooses 2 random pixels and swaps them if that would get them closer to the source image. "Closer" is defined using a color distance function that calculates the difference between the r, g, b components (luma-weighted) together with the total luma difference, with a greater weight for luma.
It takes just a few seconds for the shapes to form, but a while longer for the colors to come together. You can save the current image at any time. I usually waited about 1-3 minutes before saving.
Results:
Unlike some other answers, these images were all generated using the exact same parameters (other than the file names).
American Gothic palette

Mona Lisa palette

Starry Night palette

The Scream palette

Spheres palette
I think this is the toughest test and everybody should post their results with this palette:

Sorry, I didn't find the river image very interesting so I haven't included it.
I also added a video at https://www.youtube.com/watch?v=_-w3cKL5teM , it shows what the program does (not exactly in real-time but similar) then it shows the gradual pixel movement using Calvin's python script. Unfortunately the video quality is significantly damaged by youtube's encoding/compression.


Accentuated abjad English (ōcćnt̮ōt̖d ōbj̄d óngḷsh)

GNU sed, 168 158 134 105 98 85 byt̖s

ǒr 75 ch̠rs (b̭th ȯncl̮ḍng +1 f̭r th̖ -r fl̠g).

s/([bdfhklt])([aeiou])/\1\u\2/g;y/aeiouAEIOU/̠̖̣̭̮̄́̇̌̑/;s/\B[^ ,a-z]/o&/g

óxpl̠n̄ṭǒn

Wó s̄v́ ō ḅt ȏṡng th̖ čnstr̄ȯnt th̠t ȯnp̑t ȯs ōll ḽẃr-c̄ś.  Wó ȏpc̄ś ōny v̌ẃl f̭lḽẇng ō čnšn̄nt, b̖f̭ŕ čnv́rṭng ōll v̌ẃls ṱ ōcćnts.

#!/bin/sed -rf

s/([bdfhklt])([aeiou])/\1\u\2/g  # upcase vowel following ascender
y/aeiouAEIOU/̠̖̣̭̮̄́̇̌̑/
s/\B[^ ,a-z]/o&/g                # precede with 'o' if needed

Th̖ ǒdd-ḽǒḳng ch̠r̄ct̖rs ōŕ // čnt̠ȯṅng ōll t̖n ōcćnts (/̠̖̣̭̮̄́̇̌̑/).  óxp̄nd̖d ǒȏt ẇth sp̄ćs, th̖y w̌ȏld ḽǒk ḷk̖ / ̄ ́ ̇ ̌ ̑  ̠ ̖ ̣ ̭ ̮ /.

ǒȏtp̑t

přgr̄mṁng p̑zzl̖s ōnd čd̖ ǧlf
th̖ q̑ȯck břwn f̭x j̑mps ǒv́r th̖ l̠zy ḓg
b̖ōȏṭf̮l
ǒń ṙng ṱ ȓl̖ th̖m ōll, ǒń ṙng ṱ f̣nd th̖m, ǒń ṙng ṱ bṙng th̖m ōll ōnd ȯn th̖ d̠rkńss ḅnd th̖m


Z shell, 12 bytes

grep "$@"<$0

Zsh conditionals understand only exit codes, and the scripts exits with 0 or 1 accordingly.

In addition, this prints a non-empty string (the source code) for a match and an empty one for a mismatch, which could be as truthy/falsy values in combination with test/[.

The program reads its own file, but according to this comment by the OP, this is allowed.


Wave-Particle Duality Laterally Programmatically

C, 69 bytes

p;f(char*s){p=s[strlen(s)-1]^46;p^=p?93:3022856;printf("%s%s",s,&p);}

This requires a little-endian machine, and output to a terminal that support ASCII escape codes.

p=s[strlen(s)-1]^46 grabs the last ASCII code of the input string, and XORs it with the ASCII code of a dot.

p^=p?93:3022856 will cause p to be p^93 if the ASCII code is not a (back)slash, where p^46^93 == p^115, which will toggle between back and forward slash. If p is a dot, it will instead be 3022856, which is little-endian for "\b .".

printf("%s%s",s,&p); prints the input string followed by the integer p, interpreted as a little-endian byte string.


Pentagonal numbers made from pentagonal numbers

CJam, 29 bytes

6e5{)_3*(*2/}%_A4#<riew::+&1<

Try it online.

Takes a couple of seconds to run.

Explanation

First, we need to check how many pentagonal numbers we need to consider as potential sums. The sum of the first 10,000 pentagonal numbers is 500050000000. The first pentagonal number greater than that is the 577,380th.

6e5       e# 600,000 (a short number that's a bit bigger than we need).
{         e# Map this block onto every number from 0 to 599,999...
  )       e#   Increment.
  _3*(*2/ e#   Apply the pentagonal number formula given in the challenge.
}%
_         e# Make a copy.
A4#<      e# Truncate to the first 10,000 elements.
ri        e# Read input and convert to integer.
ew        e# Get sublists of that length.
::+       e# Sum each sublist.
&         e# Set intersection with all 600k pentagonal numbers computed earlier.
1<        e# Truncate to the first result.

I used a slightly modified program to find the largest inputs which yield a non-empty solution. These are all the solutions for inputs greater than 9,000:

9919 -> 496458299155
9577 -> 446991927537
9499 -> 455533474060
9241 -> 401702906276
9017 -> 429351677617


8086 machine code (MS-DOS .COM), score 26 402

The file is 52 947 bytes long. The length was a product of what produced benign instruction sleds, and the maximum file size for .COM files (65 280 bytes -- 65 264 in case an interrupt happens before you can stop it).

Here in binary form, with repeating lines snipped out for obvious reasons:

00000000 : E9 67 67 67 67 67 67 67 67 67 67 67 67 67 67 67 : .ggggggggggggggg
00000010 : 67 67 67 67 67 67 67 67 67 67 67 67 67 67 67 67 : gggggggggggggggg
    <...>
00006720 : 67 67 67 67 67 90 D1 EE AD 93 AC E8 00 00 5A 2C : ggggg.........Z,
00006730 : 30 01 C2 3C 04 75 03 83 C2 02 D1 E0 D1 E0 01 C2 : 0..<.u..........
00006740 : 83 C2 1B B4 09 CD 21 CD 20 43 6F 64 65 24 47 6F : ......!. Code$Go
00006750 : 6C 66 24 61 6E 64 24 24 43 6F 64 69 6E 67 24 43 : lf$and$$Coding$C
00006760 : 68 61 6C 6C 65 6E 67 65 73 24 EB 9F 9F 9F 9F 9F : hallenges$......
00006770 : 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F : ................
    <...>
0000CE80 : 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F 9F D1 : ................
0000CE90 : EE AD 93 AC E8 00 00 5A 2C 30 01 C2 3C 04 75 03 : .......Z,0..<.u.
0000CEA0 : 83 C2 02 D1 E0 D1 E0 01 C2 83 C2 1B B4 09 CD 21 : ...............!
0000CEB0 : CD 20 43 6F 64 65 24 47 6F 6C 66 24 61 6E 64 24 : . Code$Golf$and$
0000CEC0 : 24 43 6F 64 69 6E 67 24 43 68 61 6C 6C 65 6E 67 : $Coding$Challeng
0000CED0 : 65 73 24                                        : es$

In readable form:

org 0x100
cpu 8086

SLED_LEN    equ (0x6767 - (part1_end - part1) + 2)

db 0xe9
times SLED_LEN db 0x67

part1:
    nop
    shr si, 1       ; SI = 0x80
    lodsw           ; SI = 0x82
    xchg bx, ax     ; AX = 0
    lodsb           ; AL = first character of command line argument

    ; Load DX with IP, since we only know our strings' relative position
    call near .nextline
.nextline:
    pop dx

    sub al, '0'
    add dx, ax
    cmp al, 4
    jne .skip
    add dx, 2

.skip:
    shl ax, 1
    shl ax, 1
    add dx, ax

    add dx, 0x1b
    mov ah, 0x09
    int 0x21
    int 0x20

p1_msg0 db "Code$"
p1_msg1 db "Golf$"
p1_msg2 db "and$$"
p1_msg3 db "Coding$"
p1_msg4 db "Challenges$"

part1_end:

part2:
    db 0xeb
    times SLED_LEN db 0x9f

    shr si, 1       ; SI = 0x80
    lodsw           ; SI = 0x82
    xchg bx, ax     ; AX = 0
    lodsb           ; AL = first character of command line argument

    ; Load DX with IP, since we only know our strings' relative position
    call near .nextline
.nextline:
    pop dx

    sub al, '0'
    add dx, ax
    cmp al, 4
    jne .skip
    add dx, 2

.skip:
    shl ax, 1
    shl ax, 1
    add dx, ax

    add dx, 0x1b
    mov ah, 0x09
    int 0x21
    int 0x20

p2_msg0 db "Code$"
p2_msg1 db "Golf$"
p2_msg2 db "and$$"
p2_msg3 db "Coding$"
p2_msg4 db "Challenges$"

Rundown

This is a slightly adapted variation on a previous answer of mine.

The active part is duplicated so that there is always one untouched by radiation. We select the healthy version by way of jumps. Each jump is a near jump, and so is only three bytes long, where two last bytes are the displacement (i.e. distance to jump, with sign determining direction). This displacement is replicated over and over, forming a long NOP sled of sorts.

We can divide the code into four parts which could be irradiated: jump 1, code 1, jump 2, and code 2. The idea is to make sure a clean code part is always used. If one of the code parts is irradiated, the other must be chosen, but if one of the jumps is irradiated, both code parts will be clean, so it will not matter which one is chosen.

The reason for having two jump parts is to detect irradiation in the first part by jumping over it. If the first code part is irradiated, it means we will arrive off mark, somewhere in the second NOP sled. If we make sure that such a botched landing selects code 2, and a proper landing selects code 1, we're golden.

For both jumps, we duplicate the displacement word, making each jump part one opcode followed by a massive repetition of the displacement. This ensures that irradiation somewhere in the sled will still make the jump valid, as long as at least two bytes of the sled remains. Irradiation in the first byte will stop the jump from happening at all, since the following sled will form a completely different instruction.

Take the first jump:

E9 67 67 67 67 ...      jmp +0x6767 / dw 0x6767 ...

If either of the 0x67 bytes are removed, it will still jump to the same place, as long as at least one word remains. If the 0xE9 byte is removed, we will instead end up with

67 67 67 67...

each of which is a address-size override prefix. The CPU will gladly chomp them all down, and then we fall through to code 1, which must be clean, since the damage was in jump 1.

If the jump is taken, we land at the second jump:

EB 9F 9F 9F 9F ...       jmp -0x61 / db 0x9f

If this byte sequence is intact, and we land right on the mark, that means that code 1 was clean, and this instruction jumps back to that part. The replicated displacement byte guarantees this, even if it is one of these displacement bytes that were damaged.

The astute reader will notice that this instruction jumps too far back, but that's alright, since if we hit the jump, then part1's NOP sled must be wholly intact, making a slightly longer jump backwards okay.

If we either land off the mark (because of a damaged code 1 or jump 1) or the 0xEB byte is the damaged one, the remaining bytes will also here be benign:

9F 9F 9F 9F ...          lahf / lahf

Whichever the case, if we end up executing that sled of instructions, we know that either jump 1, code 1, or jump 2 were irradiated, which makes a fall-through to code 2 safe.

Testing

Testing proved problematic. I've done some tests on certain corner-cases and a few random ones, but I have to find a better way for exhaustive testing. It should not be a problem up to the above-mentioned score.

The following program was used to automatically create all versions of the .COM file for a certain gap size. It also creates a BAT file that can be run in the target environment, which runs each irradiated binary, and pipes their outputs to separate text files. Comparing the output files to validate is easy enough, but DOSBox does not have fc, so it was not added to the BAT file.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
    FILE *fin, *fout, *fbat;
    int fsize;
    char *data;
    int gapsize = 1;

    if (!(fin = fopen(argv[1], "rb")))
    {
        fprintf(stderr, "Could not open input file \"%s\".\n", argv[1]);
        exit(1);
    }

    if (!(fbat = fopen("tester.bat", "w")))
    {
        fprintf(stderr, "Could not create BAT test file.\n");
        exit(2);
    }

    if (argc > 2)
    {
        gapsize = atoi(argv[2]);
    }

    fseek(fin, 0L, SEEK_END);
    fsize = ftell(fin);
    fseek(fin, 0L, SEEK_SET);

    if (!(data = malloc(fsize)))
    {
        fprintf(stderr, "Could not allocate memory.\n");
        exit(3);
    }

    fread(data, 1, fsize, fin);

    fprintf(fbat, "@echo off\n");

    for (int i = 0; i <= fsize - gapsize; i++)
    {
        char fname[512];

        sprintf(fname, "%06d.com", i);

        for (int j = 0; j < 5; j++)
            fprintf(fbat, "%s %d >> %06d.txt\n", fname, j, i);

        fout = fopen(fname, "wb");

        fwrite(data, 1, i, fout);
        fwrite(data + i + gapsize, 1, fsize - i - gapsize, fout);

        fclose(fout);
    }

    free(data);
    fclose(fin);
    fclose(fbat);
}


Bad matrix multiplication that gives the right answer

Python, N = 7
Using variable neighborhood search over elementary row and column operations.  Not every seed works quickly (or at all?), but seed 9 finds a solution for N = 7 in a few seconds.
$ time python3 search.py 7 9
[[0 3 6 6 1 6 6]
 [0 1 5 5 0 5 5]
 [1 3 1 2 1 8 1]
 [0 0 1 0 0 1 0]
 [1 7 9 9 0 9 9]
 [1 3 1 1 1 0 1]
 [0 0 1 1 0 1 1]]
[[5 5 1 1 0 4 0]
 [1 7 0 0 1 0 0]
 [0 0 9 4 0 1 5]
 [0 0 0 5 0 0 5]
 [2 2 1 1 7 4 0]
 [0 0 1 1 0 9 0]
 [0 2 0 0 0 0 0]]

real    0m4.909s
user    0m4.883s
sys     0m0.026s

Code
import itertools
import sys

import numpy as np

def search(depth, C, D, best):
    A = C + I
    B = D + 10 * I
    x = np.r_[A, B].flatten()
    score = (
        np.maximum(0, np.maximum(x - 9, 1 - x)).sum()
        - min((A == 0).sum(), -(-n * n // 2))
        - min((B == 0).sum(), -(-n * n // 2))
        + 2 * n
        - np.linalg.matrix_rank(A)
        - np.linalg.matrix_rank(B)
    )
    if best is None or score < best:
        return C, D, score
    if depth == 0:
        return None

    tried = {}
    for i in reversed(range(n * (n - 1) * 5)):
        j = rng.integers(i + 1)
        mutation, tried[j] = tried.get(j, j), tried.get(i, i)
        p, mutation = divmod(mutation, (n - 1) * 5)
        q, mutation = divmod(mutation, 5)
        q = (p + q + 1) % n
        C1 = C.copy()
        D1 = D.copy()

        if mutation == 0:
            C1[p, :] += C1[q, :]
            D1[:, q] -= D1[:, p]
        elif mutation == 1:
            C1[p, :] -= C1[q, :]
            D1[:, q] += D1[:, p]
        elif mutation == 2:
            C1[:, p] += C1[:, q]
            D1[q, :] -= D1[p, :]
        elif mutation == 3:
            C1[:, p] -= C1[:, q]
            D1[q, :] += D1[p, :]
        elif p < q:
            C1[[p, q], :] = C1[[q, p], :]
            D1[:, [p, q]] = D1[:, [q, p]]
        else:
            C1[:, [p, q]] = C1[:, [q, p]]
            D1[[p, q], :] = D1[[q, p], :]

        ret = search(depth - 1, C1, D1, best)
        if ret is not None:
            return ret

    return None

n, seed = map(int, sys.argv[1:])
rng = np.random.default_rng(seed)
I = np.eye(n, dtype=int)
score = None
k = rng.integers(0, 8, n)
C = np.diag(np.array([-10, -5, -2, -1, 1, 2, 5, 10])[k])
D = np.diag(np.array([-1, -2, -5, -10, 10, 5, 2, 1])[k])
depth = 1

while score != 0:
    ret = search(depth, C, D, score)
    if ret is not None:
        C, D, score = ret
        depth = 0
    depth += 1

A = C + I
B = D + 10 * I
assert (A @ B == 10 * A + B).all()
print(A)
print(B)


Haskell, 63 55 bytes

Since no one has done Haskell yet here's my take on it.  Takes a string as input (of course).

import Data.List
f s=product[read x|x@(_:_:_)<-group s]

Try it online!

This code almost looks as if it is not golfed, but I cannot find anyway to make it shorter.


C, 18 bytes

Pretty easy, but let's do it just for fun...

puts("-1"+*i/8%2);

Given the string char *i it prints 1 for heads and -1 for tails, with trailing newline.

Explanation

In C, "-1" + 1 points to 1 character forward, so it is the same as "1". Let's take a look at the first characters:

"heads"[0] = 'h' = 104 = 0b01101000
"tails"[0] = 't' = 116 = 0b01110100

If we count the bits from the rightmost one starting at zero, bit 3 is 1 in heads and 0 in tails: summing it to "-1" gives the right string. It looks like this:

"-1" + ((i[0] >> 3) & 1)

Now, substitute i[0] with *i and the right shift with the power-of-two division to save some bytes. Also remove useless parentheses:

"-1" + (*i / 8 & 1)

Now, & 1 can be substituted with % 2. The character count is the same, but the modulus has higher priority, allowing to drop the parentheses. Remove the whitespace:

"-1"+*i/8%2

Bonus

I think the shortest way to get an integer 1 or -1 (not a string) in C is:

18-*i/6

Explanation:

'h' = 104
't' = 116

('h' + 't') / 2 = 110
110 - 'h' =  6
110 - 't' = -6

(110 - 'h') / 6 =  1
(110 - 't') / 6 = -1

Apply distributive property (integer division):
18 - 'h' / 6 =  1
18 - 't' / 6 = -1


JavaScript (ES6), 297 286 279 267 bytes

Takes input in currying syntax (s)(k), where s is an array of digit characters and k is the number of moves (integer).

s=>k=>(B=(n,b=0)=>n?B(n^n&-n,b+1):b,b=[...p='u"[k,iy#}m'].map(c=>c.charCodeAt()+2),r=[],g=(n,d='')=>n?n>0&&b.map((v,i)=>g(n-B(v),d+i)):r.push(d))(s.reduce((s,c)=>s+B(b[c]),M=0))&&b.map((_,j)=>r.map(n=>M=[...n+p].reduce((t,d,i)=>t+B(b[d]^b[s[i-j]]),0)>k*2|+n<M?M:n))|M

Test cases

let f=

s=>k=>(B=(n,b=0)=>n?B(n^n&-n,b+1):b,b=[...p='u"[k,iy#}m'].map(c=>c.charCodeAt()+2),r=[],g=(n,d='')=>n?n>0&&b.map((v,i)=>g(n-B(v),d+i)):r.push(d))(s.reduce((s,c)=>s+B(b[c]),M=0))&&b.map((_,j)=>r.map(n=>M=[...n+p].reduce((t,d,i)=>t+B(b[d]^b[s[i-j]]),0)>k*2|+n<M?M:n))|M

console.log("0   / 1 -> " + f([..."0"  ])(1)) // -> 9
console.log("0   / 3 -> " + f([..."0"  ])(3)) // -> 77
console.log("0   / 4 -> " + f([..."0"  ])(4)) // -> 111
console.log("8   / 3 -> " + f([..."8"  ])(3)) // -> 74
console.log("220 / 1 -> " + f([..."220"])(1)) // -> 320
console.log("220 / 2 -> " + f([..."220"])(2)) // -> 520
console.log("220 / 3 -> " + f([..."220"])(3)) // -> 7227
console.log("220 / 4 -> " + f([..."220"])(4)) // -> 22111
console.log("220 / 5 -> " + f([..."220"])(5)) // -> 32111
console.log("747 / 1 -> " + f([..."747"])(1)) // -> 747
console.log("747 / 2 -> " + f([..."747"])(2)) // -> 7171
console.log("747 / 3 -> " + f([..."747"])(3)) // -> 7711

How?

Shape data and helper function

The array b describes the shapes of the digits as 7-bit integers, where each bit is a segment:

For instance, the shape of "7" is 0b0100101 = 37.
The helper function B() returns the number of 1's in the binary representation of a given number:

B = (n, b = 0) => n ? B(n ^ n & -n, b + 1) : b

Step #1

We first count the number of matchsticks used in the input number:

s.reduce((s, c) => s + B(b[c]), 0)

Step #2

We pass this value to the recursive function g(), which populates a list r with all numbers that can be built with exactly this number of matchsticks:

g = (n, d = '') =>
  n ?
    n > 0 &&
    b.map((v, i) => g(n - B(v), d + i))
  :
    r.push(d)

For instance, g(5) will load [ '17', '2', '3', '5', '71' ] into r.

Step #3

We now have to select the highest number M in r which can actually be obtained from the input number, within the allowed number of moves k.

Because each number n in r uses exactly as many matchsticks as the input number s, the number of moves required to transform s into n equals half the number of segment differences between each of their digits.

The number of segment differences between two digits x and y is given by the number of 1's in the binary representation of b[x] XOR b[y].

Finally, it's important to note that we need to try several possible digit alignments, because the first digit of s is not necessarily mapped to the first digit of n. The shift between the digits is given by the variable j in the code.


Python 3, 747 369 335 bytes

As an example answer, only slightly golfed, and to give you an idea of what an answer will look like.
And yes, the prime factorization and run-length-encoding bits are cribbed from Pyth with apologies to isaacg.
from itertools import*
def k(d,r):
 if d<0:a=-d;m=1
 else:a=d;m=0
 if r==1:return 1
 p=1;w=r;n=2;f=[]
 while n*n<=w:
  while w%n<1:w//=n;f+=n,
  n+=1
 if w>1:f+=w,
 z=[[k,len(list(g))]for k,g in groupby(f)]
 for i,j in z:
  if i==2:p*=pow(-1,(a*a-1)//8)
  x=pow(a,(i-1)//2,i)
  if x>1:x-=i
  p*=x**j
 if m:p*=pow(-1,(r-1)//2)
 return p


Coding a recursive function for highest possible input

Java

I've applied some algebraic transformation and dynamic programming.

public class CodeGolf42234 {
    public static void main(String[] args) {
        int r = Integer.parseInt(args[0]);
        for (int L = 1; L < r; L++) System.out.println(qDouble5(r, r-L, L));
    }

    private static double qDouble5(int _r, int _b, int L) {
        double[][] q = new double[_r+1][_b+1];
        for (int r = 0; r <= L; r++) {
            for (int b = 0; b < q[r].length; b++) q[r][b] = 1;
        }
        for (int r = L + 1; r < q.length; r++) {
            for (int b = 1 + (r - L - 1)/L; b < q[r].length; b++) {
                double sum = 0, m = 1;
                for (int k = 0; k <= L; k++) {
                    sum += m * q[r-k][b-1];
                    m = m * (r - k) / (r + b - 1 - k);
                }
                q[r][b] = sum * b / (r + b);
            }
        }
        return q[_r][_b];
    }
}


Find longest consecutive characters in 2D array

Charcoal, 110 bytes

≔⪫Ａ⸿θＰθＦθ«≔⟦⟧ηＦ∧¬№0⸿ι⟦→↘↓↙⟧«≔ＫＤＬθ✳κζＷ›Ｌζ№ζι≔⊟ζε⊞η⟦κιＬζ⟧»¿⁼¹⌈Ｅη§κ²⊞υ⊟ηＦη⊞υκι»⎚≔⌈Ｅυ§ι²εＦΦυ⁼⊟ιε«⊟ι,Ｉε,Ｐ✳⊟ι⎇⊖ε¹.¦⸿

Try it online! Link is to verbose version of code. Takes an array of strings as input. Explanation:

≔⪫Ａ⸿θＰθ

Join the strings with carriage returns (not newlines) and output them without moving the cursor.

Ｆθ«

Loop over each character in the string.

≔⟦⟧η

Collect all of the consecutive characters starting at this position in an array.

Ｆ∧¬№0⸿ι⟦→↘↓↙⟧«

If the current character is not a 0 or a carriage return, then check all four directions.

≔ＫＤＬθ✳κζ

Peek as much as possible in that direction.

Ｗ›Ｌζ№ζι≔⊟ζε

Shorten the string until all of the characters are the same.

⊞η⟦κιＬζ⟧»

Save the results in the array.

¿⁼¹⌈Ｅη§κ²⊞υ⊟ηＦη⊞υκ

If the maximum consecutive character was 1, then only push one of the results to the final array, otherwise push all of them.

ι»

Reprint the current character, this time allowing the cursor to move.

⎚

Clear the input from the canvas.

≔⌈Ｅυ§ι²ε

Find the longest consecutive length.

ＦΦυ⁼⊟ιε«

Loop over the entries with that length.

⊟ι,Ｉε,

Output the character and length.

Ｐ✳⊟ι⎇⊖ε¹.¦⸿

If the length is 1 then output a . otherwise output a direction character. Then move to the start of the next line for the next result.


Perl on Linux, 17 bytes

I thought it might be interesting to create a program that doesn't maintain any state itself, and doesn't modify its own source code; in other words, it actually checks how often it's been run by asking the OS. The question says "Any facilities used for storage may be assumed to be empty before the first execution of the program.", and thus we'd want to start from a completely blank OS. As such, I'd better explain just how you go about doing that, as otherwise testing the program is difficult.

There are actually two ways to set up for running the program. Either way, the minimal OS for the purpose would be running nothing but a shell (to enable us to run Perl in turn), and the simplest possible shell at that (so that it doesn't do anything fancy that makes the OS non-blank). /bin/dash is a good choice here, as it was intended as a minimal shell for system recovery. Then, we need to start Linux in such a way that it's running nothing but dash. We can either do this by rebooting the computer with init=/bin/dash on the Linux command line so that it starts nothing besides dash, or (much more conveniently) creating a Linux container using unshare -Urfp /bin/dash in a terminal (unshare doesn't actually create a blank OS, but it does simulate one; notably, the inside of the container thinks it's root, dash thinks it's init, etc., just as would happen on an actual blank OS). Disclaimer: I haven't actually tested this on bare metal yet, only inside unshare, but it should work both ways in theory.

Finally, once we've got that set up, we simply have to look at the PID; as we're on a blank system, the init system (here, the shell) will have PID 1, so the executions of Perl will have PIDs from 2 up to 12 inclusive. So our program looks like this:

say 12-$$||die

Here's a sample run:

$ unshare -Urfp /bin/dash
# perl -E 'say 12-$$||die'
10
# perl -E 'say 12-$$||die'
9
# perl -E 'say 12-$$||die'
8
# perl -E 'say 12-$$||die'
7
# perl -E 'say 12-$$||die'
6
# perl -E 'say 12-$$||die'
5
# perl -E 'say 12-$$||die'
4
# perl -E 'say 12-$$||die'
3
# perl -E 'say 12-$$||die'
2
# perl -E 'say 12-$$||die'
1
# perl -E 'say 12-$$||die'
Died at -e line 1.
#


CJam, 89 81 bytes

q~"><v^":A2/{f{\*}z}/sA[1W52-52]er:T,,{[52md]51f%0e=1=},:E{[2704{__T=+}*]\-E&},,g

Try it online in the CJam interpreter.

How it works

q~        e# Read and evaluate all input. This pushes an array of strings.
"><v^":A  e# Push that string and save it in A.
2/        e# Split it into ["><" "v^"].
{         e# For each chunk:
  f{      e#   For each input string, push the string and the chunk; then:
    \*    e#     Join the chunk, using the string as separator.
  }       e#
  z       e#   Transpose rows and columns.
}/        e#
s         e# Flatten the resulting array of strings.
A         e# Push "><v^".
[1W52-52] e# Push [1 -1 52 -52].
er        e# Perform transliteration.
:T        e# Save the result in T.
,,        e# Push [0 ... 2703].
{         e# Filter; for each integer I in [0 ... 2703]:
  [52md]  e#   Push [I/52 I%52].
  51f%    e#   Take both integers modulo 51 to map 51 to 0.
  0e=     e#   Count the number of resulting zeroes.
  1=      e#   Check if the count is 1.
},        e# If it is, keep I.
:E        e# Save the filtered array in E.
{         e# For each integer I in E:
  [2704{  e#   Do 2704 times:
    __    e#     Push two copies of the integer on the stack.
    T=    e#     Select the corresponding element from T.
    +     e#     Add it to the first copy.
  }*]     e#   Collect all results in an array.
  \-      e#   Remove I from that array.
  E&      e#   Intersect with E.
},        e# If the intersection is non-empty, keep the integer.
,g        e# Push the sign of the length of the filtered array.


05AB1E, 207 bytes

þ"! ! ABC DEF GHI JKL MNO PQRS TUV WXYZ"S#sSèU
"€‚ƒ„…†‡ˆ‰Š‹ŒŽ•–—™š›œžŸ¡¢£¤¥¦§¨©ª«¬®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîï"©vyV®vYy«"“ÿ“".Vu}})
ʒg¹þgQ}
ʒ´vXNèyåˆ}¯P}
¹þg7Q¹þgTQ&i´¯}

Try it online!

(1) The first line of the code, will replace each number in the input with the corresponding set of possible letters.

þ                                              # Only digits of input.
 "! ! ABC DEF GHI JKL MNO PQRS TUV WXYZ"       # Push keypad letters.
                                        S#     # Split into list and on spaces.
                                          sS   # Split input into digits.
                                            èU # Push indexes of digits and store in X.

(2) The second line of the code, will push every possible dictionary word that is stored in 05AB1E. It accomplishes this by pushing all pairings of the dictionary encrypted characters and converting them to their dictionary stored equivalents. There are 100 unique dictionary characters, and 100*100 unique pairs of them. This means we are getting access to a total of 10,000 words from the 05AB1E dictionary.

(3) The third line of the code, will filter the dictionary by the length of the number of digits in the input.

(4) The fourth line of the code, will filter again the words from the dictionary which match the filter of possible letters outlined by line #1.

(5) The final line of the code, will simply return an empty array provided that the input was not 7 or 10 digits long after parsing.

Using no external libraries/files, this code can detect any word that is in the 05AB1E dictionary. More specifically, if the input is limited to 7 characters the following list:

["ABILITY", "ABRAHAM", "ABSENCE", "ACADEMY", "ACCEPTS", "ACCOUNT", "ACCUSED", "ACHIEVE", "ACQUIRE", "ACROBAT", "ACRYLIC", "ACTIONS", "ACTRESS", "ADAPTED", "ADAPTER", "ADAPTOR", "ADDRESS", "ADOPTED", "ADVANCE", "ADVERSE", "ADVISED", "ADVISOR", "AFFAIRS", "AFFECTS", "AFRICAN", "AGAINST", "AIRFARE", "AIRLINE", "AIRPORT", "ALABAMA", "ALBANIA", "ALBERTA", "ALCOHOL", "ALGEBRA", "ALGERIA", "ALLEGED", "ALLERGY", "ALLOWED", "ALREADY", "ALTERED", "AMATEUR", "AMAZING", "AMBIENT", "AMENDED", "AMERICA", "AMONGST", "AMOUNTS", "AMPLAND", "ANAHEIM", "ANALYST", "ANALYZE", "ANATOMY", "ANCIENT", "ANDORRA", "ANDREAS", "ANDREWS", "ANGELES", "ANIMALS", "ANOTHER", "ANSWERS", "ANTENNA", "ANTHONY", "ANTIGUA", "ANTIQUE", "ANTONIO", "ANXIETY", "ANYBODY", "ANYMORE", "ANYTIME", "APPAREL", "APPEALS", "APPEARS", "APPLIED", "APPLIES", "APPROVE", "AQUATIC", "ARCHIVE", "ARISING", "ARIZONA", "ARMENIA", "ARRANGE", "ARRIVAL", "ARRIVED", "ARRIVES", "ARTICLE", "ARTISTS", "ARTWORK", "ASPECTS", "ASSAULT", "ASSISTS", "ASSUMED", "ASSUMES", "ASSURED", "ATLANTA", "ATTACKS", "ATTEMPT", "ATTRACT", "AUCTION", "AUDITOR", "AUSTRIA", "AUTHORS", "AVERAGE", "AWARDED", "AWESOME", "BACKING", "BAGHDAD", "BAHAMAS", "BAHRAIN", "BALANCE", "BALLOON", "BANGBUS", "BANGKOK", "BANKING", "BANNERS", "BAPTIST", "BARBARA", "BARGAIN", "BARRIER", "BASKETS", "BATTERY", "BEACHES", "BEARING", "BEATLES", "BECAUSE", "BECOMES", "BEDDING", "BEDFORD", "BEDROOM", "BEIJING", "BELARUS", "BELFAST", "BELGIUM", "BELIEFS", "BELIEVE", "BELONGS", "BENEATH", "BENEFIT", "BENNETT", "BERMUDA", "BERNARD", "BESIDES", "BETTING", "BETWEEN", "BEVERLY", "BICYCLE", "BIDDING", "BIGGEST", "BILLING", "BILLION", "BINDING", "BIOLOGY", "BIZARRE", "BIZRATE", "BLANKET", "BLESSED", "BLOCKED", "BLOGGER", "BLOWING", "BLOWJOB", "BOATING", "BOLIVIA", "BONDAGE", "BOOKING", "BOOLEAN", "BORDERS", "BOROUGH", "BOTTLES", "BOULDER", "BOUQUET", "BOWLING", "BRACKET", "BRADLEY", "BRANDON", "BREASTS", "BRIDGES", "BRIEFLY", "BRISTOL", "BRITAIN", "BRITISH", "BRITNEY", "BROADER", "BROKERS", "BROTHER", "BROUGHT", "BROWSER", "BUDGETS", "BUFFALO", "BUILDER", "BUKKAKE", "BURNING", "BUTTONS", "CABINET", "CALCIUM", "CALGARY", "CALLING", "CAMERAS", "CAMERON", "CAMPING", "CANDLES", "CAPABLE", "CAPITAL", "CAPITOL", "CAPTAIN", "CAPTURE", "CARDIAC", "CARDIFF", "CAREERS", "CAREFUL", "CARRIED", "CARRIER", "CARRIES", "CARROLL", "CARTOON", "CASINOS", "CASTING", "CATALOG", "CAUSING", "CAUTION", "CEILING", "CENTERS", "CENTRAL", "CENTRES", "CENTURY", "CERAMIC", "CERTAIN", "CHAMBER", "CHANCES", "CHANGED", "CHANGES", "CHANNEL", "CHAPTER", "CHARGED", "CHARGER", "CHARGES", "CHARITY", "CHARLES", "CHARLIE", "CHARTER", "CHASSIS", "CHEAPER", "CHECKED", "CHELSEA", "CHESTER", "CHICAGO", "CHICKEN", "CHINESE", "CHOICES", "CHRONIC", "CIRCLES", "CIRCUIT", "CITIZEN", "CLAIMED", "CLARITY", "CLASSES", "CLASSIC", "CLEANER", "CLEANUP", "CLEARED", "CLEARLY", "CLIENTS", "CLIMATE", "CLINICS", "CLINTON", "CLOSELY", "CLOSEST", "CLOSING", "CLOSURE", "CLOTHES", "CLUSTER", "COACHES", "COASTAL", "COATING", "COLEMAN", "COLLECT", "COLLEGE", "COLLINS", "COLOGNE", "COLORED", "COLOURS", "COLUMNS", "COMBINE", "COMFORT", "COMMAND", "COMMENT", "COMMONS", "COMPACT", "COMPANY", "COMPARE", "COMPETE", "COMPILE", "COMPLEX", "COMPUTE", "CONCEPT", "CONCERN", "CONCERT", "CONCORD", "CONDUCT", "CONFIRM", "CONNECT", "CONSENT", "CONSIST", "CONSOLE", "CONSULT", "CONTACT", "CONTAIN", "CONTENT", "CONTEST", "CONTEXT", "CONTROL", "CONVERT", "COOKIES", "COOKING", "COOLING", "COPYING", "CORNELL", "CORNERS", "CORRECT", "COSTUME", "COTTAGE", "COUNCIL", "COUNSEL", "COUNTED", "COUNTER", "COUNTRY", "COUPLED", "COUPLES", "COUPONS", "COURAGE", "COURIER", "COURSES", "COVERED", "CREATED", "CREATES", "CREATOR", "CREDITS", "CRICKET", "CRITICS", "CROATIA", "CRUCIAL", "CRUISES", "CRYSTAL", "CUISINE", "CULTURE", "CUMSHOT", "CURIOUS", "CURRENT", "CUSTODY", "CUSTOMS", "CUTTING", "CYCLING", "DAMAGED", "DAMAGES", "DANCING", "DEALERS", "DEALING", "DEBORAH", "DECADES", "DECIDED", "DECIMAL", "DECLARE", "DECLINE", "DEFAULT", "DEFECTS", "DEFENCE", "DEFENSE", "DEFICIT", "DEFINED", "DEFINES", "DEGREES", "DELAYED", "DELETED", "DELIGHT", "DELIVER", "DEMANDS", "DENMARK", "DENSITY", "DEPENDS", "DEPOSIT", "DERIVED", "DESERVE", "DESIGNS", "DESIRED", "DESKTOP", "DESPITE", "DESTINY", "DESTROY", "DETAILS", "DETROIT", "DEUTSCH", "DEVELOP", "DEVIANT", "DEVICES", "DEVOTED", "DIAGRAM", "DIAMOND", "DIETARY", "DIGITAL", "DIPLOMA", "DISABLE", "DISCUSS", "DISEASE", "DISPLAY", "DISPUTE", "DISTANT", "DIVERSE", "DIVIDED", "DIVORCE", "DOCTORS", "DOLLARS", "DOMAINS", "DONATED", "DOUGLAS", "DRAWING", "DRESSED", "DRESSES", "DRIVERS", "DRIVING", "DROPPED", "DURABLE", "DYNAMIC", "EARLIER", "EARNING", "EASTERN", "ECLIPSE", "ECOLOGY", "ECONOMY", "ECUADOR", "EDITING", "EDITION", "EDITORS", "EDWARDS", "EFFECTS", "EFFORTS", "ELDERLY", "ELECTED", "ELECTRO", "ELEGANT", "ELEMENT", "ELLIOTT", "EMBASSY", "EMERALD", "EMPEROR", "ENABLED", "ENABLES", "ENDLESS", "ENEMIES", "ENGAGED", "ENGINES", "ENGLAND", "ENGLISH", "ENHANCE", "ENJOYED", "ENLARGE", "ENQUIRY", "ENSURES", "ENTERED", "ENTRIES", "EPISODE", "EQUALLY", "EROTICA", "ESCORTS", "ESSENCE", "ESTATES", "ESTONIA", "ETERNAL", "ETHICAL", "EVENING", "EVIDENT", "EXACTLY", "EXAMINE", "EXAMPLE", "EXCERPT", "EXCITED", "EXCLUDE", "EXECUTE", "EXHAUST", "EXHIBIT", "EXISTED", "EXPECTS", "EXPEDIA", "EXPENSE", "EXPERTS", "EXPIRED", "EXPIRES", "EXPLAIN", "EXPLORE", "EXPORTS", "EXPOSED", "EXPRESS", "EXTENDS", "EXTRACT", "EXTREME", "FABRICS", "FACTORS", "FACTORY", "FACULTY", "FAILING", "FAILURE", "FALLING", "FANTASY", "FARMERS", "FARMING", "FASHION", "FASTEST", "FATHERS", "FEATURE", "FEDERAL", "FEEDING", "FEELING", "FEMALES", "FERRARI", "FICTION", "FIFTEEN", "FIGHTER", "FIGURED", "FIGURES", "FILLING", "FILTERS", "FINALLY", "FINANCE", "FINDING", "FINDLAW", "FINGERS", "FINLAND", "FINNISH", "FIREFOX", "FISHING", "FISTING", "FITNESS", "FITTING", "FLIGHTS", "FLORIDA", "FLORIST", "FLOWERS", "FOCUSED", "FOCUSES", "FOLDERS", "FOLDING", "FOLLOWS", "FOOTAGE", "FOREIGN", "FORESTS", "FOREVER", "FORMATS", "FORMING", "FORMULA", "FORTUNE", "FORWARD", "FOUNDED", "FOUNDER", "FRAMING", "FRANCIS", "FREEBSD", "FREEDOM", "FREIGHT", "FRIENDS", "FUCKING", "FUJITSU", "FUNDING", "FUNERAL", "FURTHER", "FUTURES", "GABRIEL", "GADGETS", "GALLERY", "GARBAGE", "GARDENS", "GATEWAY", "GAZETTE", "GENERAL", "GENERIC", "GENESIS", "GENETIC", "GENUINE", "GEOLOGY", "GEORGIA", "GERMANY", "GETTING", "GILBERT", "GLASGOW", "GLASSES", "GLUCOSE", "GOURMET", "GRAMMAR", "GRANTED", "GRAPHIC", "GRATUIT", "GRAVITY", "GREATER", "GREATLY", "GREGORY", "GRENADA", "GRIFFIN", "GROCERY", "GROUNDS", "GROWING", "GUITARS", "HABITAT", "HALIFAX", "HAMBURG", "HAMPTON", "HANDJOB", "HANDLED", "HANDLES", "HANGING", "HAPPENS", "HARBOUR", "HARMFUL", "HARMONY", "HARVARD", "HARVEST", "HAZARDS", "HEADERS", "HEADING", "HEADSET", "HEALING", "HEALTHY", "HEARING", "HEATHER", "HEATING", "HEAVILY", "HEIGHTS", "HELPFUL", "HELPING", "HERSELF", "HEWLETT", "HIGHEST", "HIGHWAY", "HIMSELF", "HISTORY", "HITACHI", "HITTING", "HOBBIES", "HOLDERS", "HOLDING", "HOLIDAY", "HOLLAND", "HOPKINS", "HORIZON", "HORMONE", "HOSTELS", "HOSTING", "HOTMAIL", "HOTTEST", "HOUSING", "HOUSTON", "HOWEVER", "HUNDRED", "HUNGARY", "HUNTING", "HUSBAND", "HYGIENE", "HYUNDAI", "ICELAND", "IGNORED", "ILLEGAL", "ILLNESS", "IMAGINE", "IMAGING", "IMPACTS", "IMPLIED", "IMPLIES", "IMPORTS", "IMPOSED", "IMPROVE", "INCLUDE", "INDEXED", "INDEXES", "INDIANA", "INDIANS", "INDICES", "INDUCED", "INFANTS", "INITIAL", "INJURED", "INQUIRE", "INQUIRY", "INSECTS", "INSIDER", "INSIGHT", "INSTALL", "INSTANT", "INSTEAD", "INSULIN", "INSURED", "INTEGER", "INTENSE", "INTERIM", "INVALID", "INVITED", "INVOICE", "INVOLVE", "IRELAND", "ISLAMIC", "ISLANDS", "ISRAELI", "ITALIAN", "JACKETS", "JACKSON", "JAMAICA", "JANUARY", "JEFFREY", "JELSOFT", "JESSICA", "JEWELRY", "JOHNSON", "JOINING", "JOURNAL", "JOURNEY", "JUMPING", "JUSTICE", "JUSTIFY", "KARAOKE", "KATRINA", "KEEPING", "KENNEDY", "KENNETH", "KEYWORD", "KILLING", "KINGDOM", "KISSING", "KITCHEN", "KNIGHTS", "KNOWING", "LABELED", "LANDING", "LAPTOPS", "LARGELY", "LARGEST", "LASTING", "LATINAS", "LAUNDRY", "LAWSUIT", "LAWYERS", "LEADERS", "LEADING", "LEARNED", "LEASING", "LEATHER", "LEAVING", "LEBANON", "LECTURE", "LEGALLY", "LEGENDS", "LEISURE", "LENDERS", "LENDING", "LEONARD", "LESBIAN", "LESSONS", "LETTERS", "LETTING", "LEVITRA", "LEXMARK", "LIBERAL", "LIBERIA", "LIBERTY", "LIBRARY", "LICENCE", "LICENSE", "LICKING", "LIGHTER", "LIMITED", "LINCOLN", "LINDSAY", "LINKING", "LISTING", "LIVECAM", "LIVESEX", "LOADING", "LOCALLY", "LOCATED", "LOCATOR", "LOCKING", "LODGING", "LOGGING", "LOGICAL", "LONGEST", "LOOKING", "LOTTERY", "LUGGAGE", "MACHINE", "MADISON", "MADNESS", "MADONNA", "MAGICAL", "MAILING", "MAILMAN", "MANAGED", "MANAGER", "MANDATE", "MANUALS", "MAPPING", "MARILYN", "MARKERS", "MARKETS", "MARKING", "MARRIED", "MARTIAL", "MASSAGE", "MASSIVE", "MASTERS", "MATCHED", "MATCHES", "MATTERS", "MATTHEW", "MAXIMUM", "MEANING", "MEASURE", "MEDICAL", "MEDLINE", "MEETING", "MELISSA", "MEMBERS", "MEMPHIS", "MENTION", "MERCURY", "MESSAGE", "METHODS", "MEXICAN", "MICHAEL", "MIDWEST", "MILEAGE", "MILLION", "MINERAL", "MINIMAL", "MINIMUM", "MINOLTA", "MINUTES", "MIRACLE", "MIRRORS", "MISSILE", "MISSING", "MISSION", "MISTAKE", "MIXTURE", "MOBILES", "MODULAR", "MODULES", "MOLDOVA", "MOMENTS", "MONITOR", "MONSTER", "MONTANA", "MONTHLY", "MORNING", "MOROCCO", "MOTHERS", "MOUNTED", "MOZILLA", "MUSCLES", "MUSEUMS", "MUSICAL", "MUSLIMS", "MUSTANG", "MYANMAR", "MYSIMON", "MYSPACE", "MYSTERY", "NAMIBIA", "NATIONS", "NATURAL", "NAUGHTY", "NEAREST", "NEITHER", "NERVOUS", "NETWORK", "NEUTRAL", "NEWPORT", "NIAGARA", "NIGERIA", "NIPPLES", "NIRVANA", "NORFOLK", "NOTHING", "NOTICED", "NOTICES", "NOVELTY", "NOWHERE", "NUCLEAR", "NUMBERS", "NUMERIC", "NURSERY", "NURSING", "OAKLAND", "OBESITY", "OBJECTS", "OBSERVE", "OBVIOUS", "OCTOBER", "OFFENSE", "OFFERED", "OFFICER", "OFFICES", "OFFLINE", "OLYMPIC", "OLYMPUS", "ONGOING", "ONTARIO", "OPENING", "OPERATE", "OPINION", "OPPOSED", "OPTICAL", "OPTIMAL", "OPTIMUM", "OPTIONS", "ORDERED", "ORGANIC", "ORIGINS", "ORLANDO", "ORLEANS", "OUTCOME", "OUTDOOR", "OUTLETS", "OUTLINE", "OUTLOOK", "OUTPUTS", "OUTSIDE", "OVERALL", "PACIFIC", "PACKAGE", "PACKARD", "PACKETS", "PACKING", "PAINFUL", "PAINTED", "PANTIES", "PARENTS", "PARKING", "PARTIAL", "PARTIES", "PARTNER", "PASSAGE", "PASSING", "PASSION", "PASSIVE", "PATCHES", "PATENTS", "PATIENT", "PATRICK", "PATTERN", "PAYABLE", "PAYMENT", "PAYROLL", "PENALTY", "PENDANT", "PENDING", "PENGUIN", "PENSION", "PENTIUM", "PEOPLES", "PERCENT", "PERFECT", "PERFORM", "PERFUME", "PERHAPS", "PERIODS", "PERMITS", "PERSIAN", "PERSONS", "PHANTOM", "PHILIPS", "PHOENIX", "PHRASES", "PHYSICS", "PICKING", "PICTURE", "PIONEER", "PIRATES", "PISSING", "PLACING", "PLANETS", "PLANNED", "PLANNER", "PLASTIC", "PLAYBOY", "PLAYERS", "PLAYING", "PLEASED", "PLUGINS", "POCKETS", "PODCAST", "POINTED", "POINTER", "POKEMON", "POLYMER", "PONTIAC", "POPULAR", "PORSCHE", "PORTION", "POSSESS", "POSTAGE", "POSTERS", "POSTING", "POTTERY", "POULTRY", "POVERTY", "POWERED", "PRAIRIE", "PRAYERS", "PRECISE", "PREDICT", "PREFERS", "PREMIER", "PREMIUM", "PREPAID", "PREPARE", "PRESENT", "PRESSED", "PRESTON", "PREVENT", "PREVIEW", "PRICING", "PRIMARY", "PRINTED", "PRINTER", "PRIVACY", "PRIVATE", "PROBLEM", "PROCEED", "PROCESS", "PRODUCE", "PRODUCT", "PROFILE", "PROFITS", "PROGRAM", "PROJECT", "PROMISE", "PROMOTE", "PROPHET", "PROPOSE", "PROTECT", "PROTEIN", "PROTEST", "PROUDLY", "PROVIDE", "PUBLISH", "PULLING", "PURPOSE", "PURSUIT", "PUSHING", "PUTTING", "PUZZLES", "QUALIFY", "QUALITY", "QUANTUM", "QUARTER", "QUERIES", "QUICKLY", "QUIZZES", "RADICAL", "RAILWAY", "RAINBOW", "RAISING", "RALEIGH", "RANGERS", "RANGING", "RANKING", "RAPIDLY", "RATINGS", "RAYMOND", "REACHED", "REACHES", "READERS", "READILY", "READING", "REALITY", "REALIZE", "REALTOR", "REASONS", "REBATES", "REBECCA", "REBOUND", "RECEIPT", "RECEIVE", "RECIPES", "RECORDS", "RECOVER", "REDHEAD", "REDUCED", "REDUCES", "REFINED", "REFLECT", "REFORMS", "REFRESH", "REFUSED", "REGARDS", "REGIONS", "REGULAR", "RELATED", "RELATES", "RELEASE", "RELYING", "REMAINS", "REMARKS", "REMOVAL", "REMOVED", "RENEWAL", "RENTALS", "REPAIRS", "REPLACE", "REPLICA", "REPLIED", "REPLIES", "REPORTS", "REPRINT", "REQUEST", "REQUIRE", "RESERVE", "RESOLVE", "RESORTS", "RESPECT", "RESPOND", "RESTORE", "RESULTS", "RESUMES", "RETIRED", "RETREAT", "RETURNS", "REUNION", "REUTERS", "REVEALS", "REVENGE", "REVENUE", "REVERSE", "REVIEWS", "REVISED", "REWARDS", "RICHARD", "ROBERTS", "ROLLING", "ROMANCE", "ROMANIA", "ROUGHLY", "ROUTERS", "ROUTINE", "ROUTING", "ROYALTY", "RUNNING", "RUNTIME", "RUSSELL", "RUSSIAN", "SAILING", "SAMPLES", "SAMSUNG", "SATISFY", "SAVINGS", "SCANNED", "SCANNER", "SCHEMES", "SCHOLAR", "SCHOOLS", "SCIENCE", "SCORING", "SCRATCH", "SCREENS", "SCRIPTS", "SEAFOOD", "SEASONS", "SEATING", "SEATTLE", "SECONDS", "SECRETS", "SECTION", "SECTORS", "SECURED", "SEEKERS", "SEEKING", "SEGMENT", "SELLERS", "SELLING", "SEMINAR", "SENATOR", "SENDING", "SENEGAL", "SENIORS", "SENSORS", "SERIOUS", "SERVERS", "SERVICE", "SERVING", "SESSION", "SETTING", "SETTLED", "SEVENTH", "SEVERAL", "SHADOWS", "SHAKIRA", "SHANNON", "SHARING", "SHELTER", "SHEMALE", "SHERIFF", "SHERMAN", "SHIPPED", "SHOPPER", "SHORTER", "SHORTLY", "SHOWERS", "SHOWING", "SHUTTLE", "SIEMENS", "SIGNALS", "SIGNING", "SILENCE", "SILICON", "SIMILAR", "SIMPSON", "SINGING", "SINGLES", "SISTERS", "SITEMAP", "SITTING", "SKATING", "SKILLED", "SMALLER", "SMILIES", "SMOKING", "SOCIETY", "SOLARIS", "SOLDIER", "SOLOMON", "SOLVING", "SOMALIA", "SOMEHOW", "SOMEONE", "SOONEST", "SOURCES", "SPANISH", "SPATIAL", "SPEAKER", "SPECIAL", "SPECIES", "SPECIFY", "SPENCER", "SPIRITS", "SPONSOR", "SPRINGS", "SPYWARE", "STADIUM", "STANLEY", "STARTED", "STARTER", "STARTUP", "STATING", "STATION", "STATUTE", "STAYING", "STEPHEN", "STEVENS", "STEWART", "STICKER", "STOMACH", "STOPPED", "STORAGE", "STORIES", "STRANGE", "STREAMS", "STREETS", "STRETCH", "STRIKES", "STRINGS", "STRIPES", "STUDENT", "STUDIED", "STUDIES", "STUDIOS", "STUFFED", "STYLISH", "SUBJECT", "SUBLIME", "SUCCEED", "SUCCESS", "SUCKING", "SUGGEST", "SUICIDE", "SUMMARY", "SUNRISE", "SUPPORT", "SUPPOSE", "SUPREME", "SURFACE", "SURFING", "SURGEON", "SURGERY", "SURNAME", "SURPLUS", "SURVEYS", "SURVIVE", "SUSPECT", "SWEDISH", "SYMBOLS", "SYSTEMS", "TABLETS", "TACTICS", "TALKING", "TARGETS", "TEACHER", "TEACHES", "TEENAGE", "TELECOM", "TELLING", "TENSION", "TERRACE", "TERRAIN", "TESTING", "TEXTILE", "TEXTURE", "THEATER", "THEATRE", "THEOREM", "THERAPY", "THEREBY", "THEREOF", "THERMAL", "THOMSON", "THOUGHT", "THREADS", "THREATS", "THROUGH", "THUNDER", "TICKETS", "TIFFANY", "TIMOTHY", "TOBACCO", "TODDLER", "TONIGHT", "TOOLBAR", "TOOLBOX", "TOOLKIT", "TOPLESS", "TORONTO", "TORTURE", "TOSHIBA", "TOTALLY", "TOUCHED", "TOURING", "TOURISM", "TOURIST", "TOWARDS", "TRACKED", "TRACKER", "TRACTOR", "TRADING", "TRAFFIC", "TRAGEDY", "TRAILER", "TRAINED", "TRAINER", "TRANSIT", "TRAVELS", "TREATED", "TRIBUNE", "TRIBUTE", "TRIGGER", "TRINITY", "TRIUMPH", "TROUBLE", "TRUSTED", "TRUSTEE", "TSUNAMI", "TUESDAY", "TUITION", "TUNISIA", "TURKISH", "TURNING", "TWISTED", "TYPICAL", "UKRAINE", "UNIFIED", "UNIFORM", "UNKNOWN", "UNUSUAL", "UPDATED", "UPDATES", "UPGRADE", "UPSKIRT", "URUGUAY", "USUALLY", "UTILITY", "UTILIZE", "VACCINE", "VAMPIRE", "VANILLA", "VARIETY", "VARIOUS", "VARYING", "VATICAN", "VEHICLE", "VENDORS", "VENTURE", "VERIZON", "VERMONT", "VERSION", "VESSELS", "VETERAN", "VICTIMS", "VICTORY", "VIETNAM", "VIEWERS", "VIEWING", "VILLAGE", "VINCENT", "VINTAGE", "VIOLENT", "VIRTUAL", "VIRUSES", "VISIBLE", "VISITED", "VISITOR", "VITAMIN", "VOLTAGE", "VOLUMES", "WAITING", "WALKING", "WALLACE", "WANTING", "WARMING", "WARNING", "WARRANT", "WARRIOR", "WASHING", "WATCHED", "WATCHES", "WEAPONS", "WEARING", "WEATHER", "WEBCAMS", "WEBCAST", "WEBLOGS", "WEBPAGE", "WEBSITE", "WEBSTER", "WEDDING", "WEEKEND", "WEIGHTS", "WELCOME", "WELDING", "WELFARE", "WESTERN", "WHEREAS", "WHETHER", "WICHITA", "WILLIAM", "WILLING", "WINDOWS", "WINDSOR", "WINNERS", "WINNING", "WINSTON", "WISHING", "WITHOUT", "WITNESS", "WORKERS", "WORKING", "WORKOUT", "WORRIED", "WORSHIP", "WRAPPED", "WRITERS", "WRITING", "WRITTEN", "WYOMING", "YOUNGER", "ZEALAND"]

For 10 characters, you'd be able to detect:

["ABORIGINAL", "ABSOLUTELY", "ABSORPTION", "ACCEPTABLE", "ACCEPTANCE", "ACCESSIBLE", "ACCOMPLISH", "ACCORDANCE", "ACCOUNTING", "ACCREDITED", "ACCURATELY", "ACDBENTITY", "ACTIVATION", "ACTIVITIES", "ADAPTATION", "ADDITIONAL", "ADDRESSING", "ADJUSTABLE", "ADJUSTMENT", "ADMISSIONS", "ADOLESCENT", "ADVANTAGES", "ADVENTURES", "ADVERTISER", "AFFILIATED", "AFFILIATES", "AFFORDABLE", "AFTERWARDS", "AGGRESSIVE", "AGREEMENTS", "ALEXANDRIA", "ALGORITHMS", "ALLOCATION", "AMBASSADOR", "AMENDMENTS", "ANALYTICAL", "ANNOTATION", "ANTARCTICA", "ANTIBODIES", "APARTMENTS", "APPARENTLY", "APPEARANCE", "APPLIANCES", "APPLICABLE", "APPLICANTS", "APPRECIATE", "APPROACHES", "ARCHITECTS", "ARTIFICIAL", "ASSESSMENT", "ASSIGNMENT", "ASSISTANCE", "ASSOCIATED", "ASSOCIATES", "ASSUMPTION", "ATMOSPHERE", "ATTACHMENT", "ATTEMPTING", "ATTENDANCE", "ATTRACTION", "ATTRACTIVE", "ATTRIBUTES", "AUSTRALIAN", "AUTHORIZED", "AUTOMATION", "AUTOMOBILE", "AUTOMOTIVE", "AZERBAIJAN", "BACKGROUND", "BANGLADESH", "BANKRUPTCY", "BASKETBALL", "BEASTALITY", "BEHAVIORAL", "BENEFICIAL", "BESTIALITY", "BIOLOGICAL", "BIRMINGHAM", "BLACKBERRY", "BOUNDARIES", "BRITANNICA", "BURLINGTON", "BUSINESSES", "CALCULATED", "CALCULATOR", "CALIFORNIA", "CAMCORDERS", "CANDIDATES", "CAPABILITY", "CARTRIDGES", "CATEGORIES", "CHALLENGED", "CHALLENGES", "CHANCELLOR", "CHARACTERS", "CHARITABLE", "CHARLESTON", "CHRISTIANS", "CHRONICLES", "CIGARETTES", "CINCINNATI", "CITYSEARCH", "CLASSIFIED", "COLLEAGUES", "COLLECTING", "COLLECTION", "COLLECTIVE", "COLLECTORS", "COLUMNISTS", "COMMENTARY", "COMMERCIAL", "COMMISSION", "COMMITMENT", "COMMITTEES", "COMPARABLE", "COMPARISON", "COMPATIBLE", "COMPLAINTS", "COMPLEMENT", "COMPLETELY", "COMPLETING", "COMPLETION", "COMPLEXITY", "COMPLIANCE", "COMPONENTS", "COMPRESSED", "COMPROMISE", "CONCEPTUAL", "CONCERNING", "CONCLUSION", "CONDITIONS", "CONDUCTING", "CONFERENCE", "CONFIDENCE", "CONFIGURED", "CONNECTING", "CONNECTION", "CONNECTORS", "CONSIDERED", "CONSISTENT", "CONSISTING", "CONSORTIUM", "CONSPIRACY", "CONSTANTLY", "CONSTITUTE", "CONSTRAINT", "CONSULTANT", "CONSULTING", "CONTACTING", "CONTAINERS", "CONTAINING", "CONTINUING", "CONTINUITY", "CONTINUOUS", "CONTRACTOR", "CONTRIBUTE", "CONTROLLED", "CONTROLLER", "CONVENIENT", "CONVENTION", "CONVERSION", "CONVICTION", "COORDINATE", "COPYRIGHTS", "CORRECTION", "CORRUPTION", "COUNSELING", "CREATIVITY", "CUMULATIVE", "CURRENCIES", "CURRICULUM", "CUSTOMIZED", "DECORATING", "DECORATIVE", "DEFINITELY", "DEFINITION", "DELEGATION", "DELIVERING", "DEMOCRATIC", "DEPARTMENT", "DEPENDENCE", "DEPLOYMENT", "DEPRESSION", "DESCENDING", "DESCRIBING", "DESIGNATED", "DETERMINED", "DETERMINES", "DEVELOPERS", "DEVELOPING", "DIAGNOSTIC", "DICTIONARY", "DIFFERENCE", "DIFFICULTY", "DIMENSIONS", "DIRECTIONS", "DISABILITY", "DISCIPLINE", "DISCLAIMER", "DISCLOSURE", "DISCOUNTED", "DISCOVERED", "DISCRETION", "DISCUSSING", "DISCUSSION", "DISPATCHED", "DISPLAYING", "DISTRIBUTE", "DOCUMENTED", "DOWNLOADED", "EARTHQUAKE", "ECOLOGICAL", "EDITORIALS", "EFFICIENCY", "ELECTRICAL", "ELECTRONIC", "ELEMENTARY", "EMPLOYMENT", "ENCOURAGED", "ENCOURAGES", "ENCRYPTION", "ENDANGERED", "ENGAGEMENT", "ENROLLMENT", "ENTERPRISE", "EQUIVALENT", "ESPECIALLY", "ESSENTIALS", "ESTIMATION", "EVALUATING", "EVALUATION", "EVENTUALLY", "EVERYTHING", "EVERYWHERE", "EXCELLENCE", "EXCEPTIONS", "EXCITEMENT", "EXECUTIVES", "EXHIBITION", "EXPERIENCE", "EXPERIMENT", "EXPIRATION", "EXPLAINING", "EXPLICITLY", "EXPRESSION", "EXTENSIONS", "EXTRACTION", "FACILITATE", "FACILITIES", "FAVOURITES", "FEDERATION", "FELLOWSHIP", "FORMATTING", "FORWARDING", "FOUNDATION", "FRAGRANCES", "FREQUENTLY", "FRIENDSHIP", "FUNCTIONAL", "GENERATING", "GENERATION", "GENERATORS", "GEOGRAPHIC", "GEOLOGICAL", "GIRLFRIEND", "GOVERNANCE", "GOVERNMENT", "GRADUATION", "GREENHOUSE", "GREENSBORO", "GUARANTEED", "GUARANTEES", "GUIDELINES", "HARASSMENT", "HEADPHONES", "HEALTHCARE", "HELICOPTER", "HIGHLIGHTS", "HISTORICAL", "HORIZONTAL", "HOUSEHOLDS", "HOUSEWARES", "HOUSEWIVES", "HUMANITIES", "HUNTINGTON", "HYPOTHESIS", "IDENTIFIED", "IDENTIFIER", "IDENTIFIES", "IMMIGRANTS", "IMMUNOLOGY", "IMPORTANCE", "IMPOSSIBLE", "IMPRESSION", "IMPRESSIVE", "INCENTIVES", "INCOMPLETE", "INCREASING", "INCREDIBLE", "INDICATING", "INDICATION", "INDICATORS", "INDIGENOUS", "INDIVIDUAL", "INDONESIAN", "INDUSTRIAL", "INDUSTRIES", "INFECTIONS", "INFECTIOUS", "INFLUENCED", "INFLUENCES", "INITIATIVE", "INNOVATION", "INNOVATIVE", "INSPECTION", "INSTALLING", "INSTITUTES", "INSTRUCTOR", "INSTRUMENT", "INSULATION", "INTEGRATED", "INTERESTED", "INTERFACES", "INTERNSHIP", "INTERSTATE", "INTERVIEWS", "INTRODUCED", "INTRODUCES", "INVESTMENT", "INVITATION", "IRRIGATION", "JAVASCRIPT", "JOURNALISM", "JOURNALIST", "KAZAKHSTAN", "KILOMETERS", "LABORATORY", "LANDSCAPES", "LAUDERDALE", "LEADERSHIP", "LEGITIMATE", "LIKELIHOOD", "LIMITATION", "LIMOUSINES", "LITERATURE", "LITIGATION", "LOUISVILLE", "LUXEMBOURG", "MACROMEDIA", "MADAGASCAR", "MAINSTREAM", "MAINTAINED", "MANAGEMENT", "MANCHESTER", "MASTERCARD", "MEANINGFUL", "MECHANICAL", "MECHANISMS", "MEDICATION", "MEDITATION", "MEMBERSHIP", "METABOLISM", "MICROPHONE", "MILFHUNTER", "MILLENNIUM", "MINISTRIES", "MITSUBISHI", "MODERATORS", "MONITORING", "MONTGOMERY", "MOTIVATION", "MOTORCYCLE", "MOZAMBIQUE", "MULTIMEDIA", "MYSTERIOUS", "NATIONALLY", "NATIONWIDE", "NAVIGATION", "NETWORKING", "NEWSLETTER", "NEWSPAPERS", "NOMINATION", "NOTTINGHAM", "OBITUARIES", "OBJECTIVES", "OBLIGATION", "OCCASIONAL", "OCCUPATION", "OCCURRENCE", "OFFICIALLY", "OPERATIONS", "OPPOSITION", "ORGANIZING", "ORIGINALLY", "PAPERBACKS", "PARAGRAPHS", "PARAMETERS", "PARLIAMENT", "PARTICULAR", "PASSENGERS", "PERCENTAGE", "PERCEPTION", "PERFORMING", "PERIPHERAL", "PERMISSION", "PERSISTENT", "PERSONALLY", "PETERSBURG", "PHARMACIES", "PHENOMENON", "PHILOSOPHY", "PHOTOGRAPH", "PHYSICALLY", "PHYSICIANS", "PHYSIOLOGY", "PITTSBURGH", "POLYPHONIC", "POPULARITY", "POPULATION", "PORTSMOUTH", "PORTUGUESE", "POSSESSION", "POSTPOSTED", "POWERPOINT", "PREDICTION", "PREFERENCE", "PRESCRIBED", "PRESENTING", "PREVENTING", "PREVENTION", "PREVIOUSLY", "PRINCIPLES", "PRIORITIES", "PRIVILEGES", "PROCEDURES", "PROCEEDING", "PROCESSING", "PROCESSORS", "PRODUCTION", "PRODUCTIVE", "PROFESSION", "PROGRAMMER", "PROGRAMMES", "PROHIBITED", "PROJECTION", "PROJECTORS", "PROMOTIONS", "PROPERTIES", "PROPORTION", "PROTECTING", "PROTECTION", "PROTECTIVE", "PROVIDENCE", "PROVINCIAL", "PROVISIONS", "PSYCHIATRY", "PSYCHOLOGY", "PUBLISHERS", "PUBLISHING", "PUNISHMENT", "PURCHASING", "QUALIFYING", "QUANTITIES", "QUEENSLAND", "QUOTATIONS", "REASONABLE", "REASONABLY", "RECIPIENTS", "RECOGNISED", "RECOGNIZED", "RECOMMENDS", "RECORDINGS", "RECREATION", "RECRUITING", "REDUCTIONS", "REFERENCED", "REFERENCES", "REFLECTION", "REGARDLESS", "REGISTERED", "REGRESSION", "REGULATION", "REGULATORY", "RELATIVELY", "RELAXATION", "RELOCATION", "REMARKABLE", "REMEMBERED", "REPOSITORY", "REPRESENTS", "REPRODUCED", "REPUBLICAN", "REPUTATION", "REQUESTING", "RESEARCHER", "RESISTANCE", "RESOLUTION", "RESPECTIVE", "RESPONDENT", "RESPONDING", "RESTAURANT", "RESTRICTED", "RETIREMENT", "REVELATION", "REVOLUTION", "RICHARDSON", "SACRAMENTO", "SCHEDULING", "SCIENTIFIC", "SCIENTISTS", "SCREENSHOT", "SECURITIES", "SELECTIONS", "SEPARATELY", "SEPARATION", "SETTLEMENT", "SIGNATURES", "SIMPLIFIED", "SIMULATION", "SITUATIONS", "SOUNDTRACK", "SPECIALIST", "STATEMENTS", "STATIONERY", "STATISTICS", "STRATEGIES", "STRENGTHEN", "STRUCTURAL", "STRUCTURED", "STRUCTURES", "SUBJECTIVE", "SUBMISSION", "SUBMITTING", "SUBSCRIBER", "SUBSECTION", "SUBSEQUENT", "SUBSIDIARY", "SUBSTANCES", "SUBSTITUTE", "SUCCESSFUL", "SUFFICIENT", "SUGGESTING", "SUGGESTION", "SUNGLASSES", "SUPERVISOR", "SUPPLEMENT", "SUPPORTERS", "SUPPORTING", "SURPRISING", "SURROUNDED", "SUSPENSION", "SYSTEMATIC", "TECHNICIAN", "TECHNIQUES", "TECHNOLOGY", "TELEVISION", "TERRORISTS", "THEMSELVES", "THEREAFTER", "THOROUGHLY", "THREATENED", "THROUGHOUT", "THUMBNAILS", "THUMBZILLA", "TOURNAMENT", "TRACKBACKS", "TRADEMARKS", "TRADITIONS", "TRANSCRIPT", "TRANSEXUAL", "TRANSITION", "TRANSLATED", "TRANSLATOR", "TRAVELLING", "TREATMENTS", "TREMENDOUS", "ULTIMATELY", "UNDERLYING", "UNDERSTAND", "UNDERSTOOD", "UNDERTAKEN", "UNEXPECTED", "UNIVERSITY", "UZBEKISTAN", "VALIDATION", "VARIATIONS", "VEGETABLES", "VEGETARIAN", "VEGETATION", "VETERINARY", "VIETNAMESE", "VIOLATIONS", "VISIBILITY", "VOCABULARY", "VOCATIONAL", "VOLKSWAGEN", "VOLLEYBALL", "VOLUNTEERS", "VULNERABLE", "WALLPAPERS", "WARRANTIES", "WASHINGTON", "WATERPROOF", "WEBMASTERS", "WELLINGTON", "WIDESCREEN", "WIDESPREAD", "WILDERNESS", "WITHDRAWAL", "YUGOSLAVIA"]

It works for other lengths too, but I thought I'd specifically mention the ones within the spec that it will indeed work for. For example 227 results in:

["ABS", "BAR", "BBS", "CAP", "CAR", "CAS", "CBS"]

If the winner of this challenge is being chosen by shortest code, I can make this 140 bytes shorter if needed.


PHP, 246 printable bytes, distance 0
while($c=ord(base64_decode("vGec7K9+WXdBDEebnIQr5GkrI7WlZyuifOpMuZFfBxTJC5vkFwIaWPywLG3gX3ZpBlpXA+vk4tjazJ2tVcfoGZwHvJNgWgqTmiglNNpeBAEgFOi+IfcHYTzUSDd5rITXKpBu2Ia7Xo8NF9Zo0DhxQejheDyWtDxI/aU/zkpik/Y")[$i++]))echo strtr(sprintf("%08b",$c),10,BA);

or
while($c=base64_decode("vGec7K9+WXdBDEebnIQr5GkrI7WlZyuifOpMuZFfBxTJC5vkFwIaWPywLG3gX3ZpBlpXA+vk4tjazJ2tVcfoGZwHvJNgWgqTmiglNNpeBAEgFOi+IfcHYTzUSDd5rITXKpBu2Ia7Xo8NF9Zo0DhxQejheDyWtDxI/aU/zkpik/Y")[$i++])echo strtr(sprintf("%08b",ord($c)),10,BA);

Remarkable: gnuzip fails on the binary string. gzcompress adds 11 bytes and gzdeflate adds 5.
The fact that no 0x00 byte is in there saves 2 bytes on the first version;
no 0x30 saves 2 bytes on the second one.


Python 2.7: 544 bytes -50% = 272 bytes**

import sys;o=''.join;r=range;a=sys.argv[1];a=o([(' ',x)[x in a[12]+a[19]+a[22]] for x in a]);v={a:''};w={' '*4+(a[12]*2+' '*4+a[19]*2)*2+a[22]*4:''}
m=lambda a,k:o([a[([0x55a5498531bb9ac58d10a98a4788e0,0xbdab49ca307b9ac2916a4a0e608c02,0xbd9109ca233beac5a92233a842b420][k]>>5*i)%32] for i in r(24)])
def z(d,h):
 t={}
 for s in d[0]:
  if s in d[1]:print d[h][s]+d[1-h][s];exit()
  n=[d[0][s],'']
  for k in r(3):
   for j in r(3):s=m(s,k);t[s]=n[h]+'RUF'[k]+" 2'"[(j,2-j)[h]]+n[1-h]
   s=m(s,k)
 d[0]=t;return d
while 1:v,w=z([v,w],0);w,v=z([w,v],1)

Stackexchange replaces tabs with multiple whitespaces. So technical this version has 549 bytes. Just replace the first two spaces in the lines 6-10 with a tabulator.

Idea behind my program:
My first idea was a breath first search. But this took too long. Around 2 minutes for a hard (11 move optimal) scramble.
So I decided to approach the problem from both sides. I use two sets. I generate    sequentially all states with distance 1,2,3,... to the scramble and save them in set1, and at the same time all states with distance 1,2,3,... to the solved state and save them in set2.
The first time a state is in both sets, we found the solution.

For this I need the colors of the solved cube, which are not known. The characters 13, 20 and 23 define the left, back and down color. But these 3 colors are sufficient to represent the cube. I simply replace the other 3 colors with whitespaces and I can represent my solved state as '____ll____bbll____dddd'.

Oh, and for shortening the permutations I used an idea from https://codegolf.stackexchange.com/a/34651/29577

Ungolfed version:

import sys

#define permutations for R,U,F
permutation = [[0,7,2,15,4,5,6,21,16,8,3,11,12,13,14,23,17,9,1,19,20,18,22,10],
            [2,0,3,1,6,7,8,9,10,11,4,5,12,13,14,15,16,17,18,19,20,21,22,23],
            [0,1,13,5,4,20,14,6,2,9,10,11,12,21,15,7,3,17,18,19,16,8,22,23]]

def applyMove(state, move):
    return ''.join([state[i] for i in permutation[move]])

scramble = sys.argv[1]
#remove up,front,rigth colors
scramble = ''.join([(' ', x)[x in scramble[12]+scramble[19]+scramble[22]] for x in scramble])
solved = ' '*4+scramble[12]*2+' '*4+scramble[19]*2+scramble[12]*2+' '*4+scramble[19]*2+scramble[22]*4

dict1 = {scramble: ''} #stores states with dist 0,1,2,... from the scramble
dict2 = {solved: ''} #stores states with dist 0,1,2,... from the solved state

moveName = 'RUF'
turnName = " 2'"

for i in range(6):
    tmp = {}
    for state in dict1:
        if state in dict2:
            #solution found
            print dict1[state] + dict2[state]
            exit()
        moveString = dict1[state]
        #do all 9 moves
        for move in range(3):
            for turn in range(3):
                state = applyMove(state, move)
                tmp[state] = moveString + moveName[move] + turnName[turn]
            state = applyMove(state, move)
    dict1 = tmp
    tmp = {}
    for state in dict2:
        if state in dict1:
            #solution found
            print dict1[state] + dict2[state]
            exit()
        moveString = dict2[state]
        #do all 9 moves
        for move in range(3):
            for turn in range(3):
                state = applyMove(state, move)
                tmp[state] = moveName[move] + turnName[2 - turn] + moveString
            state = applyMove(state, move)
    dict2 = tmp

I'm pretty happy with the result, because I'm quite new to Python. This is one of my first python programs.

edit: half a year later: 427 - 50% = 213.5

Got a little bit more experience in Python and in golfing. So I revised my original code and could save more than 100 character.

import sys;o=''.join;a=sys.argv[1];d=[{o((' ',x)[x in a[12]+a[19]+a[22]]for x in a):[]},{' '*4+(a[12]*2+' '*4+a[19]*2)*2+a[22]*4:[]}]
for h in[0,1]*6:
 for s,x in d[h].items():
  for y in range(12):
   d[h][s]=x+[y-[1,-1,1,3][h*y%4]];
   if s in d[1-h]:print o('RUF'[x/4]+" 2'"[x%4]for x in d[0][s]+d[1][s][::-1]);exit()
   s=o(s[ord(c)-97]for c in'acahabcdnpbfegefhugiovjgqkciljdeklflmmmnnvoopxphrqdjrrbsstttuuqsviwwwkxx'[y/4::3])

I basically use the exact same approach. The biggest change is, that I don't define a function anymore. Instead of

def z(d,h):
 for s in d[0]:
  if s in d[1]:...
while 1:v,w=z([v,w],0);w,v=z([w,v],1)

I can do

for h in[0,1]*6:
 for s in d[h]:
  if s in d[1-h]:...

Also I changed the move lamda a little bit. First shortend, and then integrated the code directly, since the function call only appears once.

I keep for each state a list of numbers between 0 and 11, to represent the moves, instead of a string containing the moves. The numbers are converted at the very end.

Also I combined the two for-loops 'for k in r(3):for j in r(3): into one for y in r(12). Therefore I also have to do the moves U4, R4, F4. Of course such a move doesn't appear in the shortest solution, so " 2'"[x%4] works. (If x % 4 == 3, there would be a index out of range exception)

It's also a little bit faster, since I look for the entry in the second set earlier. About 0.5 second for a 11 move solution.


Write a continuous quine (quine-variant)

QBasic (224 bytes incl. trailing CR+LF)

(Tested with QBasic/MS-DOS on a virtual machine as well as with FreeBASIC with "-lang qb" setting)

a$="a$=:l=l+1:if l>y then f=f+1:y=y*f+y+f:while x<=y:x=x+1:print mid$(a$,1,3)+chr$(34)+a$+chr$(34)+mid$(a$,4):wend":l=l+1:if l>y then f=f+1:y=y*f+y+f:while x<=y:x=x+1:print mid$(a$,1,3)+chr$(34)+a$+chr$(34)+mid$(a$,4):wend


Pyth, 18 bytes

CxR.:++~Zkz02_B_`T

Test suite

True is represented as 1, False as 0.

Ranges are represented inclusively.


Python, 40 38 bytes
-2 bytes thanks to @MitchSchwartz (ord(d)+ord(m))%8 -> ord(d)+ord(m)&7

lambda d,m:' NESSWNW'[ord(d)+ord(m)&7]

plain lookup of answer in a list (AKA string) indexed by the smallest mod of the sum of ordinals that works.
Test cases are on ideone


Fastest python implementation of multiplication table

About 352 times faster, according to the benchmark code

(on my machine)  Python 2.7

Exactly how much faster it is will vary widely between machines. I tested it on my web server also and there it was only 288 times as fast.

import itertools as i, operator as o

def multable(width, m={}):
   if not width in m.keys():
      m[width] = '\n'.join(['%4d'*width]*width)%tuple(i.starmap(o.mul,i.product(range(1,width+1),repeat=2)))
   return m[width]

The actual algorithm is only about 1.25 times as fast as the reference one, but if you have a function which is called often, caching the result saves a lot of time.


Jelly, 11 bytes
1ẇⱮ×R$SƊ=¥#

Try it online!
Takes \$n\$ then \$m\$ on the command line and outputs the first \$m\$ \$n\$-order self-replicating numbers
How it works
1ẇⱮ×R$SƊ=¥# - Main link. Takes n on the left
         ¥  - Group the previous 2 links into a dyad f(k, n):
       Ɗ    -   Group the previous 3 links into a monad on k:
     $      -     Group the previous 2 links into a monad on k:
    R       -       Yield the range [1, 2, ..., k]
   ×        -       Multiply each element by k
  Ɱ         -     For each element i in [k, 2k, ..., k²]:
 ẇ          -       Is k a substring of i?
      S     -     Sum; Count the 1s
        =   -   Does this equal n?
1         # - Count up k = 1, 2, 3, ... until m such k return true under f(k, n)


Fastest array-by-array nearest neighbour search

C++, .0007 seconds

Uses a simple grid to place all the points of B, then looks up the points of A starting at the grid point to which it maps.

#include <stdio.h>
#include <stdlib.h>
#include <thread>
#include <sys/time.h>

double mytime() {
  struct timeval tv;
  gettimeofday(&tv, NULL);
  return tv.tv_sec + tv.tv_usec * 1e-6;
}

typedef float vector[2];

#define T 4
// N must be a multiple of T
#define N 10000

// Width of grid.  Should be about sqrt(N)
#define W 100

vector a[N];
vector b[N];
int min[N];

float dist(vector x, vector y) {
    float a = x[0]-y[0];
    float b = x[1]-y[1];
    return a*a+b*b;
}

int mindist_test(vector x, vector *y, int n) {
    float best = dist(x, y[0]);
    int bestidx = 0;
    for(int i = 1; i < n; i++) {
        float d = dist(x, y[i]);
        if(best > d) {
            best = d;
            bestidx = i;
        }
    }
    return bestidx;
}

typedef struct cell cell;
struct cell {
    vector v;
    cell *next;
};

cell *grid[W][W];
cell cells[N];

float minx, miny, scalex, scaley, scale, scale2;

void build() {
    // Find bounds
    minx = b[0][0];
    miny = b[0][1];
    float maxx = b[0][0];
    float maxy = b[0][1];
    for(int i = 1; i < N; i++) {
        if(minx > b[i][0])
            minx = b[i][0];
        if(maxx < b[i][0])
            maxx = b[i][0];
        if(miny > b[i][1])
            miny = b[i][1];
        if(maxy < b[i][1])
            maxy = b[i][1];
    }
    scalex = (maxx - minx + .00001) / W;
    scaley = (maxy - miny + .00001) / W;
    scale = scalex < scaley ? scalex : scaley;
    scale2 = scale * scale;

    // Place B vectors in grid
    for(int i = 0; i < N; i++) {
        cells[i].v[0] = b[i][0];
        cells[i].v[1] = b[i][1];
        int x = int((b[i][0] - minx) / scalex);
        int y = int((b[i][1] - miny) / scaley);
        cells[i].next = grid[x][y];
        grid[x][y] = &cells[i];
    }
}

int find(vector v) {
    // Start checking at grid[x][y]
    int x = int((v[0] - minx) / scalex);
    int y = int((v[1] - miny) / scaley);

    float mindist = 1e30;
    cell *mincell;

    // Look in grid cells within radius r
    for(int r = 1; r < W; r++) {
        for(int i = x-r; i <= x+r; i++) {
            if(i < 0 || i >= W) continue;
            for(int j = y-r; j <= y+r; j++) {
                if(j < 0 || j >= W) continue;
                for(cell *c = grid[i][j]; c != NULL; c = c->next) {
                    float d = dist(v, c->v);
                    if(mindist > d) {
                        mindist = d;
                        mincell = c;
                    }
                }
            }
        }
        // If we've found a point close enough, stop.
        // The next iterations' points are guaranteed to be at least distance r*scale away.
        if(mindist < (r*r)*scale2)
            break;
    }
    return mincell - cells;
}

void thr(int t) {
    int base = N/T*t;
    for(int i = 0; i < N/T; i++) {
        min[base+i] = find(a[base+i]);
    }
}

int main(int argc, char *argv[]) {
    // Initialize
    for(int i = 0; i < N; i++) {
        a[i][0] = rand() / (RAND_MAX/1000000.);
        a[i][1] = rand() / (RAND_MAX/1000000.);
        b[i][0] = rand() / (RAND_MAX/1000000.);
        b[i][1] = rand() / (RAND_MAX/1000000.);
    }

    // Run & time
    double start = mytime();
    build();
    std::thread* threads[T];
    for(int t = 0; t < T; t++) {
        threads[t] = new std::thread(thr, t);
    }
    for(int t = 0; t < T; t++) {
        threads[t]->join();
    }
    double stop = mytime();
    printf("time: %f\n", stop - start);

    // Check results
    for(int i = 0; i < N; i++) {
        int j = min[i];
        int k = mindist_test(a[i], b, N);
        if(dist(a[i], b[j]) != dist(a[i], b[k])) {
            printf("BAD %d: %d %f %f\n", i, j, dist(a[i], b[j]), dist(a[i], b[k]));
        }
    }
}

Compile with

g++ -O3 -std=c++11 -stdlib=libc++ grid.cc -o grid


JavaScript by Christoph, 8/25
f=(y,x=0)=>y?f(y/2,x^y):x

(range 0-255)
Sadly, f=(y,x)=>y?f(y/2,x^y):x works for all values except 0.
Technical note
We use y/2 rather than y>>1 to save a byte. This is abusing the fact that any value of y will eventually be rounded to 0 because of arithmetic underflow.


Wolfram Language (Mathematica), 33 bytes
2#2&@@#~BoundingRegion~"MinBall"&

Try it online!
Nearly exactly the same as the Mathematica answer to the 2D version. Works for input points of any dimension.


JavaScript (Node.js), 123 bytes

l=>g=([p,q,...t],h='┌'.padEnd(l,'┬')+`┐
`)=>p?h+g(t,h.replace(/\S/g,c=>'╵│ '[c>'╴'||++i%p?2:i/p%q<1|0],i=-1)):h

Try it online!

Use this function as f(20)([5, 2]).

Thanks Arnauld, saves 4 bytes.


Converting rational numbers to an “alien” data format

Batch, 531 bytes

@echo off
set q=
set s=
set m=
if %1 lss 0 set m=-
set/ai=%m%%1,n=%2,d=%3,p=0
:i
set/ar=i%%47,i/=47
if %r% gtr 9 set r=[%r%]
set s=%s%%r%
if %i% gtr 0 goto i
:p
if %n%==0 goto n
set/ao=n,g=d%%47
if %g% gtr 0 goto g
set/ap+=1,d/=47,r=n/d,n%%=d
if %r% gtr 9 set r=[%r%]
set s=%r%%s%
goto p
:g
set/aq+=1,p+=1,r=n*47/d,n=n*47%%d
if %r% gtr 9 set r=[%r%]
set s=%r%%s%
if %n% neq %o% goto g
if %q% gtr 9 set q=[%q%]
set q=%q%:
:n
if %p% gtr 9 (set q=%q%-[%p%]:)else if %p% gtr 0 set q=%q%-%p%:
echo #%q%%m%%s%

Takes three parameters, whole number, numerator, denominator representing a mixed number in its lowest terms.


JavaScript (Node.js), \$N=10\$ in 4m02s1
1: on an Intel Code i7, 7th Gen
This only includes some trivial optimizations and is therefore quite inefficient. It does at least confirm the results listed in the challenge.
function build(n) {
  let layer = [],
      cube = new Set,
      count = 0,
      x, y;

  for(y = 0; y < n; y++) {
    for(layer[y] = [], x = 0; x < n; x++) {
      layer[y][x] = 0;
    }
  }

  function fill(k, alignTop) {
    let x, y;

    if(k == 0) {
      if(!cube.has(layer + '')) {
        let transf;

        count++;

        cube.add(layer + '');
        cube.add((transf = rotate(n, layer)) + '');
        cube.add((transf = rotate(n, transf)) + '');
        cube.add((transf = rotate(n, transf)) + '');

        cube.add((transf = mirror(layer)) + '');
        cube.add((transf = rotate(n, transf)) + '');
        cube.add((transf = rotate(n, transf)) + '');
        cube.add((transf = rotate(n, transf)) + '');
      }
      return;
    }

    let y0;

    for(y0 = 0; !layer[y0].some(v => v); y0++) {}

    for(y = Math.max(0, y0 - 1); y < n; y++) {
      for(x = 0; x < n; x++) {
        if(
          !layer[y][x] && (
            (y && layer[y - 1][x]) ||
            (y < n - 1 && layer[y + 1][x]) ||
            (x && layer[y][x - 1]) ||
            (x < n - 1 && layer[y][x + 1])
          )
        ) {
          for(let i = 1; i <= (alignTop ? k : k - y0 - 1); i++) {
            layer[y][x] = i;
            fill(k - i, alignTop || !y);
            layer[y][x] = 0;
          }
        }
      }
    }
  }

  for(y = 0; y < n; y++) {
    for(let i = 1; i <= n - y; i++) {
      layer[y][0] = i;
      fill(n - i, !y);
      layer[y][0] = 0;
    }
  }

  return count;
}

function rotate(n, layer) {
  let rot = [],
      x, y;

  for(y = 0; y < n; y++) {
    for(rot[y] = [], x = 0; x < n; x++) {
      rot[y][x] = layer[n - x - 1][y];
    }
  }
  return align(rot);
}

function mirror(layer) {
  return align([...layer].reverse());
}

function align(layer) {
  while(!layer[0].some(v => v)) {
    let s = layer.shift();
    layer = [...layer, s];
  }
  while(!layer[0].some((_, y) => layer[y][0])) {
    layer = layer.map(r => {
      return [...r.slice(1), 0];
    });
  }
  return layer;
}

Try it online! (up to \$N=8\$)
Output
N = 1 --> 1
time: 10.352ms
N = 2 --> 2
time: 0.935ms
N = 3 --> 4
time: 0.877ms
N = 4 --> 12
time: 2.530ms
N = 5 --> 35
time: 9.060ms
N = 6 --> 129
time: 33.333ms
N = 7 --> 495
time: 157.160ms
N = 8 --> 2101
time: 1559.707ms
N = 9 --> 9154
time: 18555.900ms
N = 10 --> 41356
time: 242855.989ms


C++ time: O(n^2), extra space: O(1)

It takes 0.2s to complete the 15K data on my machine.

To compile it, use:

g++ -std=c++11 -O3 code.cpp -o code

To run it, use:

./code < INPUT_FILE_THAT_CONTAINS_TWO_LINES_SPERATED_BY_A_LINE_BREAK

Explaination

The idea is simple, for string s1 and s2, we try to offset s2 by i:

s1: abcabcabc
s2: bcabcab

When offset is 3:

s1: abcabcabc
s2:    bcabcab

Then, for each offset i, we perform a dynamic programing scan on s1[i:] and s2. For each j, let f[j, 0] be the maximum length d such that s1[j - d:j] == s2[j - i - d: j - i]. Similarly, let f[j, 1] be the maximum length d such that strings s1[j - d:j] and s2[j - i - d:j - i] differ by at most 1 character.

So for s1[j] == s2[j - i], we have:

f[j, 0] = f[j - 1, 0] + 1  // concat solution in f[j - 1, 0] and s1[j]
f[j, 1] = f[j - 1, 1] + 1  // concat solution in f[j - 1, 1] and s1[j]

Otherwise:

f[j, 0] = 0  // the only choice is empty string
f[j, 1] = f[j - 1, 0] + 1  // concat solution in f[j - 1, 0] and s1[j] (or s2[j - i])

And:

f[-1, 0] = f[-1, 1] = 0

Since we only need f[j - 1, :] to calculate f[j, :], only O(1) extra space is used.

Finally, the max length will be:

max(f[j, 1] for all valid j and all i)

Code

#include <string>
#include <cassert>
#include <iostream>

using namespace std;

int main() {
    string s1, s2;
    getline(cin, s1);
    getline(cin, s2);
    int n1, n2;
    n1 = s1.size();
    n2 = s2.size();
    int max_len = 0;
    int max_end = -1;
    for(int i = 1 - n2; i < n1; i++) {
        int f0, f1;
        int max_len2 = 0;
        int max_end2 = -1;
        f0 = f1 = 0;
        for(int j = max(i, 0), j_end = min(n1, i + n2); j < j_end; j++) {
            if(s1[j] == s2[j - i]) {
                f0 += 1;
                f1 += 1;
            } else {
                f1 = f0 + 1;
                f0 = 0;
            }
            if(f1 > max_len2) {
                max_len2 = f1;
                max_end2 = j + 1;
            }
        }
        if(max_len2 > max_len) {
            max_len = max_len2;
            max_end = max_end2;
        }
    }
    assert(max_end != -1);
    // cout << max_len << endl;
    cout << max_end - max_len + 1 << " " << max_end << endl;
}


Tic-Tac-Toe and Chess, with fewest [distinct] characters

APL (Dyalog Unicode), 369 characters, score 28

{Q←(QQ←⍴⍵)[1]
R←∨/¨⍵=⊂'RBQK'
B←({⍵(⍵[↑(⍳Q),¨¨⊂1--Q-⍳Q])}↑(⍳Q)=⊂⍳Q),{⍵,{⍵[{⍵[(1--1)1]}¨⍳QQ]}¨⍵}(⊂QQ)⍴¨(⍳Q)=⊂⍳Q
K←(Q-1)={∨/1↑⍴{(,⍵)/,⍳⍴⍵}⍵}¨B×⊂R
1-∨/K:1-1
K←↑∨/K/B
BB←{(,⍵)/,⍳⍴⍵}K×1-R
R←↑∨/BB-B←{(,⍵)/,⍳⍴⍵}R×1-K
1-⍴B:⍵[BB]=1↑''
BB←(1-∨/¨'RBQK'=⊂⍵[(,K)/,⍳⍴K])/'RBQK'
'K'=BB:×/∨/¨(⍳1--1)=⊂R∨-R
1-∨/(1-(⍳1--1)='RB'⍳BB)×(=/,{∨/1-×⍵})R∨-R:1-1
×/(1↑'')=⍵[B--(×⊂R)×⍳-1-∨/R]}↑⍞⍞⍞⍞

Try it online!
Character statistics:
 -  1  B  )  (  ⍵  /  Q  ⍳  R  '  ∨  LF   K  ,  =  ←  }  { ⊂ × ¨ ⍴ ↑ ] [ ⍞ :
27 26 22 20 20 19 19 18 15 15 14 12  12  12 12 11 10 10 10 9 9 9 8 8 7 7 4 4
chars 28

Decisions made during optimizing the score:

Boolean guard : is needed for early returns from a dfn {}. Either LF (\n) or a statement separator character ⋄ cannot be removed as a side effect.
I didn't try to avoid four letters RBQK as avoiding it requires at least ⎕A and the code would get messy.
Removed composition ∘, reflex/flip ⍨, and self ⊢ in favor of dfns and explicitly writing down arguments with parentheses.
Removed ≢ (tally) in favor of ⍴ (shape/reshape), as tally = first element of shape, and reshape is unavoidable.
Removed ⍉ (transpose) and ⌽ (reverse/rotate) in favor of explicit indexing [] combined with index generator ⍳. Although there are one-char functions to do the indexing (⌷, ⊃), none is suitable for transpose operation.
Removed ⊃ (first/pick) in favor of ↑ (mix/take), as take is unavoidable and indexing+mix can simulate both uses of ⊃.
Removed ∧ (logical and) in favor of × (times), and | (abs/mod) by using the workaround x∨-x for |x (abs) and explicit membership ∊ (which was removed later) for x|y (mod). ⊤ was also removed that way.
Removed ∘.f in favor of f⊂ or f¨⊂. Similar trick was used to simulate ∊ (membership) and ~ (set minus): x∊y → ∨/¨x=⊂y, x~y → (1-∨/¨x=⊂y)/x
Removed ⍸ (extract indices of ones) with the workaround (,x)/,⍳⍴x.
Removed zero with 1-1, four by extracting from ⍴⍵, and + with --.
Removing blanks in plain code is easy, but this code has ' '. I avoided it with 1↑'', which "overtakes" length 1 from an empty string and gives a single blank. (It is a slightly different thing from the literal ' ', but they are compatible in most cases.)

Ungolfed with comments
{
  ⍝ 4×4 boolean matrix where 1 means a white piece
  whites←⍵∊'RBKQ'
  ⍝ one matrix per a winning position; roughly looks like
  ⍝ 1 0 0 0 ... 1 1 1 1 ... 1 0 0 0
  ⍝ 1 0 0 0     0 0 0 0     0 1 0 0
  ⍝ 1 0 0 0     0 0 0 0     0 0 1 0
  ⍝ 1 0 0 0     0 0 0 0     0 0 0 1
  masks←((⊂,⊂∘⌽)∘.=⍨⍳4),(⊢,⍉¨)(⍳4)⌽¨⊂4 4⍴4↑1
  ⍝ 1 if the white is about to win in that specific winning position
  filter←3=masks{≢⍸⍺∧⍵}¨⊂whites
  ⍝ No three-in-a-row: return false
  ~∨/filter:0

  ⍝ fetch the mask closest to white's winning
  mask←(⍸filter)⊃masks
  ⍝ coordinates of misplaced piece (from) and empty position (to)
  from←⍸whites>mask
  to←⍸whites<mask
  ⍝ No from: the remaining place must be empty
  ~≢from:' '=⍵[to]

  ⍝ get the type of the piece to move
  type←'RBKQ'~⍵[⍸mask]
  ⍝ Knight: true if 1×2 steps away, ignoring any obstacles
  'K'=type:∧/1 2∊|⊃from-to
  ⍝ two booleans indicating if it can move in diagonals (BQ) or
  ⍝ cardinal directions (RQ)
  diag cross←0 2⊤⊃'RB'⍳type
  ⍝ two booleans indicating if the direction to move is actually
  ⍝ diagonal or cardinal
  isdiag←=/|⊃from-to
  iscross←0∊|⊃from-to
  ⍝ Not aligned with the piece to move: return false
  diag cross⍱.∧isdiag iscross:0
  ⍝ If aligned, true if all cells between from and to are blanks
  ∧/' '=¯1↓⍵[from+(×v)×⍳⌈/⊃|v←to-from]
}↑{⍞}¨⍳4  ⍝ Take 4 lines of input, format as matrix and pass to function


Dyalog APL, 5 3 bytes

⍳⍴⍨

-2 bytes thanks to FrownyFrog

Try it online!

⍳ gives all the indices given the shape of an array. e.g. 2 3.
⍴ reshapes the right arg to be the size of the left arg. ⍨ makes both be the right arg.


What's the shortest contiguous subset of ASCII you need to output the rest?


Japt, 11 13 programs, length 61

\x:#).&~L // outputs 9  (41 & ~100)
~T+~Tf)p  // outputs 4  ((~0 + ~floor(0)) ** 2)
$~Q$ *\~Z // outputs 1  (~'"' * ~0)
I%A^O||@{=!(Hmy))  // outputs 4  (64 % 10 ^ {} || function(X,Y,Z) { return function() { return ((U = !(H.m("y")))) } })
`!        // outputs !
`!        // outputs !
`.        // outputs .
`@        // outputs @
`Q        // outputs Q
`e        // outputs e
`|        // outputs |
`~        // outputs ~
`~        // outputs ~

It's awfully hard to come up with an answer that isn't just a string literal and outputs something other than a number...

Output and programs combined:

 !!!!!#$$%&())))*+...1449:=@@@AHILOQQQTTZ\\^`````````eefmpxy{||||~~~~~~~~~

I think I got 'em all...

When stripped down to the bare minimum:

#)&~L
~T+~T)p
~Q*~Z
I%A
`!
`!
`.
`@
`Q
`e
`|
`~
`~

It leaves these chars for future programs/outputs:

 !$$()).:=@HO\\^fmxy{||

You can trade two of $, ), or | for two of any of the chars in the nine string literals; that is, two of any of !.@Qe|~.

Additionally, you can trade out the Q in the third program for H or O, and the Z for H, O, @, or {.


Multigraphs with a given degree sequence

Haskell, 57 bytes

f(h:t)=sum[f l|l<-mapM(\n->[0..n])t,sum t-sum l==h]
f _=1

Try it online!


Husk, 11 bytes

!üȯṗ→+fotpN

1-indexed.
Try it online!

Explanation

!üȯṗ→+fotpN  Implicit input, a number n.
          N  The list of positive integers [1,2,3,4,..
      f      Keep those
         p   whose list of prime factors
       ot    has a nonempty tail: [4,6,8,9,10,12,..
 ü           De-duplicate wrt this equality predicate:
     +       sum
    →        plus 1
  ȯṗ         is a prime number.
             Result is [4,9,10,15,16,..
!            Get n'th element.


Rock, Paper, Scissors, Lizard, Spock Tournament

JavaScript (ES6),  122 115  112 bytes
Takes input as an array of strings of digits, with:

\$0\$ = Scissors (S)
\$1\$ = Paper (P)
\$2\$ = Rock (R)
\$3\$ = Lizard (L)
\$4\$ = Spock (V)

Returns either a string in the same format or \$false\$ if there's no solution.
f=(a,m='',x=0,o,b=a.filter(a=>(y=a[m.length%a.length])-x?o|=y-x&1^x<y:1))=>b+b?x<4&&f(a,m,x+1)||!o&&f(b,m+x):m+x

Try it online!
How?
This is a breadth-first search: we first try all moves at a given step to see if we can win the game. If we can't win right now, we try to add another move to each non-losing move.
The move identifiers were chosen in such a way that a move \$A\$ wins against a move \$B\$ if and only if \$(B-A)\bmod 5\$ is odd.
With \$A\$ on the left and \$B\$ on the top:
$$
\begin{array}{cc|ccccc}
& & \text{(S)} & \text{(P)} & \text{(R)} & \text{(L)} & \text{(V)}\\
& & 0 & 1 & 2 & 3 & 4\\
\hline
\text{(S) }&0 & - & \color{green}1 & \color{red}2 & \color{green}3 & \color{red}4\\
\text{(P) }&1 & \color{red}4 & - & \color{green}1 & \color{red}2 & \color{green}3\\
\text{(R) }&2 & \color{green}3 & \color{red}4 & - & \color{green}1 & \color{red}2\\
\text{(L) }&3 & \color{red}2 & \color{green}3 & \color{red}4 & - & \color{green}1\\
\text{(V) }&4 & \color{green}1 & \color{red}2 & \color{green}3 & \color{red}4 & -
\end{array}
$$
From there, we can deduce another way of testing if \$A\$ wins against \$B\$ for \$A\neq B\$:
((A - B) and 1) xor (B < A)

where and and xor are bitwise operators.
Commented
f = (                        // f is a recursive function taking:
  a,                         //   a[] = input
  m = '',                    //   m   = string representing the list of moves
  x = 0,                     //   x   = next move to try (0 to 4)
  o,                         //   o   = flag set if we lose, initially undefined
  b =                        //   b[] = array of remaining opponents after the move x
    a.filter(s =>            //     for each entry s in a[]:
    ( y =                    //       define y as ...
      s[m.length % s.length] //         ... the next move of the current opponent
    ) - x                    //       subtract x from y
    ?                        //       if the difference is not equal to 0:
      o |=                   //         update o using the formula described above:
        y - x & 1 ^ x < y    //           set it to 1 if we lose; opponents are removed
                             //           while o = 0, and kept as soon as o = 1
    :                        //       else (this is a draw):
      1                      //         keep this opponent, but leave o unchanged
  )                          //     end of filter()
) =>                         //
  b + b ?                    // if b[] is not empty:
    x < 4 &&                 //   if x is less than 4:
      f(a, m, x + 1)         //     do a recursive call with x + 1 (going breadth-first)
    ||                       //   if this fails:
      !o &&                  //     if o is not set:
        f(b, m + x)          //       keep this move and do a recursive call with b[]
  :                          // else (success):
    m + x                    //   return m + x


Check if a string is the anagram of another

05AB1E, 8 bytes

lðδKJ€{Ë

Try it online!


Calculate a user's privileges on CodeGolf.SE


User Appreciation Challenge #1: Dennis ♦

Jelly, 11 bytes

ŒufØAe€ØCŒḂ

Try it online!

Alternate versions:

ŒlfØae€ØCŒḂ

ŒufØAe€ØcŒḂ

ŒlfØae€ØcŒḂ

Of course a challenge appreciating Dennis must have an answer in a language of his.


Octave, 106 bytes

This assumes the history never contains a zero.

@(h,r,s)(h=[1e3,h])(n=nnz(h))+((40-(20*(n>30)))-(10*((n>30)&(max(h)>2401))))*(s-(1/(1+10^((r-h(n))/400))))

This outputs (after some formatting):

Correct - Calculated
1038    - 1037.87
1705    - 1705.3
2497    - 2496.51

Try it online!

Note: According to the FIDE-scoring system: If you play 41 games against a player having a score of 5000 (more than 2000 points higher than the highest achieved score ever), you'll end up with a score of 2400. I believe that fewer scores than 30, and a maximum score higher than 2400 should be considered invalid input (but that's OP's decision).

Check it here


Haskell, 61 55 53 bytes

f x=[[p|p<-[0,product x`div`n..],p`mod`n==1]!!0|n<-x]

Defines a function f that takes input and gives output as a list of integers.

f x=[                                          |n<-x]  (1)
              product x                                (2)
                       `div`n                          (3)

First we loop over all integers in the input (1). Then we take the product of all of the integers (2) and divide by n to get just the product of the non-n integers, which is P (3).

           [0,               ..]                       (4)
     [p|p<-                     ,p`mod`n==1]           (5)
                                            !!0        (6)

Then we use the result (P) as the step value for a range starting at zero (4). We take the result, [0, P, 2P, 3P, ...], and filter it on values for which the result of a mod-n operation is one (5). Finally, we take the first element, which works thanks to lazy evaluation (6).

Thanks to @xnor for 2 bytes!


Jelly, 9 bytes

ÆEz0Ṣ€ZÆẸ

Try it online!

How it works

ÆEz0Ṣ€ZÆẸ  Main link. Argument: A (array)

ÆE         For each n in A, compute the exponents of n's prime factorization.
           E.g., 2000000 = 2⁷3⁰5⁶ gets mapped to [7, 0, 6].
  z0       Zip 0; append 0's to shorter exponent arrays to pad them to the same
           length, then read the resulting matrix by columns.
    Ṣ€     Sort the resulting arrays (exponents that correspond to the same prime).
      Z    Zip; read the resulting matrix by columns, re-grouping the exponents by
           the integers they represent.
       ÆẸ  Unexponents; map the exponent arrays back to integers.


Mathematica, 17 14 13 bytes

Thanks to Ian Miller for saving 3 bytes.

Thanks to LegionMammal978 for saving 1 byte.

#~NSum~{k,5}&

The input should be an actual expression containing k, e.g.:

#~NSum~{k,5}&[Sqrt[k]^3+4]


Ruby, 103 101 characters
m,b,*q=gets.scan(/[\d\.]+/).map{|t|t.to_f}
s=t=!0
q.each_slice(2){|x,y|x=x*m+b;s|=x<=y;t|=x>=y}
p s&t

Input is on STDIN in the form specified in the question while output goes to STDOUT.


Python 2.7.9 — 21 bottles

Assuming that ESultanik's speculation is right on what the input is when multiple prisoners die

r=raw_input;s=str;j=s.join;p=int(r());z=range;q=z(p);x=z(p+1)
print s(p+1)+"\n"+j("\n",(j(" ",(s(a) for a in x if a!=b)) for b in q))
v=r().split();d=[s(a) for a in q if s(a) not in v];d+=[p]if len(d)==1 else [];
print "\n"*p,;r();print j(" ",[s(a) for a in d])

Algorithm: every prisoner drinks from every bottle except their number (1st prisoner doesn't drink first bottle). If they don't die, their number bottle is poisoned. If only one prisoner survives, the extra bottle is poisoned.


Shortest way to strip the commas from column n given a .csv file/input

JavaScript (ES6), 95 93 90 bytes
Takes the content of the CSV file as its first parameter and the column index as its second parameter, with currying syntax.

let f =

s=>n=>s.split(/("[^"]*")/).map(c=>(c<' '?(k=0,c):k++-n*2?c:c.split`,`.join``),k=-1).join``

console.log(f(
`"apple","banana","apple,banana","orange"
"grape","orange","grape,orange","sprout"
`)(2));


05AB1E, 32 29 25 bytes
žDL.Xʒ•BÌË"•4в2ôsÇ87%èøOQ

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

žD                # Push builtin 4096 (the maximum Roman number is 3999)
  L               # Create a list in the range [1,4096]
   .X             # Convert each integer to a Roman number
     ʒ            # Filter this list by:
      •BÌË"•     "#  Push compressed integer 195646806
            4в    #  Convert it to base-4 as list: [2,3,2,2,2,1,1,1,1,1,1,1,1,2]
              2ô  #  Split it into parts of size 2:
                  #   [[2,3],[2,2],[2,1],[1,1],[1,1],[1,1],[1,2]]
      s           #  Swap to get the current Roman number we're filtering on
       Ç          #  Convert its characters to their unicode values
        87%       #  Take modulo-87 for each (I=73; V=86; X=1; L=76; C=67; D=68; M=77)
           è      #  Index those into the list of pairs (with automatic wrap-around)
            ø     #  Zip/transpose; so we have inner lists of top/bottom values
             O    #  Sum each inner list
              Q   #  And check if it's equal to the (implicit) input-pair
                  # (after the filter, the result is output implicitly)

See this 05AB1E tip of mine (sections How to compress large integers? and How to compress integer lists?) to understand why •BÌË"• is 195646806 and •BÌË"•4в is [2,3,2,2,2,1,1,1,1,1,1,1,1,2].


Maximum Hamming distance among a list of padded strings


Use DefXXX statements when declaring multiple variables

The statement
DefDbl A-D

Defines all variables that start with A through D as being of the type Double, which means this can shorten cases such as
Dim A As Double
Dim B As Double
Dim C As Double
Dim D As Double

Similar commands exist for the following types
DefBool     ''  Boolean
DefByte     ''  byte
DefCur      ''  Currency
DefDate     ''  Date
DefDbl      ''  Double
DefDec      ''  Decimal
DefInt      ''  Integer
DefLng      ''  Long
DefObj      ''  Object
DefSng      ''  Single
DefStr      ''  String
DefVar      ''  Variant


Charcoal, 4 bytes

Ｓ‖Ｏ^

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

Ｓ       Input the string and implicitly print it
 ‖      Reflect...
  Ｏ     ... overlapping the first and last character...
   ^    ... in the ↙↘ directions (^ is shorthand for ↙↘).


Shortest parser for a left-recursive grammar

Ruby, 51 bytes

f=->s{s.split(/(\+)(?=n$)/).map{|t|t['+n']?f[t]:t}}

This seems weirdly cumbersome. It can be called like f['n+n+n'].


Print the lyrics to "Twinkle Twinkle Little Star"

Python 3 - Partial solution (760 742 734 710 705 657 characters)
(Last edit; I promise)
This seems like a really, pretty, very hard problem (especially recognizing where the notes start or end). Automatic transcription of music seems like an open research topic (not that I know anything about it). So here's a partial solution that doesn't do any note segmentation (eg it prints "Twinkle" all at once when it hears the frequency) and probably only works for that specific ogg file:
A=-52
F=44100
C=4096
import pyaudio as P
import array
import scipy.signal as G
import numpy as N
import math
L=math.log
i=0
j=[9,2,0,2,4,5,7,9]
k=[2,4,5,7]
n=j+k+k+j
w="Twinkle, |twinkle, |little |star,\n|How I |wonder |what you |are.\n|Up a|bove the |world so |high,\n|Like a |diamond |in the |sky.\n".split('|')
w+=w[:8]
e=P.PyAudio().open(F,1,8,1,0,None,0,C)
while i<24:
 g=array.array('h',e.read(C));b=sum(map(abs,g))/C
 if b>0 and 20*L(b/32768,10)>A:
  f=G.fftconvolve(g,g[::-1])[C:];d=N.diff(f);s=0
  while d[s]<=0:s+=1
  x=N.argmax(f[s:])+s;u=f[x-1];v=f[x+1]
  if int(12*L(((u-v)/2/(u-2*f[x]+v)+x)*F/C/440,2))==n[i]+15:print(w[i],end='',flush=1);i+=1

This requires...

Python 3 (tested with 3.3 on Windows 64 bit... should work on Mac/Linux in theroy)
PyAudio (I used the windows binary package from here, since the windows binary packages from the PyAudio page didn't work)
SciPy and NumPy (I used scipy-stack from the same site)

Change the A=-52 (minimum amplitude) on the top line depending on your microphone, ammount of ambient sound, how loud the song is playing, etc. On my microphone, less than -57 seems to pick up a lot of extraneous noise and more than -49 requires you play it very loud.
This could be golfed a LOT more; I'm sure there are ways to save a bunch of characters on the words array in particular. This is my first non-trivial program in python, so I'm not very familiar with the language yet.
I stole the code for frequency detection via autocorrelation from https://gist.github.com/endolith/255291
Ungolfed:
import pyaudio
from array import array
import scipy.signal
import numpy
import math
import sys

MIN_AMPLITUDE = -52
FRAMERATE = 44100

def first(list):
    for i in range(len(list)):
        if(list[i] > 0):
            return i
    return 0

# Based on: https://en.wikipedia.org/wiki/Decibel#Acoustics
def getAmplitude(sig):
    total = 0;
    elems = float(len(sig))
    for x in sig:
        total += numpy.abs(x) / elems
    if(total == 0):
        return -99
    else:
        return 20 * math.log(total / 32768., 10)

# Based on: https://en.wikipedia.org/wiki/Piano_key_frequencies
def getNote(freq):
    return int(12 * math.log(freq / 440, 2) + 49)

# --------------------------------------------------------------------------
# This is stolen straight from here w/ very slight modifications: https://gist.github.com/endolith/255291
def parabolic(f, x):
    return 1/2. * (f[x-1] - f[x+1]) / (f[x-1] - 2 * f[x] + f[x+1]) + x

def getFrequency(sig):
    # Calculate autocorrelation (same thing as convolution, but with
    # one input reversed in time), and throw away the negative lags
    corr = scipy.signal.fftconvolve(sig, sig[::-1], mode='full')
    corr = corr[len(corr)/2:]

    # Find the first low point
    diffs = numpy.diff(corr)

    # Find the next peak after the low point (other than 0 lag). This bit is
    # not reliable for long signals, due to the desired peak occurring between
    # samples, and other peaks appearing higher.
    # Should use a weighting function to de-emphasize the peaks at longer lags.
    start = first(diffs)
    peak = numpy.argmax(corr[start:]) + start
    return parabolic(corr, peak) * (FRAMERATE / len(sig))
# --------------------------------------------------------------------------

# These are the wrong keys (ie it is detecting middle C as an A), but I'm far too lazy to figure out why.
# Anyway, these are what are detected from the Wikipedia .ogg file:
notes = [73,          66,           64,       66,         68,       69,        71,          73,       66,     68,          69,         71,         66,        68,         69,        71      ]
words = ["Twinkle, ", "twinkle, ", "little ", "star,\n",  "How I ", "wonder ", "what you ", "are.\n", "Up a", "bove the ", "world so ", "high,\n", "Like a ", "diamond ", "in the ", "sky.\n"]
notes += notes[:8]
words += words[:8]

pa = pyaudio.PyAudio()
stream = pa.open(format=pyaudio.paInt16, channels = 1, rate = FRAMERATE, input = True, frames_per_buffer = 4096)
idx = 0
while(idx < len(notes)):
    # Read signal
    sig = array('h', stream.read(4096))
    if(getAmplitude(sig) > MIN_AMPLITUDE):
        note = getNote(getFrequency(sig))
        if(note == notes[idx]):
            sys.stdout.write(words[idx])
            sys.stdout.flush()
            idx += 1


JavaScript (ES6), 26 24 23 22 21 bytes

Saved 3 bytes thanks to Shaggy and 1 byte thanks to Luke.

_=>new Date/12e5%72<1

Checks if time passed in current day is less than 1200000ms (1200s or 20min). Assumes downtime to be 20 minutes not 21, which appears to be the case in the linked post. 00:20UTC is the exclusive upper bound.