Rust, \$A(1), \dotsc, A(1375)\$ in 10 minutes

Unofficial score on Ryzen 7 1800X (8 cores/16 threads).  Build with cargo build --release and run with time target/release/tetrahedron n to compute \$A(1), \dotsc, A(n)\$.

This runs in \$O(n^4)\$ time.  (So to estimate a good value of \$n\$ for your CPU, first time it for some smaller \$n\$, then multiply that \$n\$ by a factor of \$\left(\frac{600\,\mathrm{s}}{t}\right)^{1/4}\$.)

How it works

Any triangle that fits inside a tetrahedron of minimal side \$k \le n\$ may be translated inside a tetrahedron of side \$n\$ in exactly \$\binom{n - k + 3}{3}\$ ways.  This means we only need to find it in one position, leaving six free parameters.  Two of these parameters may be computed from the other four (up to a sign choice) if the triangle is to be equilateral, so we only need to loop over an \$O(n^4)\$ space.

src/main.rs

use rayon::prelude::*;

fn get_counts(n: i64, a0: i64) -> Vec<i64> {
    let mut c = vec![0; n as usize];
    let a0a0 = a0 * a0;
    for a1 in if a0 == 0 { 1 } else { -n + 1 }..n {
        let d = a0a0 + a1 * a1;
        let m = n - a0.abs() - a1.abs();
        for a2 in if m > 0 {
            -n + 2 - (m & 1)..n
        } else {
            -n - m + 2..n + m
        }
        .step_by(2)
        {
            let d = d + a2 * a2;
            let r = 2 * (a0a0 - d);
            if r == 0 {
                continue;
            }
            for b0 in a0..n {
                let pp = d * (3 * d - 4 * (a0a0 + b0 * (b0 - a0)));
                if pp < 0 {
                    break;
                }
                let p = (pp as f64).sqrt() as i64;
                if p * p != pp {
                    continue;
                }
                let q = 2 * a0 * b0 - d;
                let mut check = |p: i64| {
                    let b1r = p * a2 + q * a1;
                    if b1r % r != 0 {
                        return;
                    }
                    let b1 = b1r / r;
                    let b2r = -p * a1 + q * a2;
                    if b2r % r != 0 {
                        return;
                    }
                    let b2 = b2r / r;
                    if (b0, b1, b2) <= (a0, a1, a2) || b0 + b1 + b2 & 1 != 0 {
                        return;
                    }
                    let t = 0.max(a0 + a1 + a2).max(b0 + b1 + b2)
                        + 0.max(-a0 - a1 + a2).max(-b0 - b1 + b2)
                        + 0.max(-a0 + a1 - a2).max(-b0 + b1 - b2)
                        + 0.max(a0 - a1 - a2).max(b0 - b1 - b2);
                    if t >= 2 * n {
                        return;
                    }
                    c[t as usize / 2] += 1;
                };
                check(p);
                if p != 0 {
                    check(-p);
                }
            }
        }
    }
    c
}

fn add_vec(c0: Vec<i64>, c1: Vec<i64>) -> Vec<i64> {
    c0.into_iter().zip(c1).map(|(x0, x1)| x0 + x1).collect()
}

fn main() {
    let n = std::env::args().skip(1).next().expect("missing argument");
    let n = n.parse().expect("not an integer");
    let counts = (0..n)
        .into_par_iter()
        .map(|a0| get_counts(n, a0))
        .reduce(|| vec![0; n as usize], add_vec);
    let (mut d0, mut d1, mut d2, mut d3) = (0, 0, 0, 0);
    for (i, x) in (1..).zip(counts) {
        d3 += x;
        d2 += d3;
        d1 += d2;
        d0 += d1;
        println!("{} {}", i, d0);
    }
}

Cargo.toml

[package]
name = "tetrahedron"
version = "0.1.0"
authors = ["Anders Kaseorg <andersk@mit.edu>"]
edition = "2018"

[dependencies]
rayon = "1.3.0"

Try it online!  (Parallelism removed for TIO.)


05AB1E, 3 bytes

!fg

This assumes that factorization built-ins are allowed. Try it online!

How it works

!    Compute the factorial of the input.
 f   Determine its unique prime factors.
  g  Get the length of the resulting list.


JavaScript (ES6), 65 bytes

n=>'101010.1010'.replace(i=/\d/g,x=>new Date(n).toJSON()[i=x-~i])

Try it online!

How?

We initialize the pointer \$i\$ to a non-numeric value (coerced to \$0\$) and then add alternately \$2\$ and \$1\$ to it to pick the relevant characters from the ISO-8601 conversion of the input timestamp.

yyyy-mm-ddThh:mm:ss.sssZ
  ^^ ^^ ^^ ^^ ^^

JavaScript (ES6), 66 bytes

n=>'235689.BCEF'.replace(/\w/g,x=>new Date(n).toJSON()[+`0x${x}`])

Try it online!

How?

Once the input timestamp is converted in ISO-8601 format, all required characters can be accessed with a single hexadecimal digit.

yyyy-mm-ddThh:mm:ss.sssZ
  ↓↓ ↓↓ ↓↓ ↓↓ ↓↓
0123456789ABCDEF


Find the minimum and maximum integers in an array, without using builtins

Jelly, 3 bytes

Ṣ.ị

Try it online!

Sort the array, and then takes the 0.5-th element.

Jelly uses 1-indexing, and floating points indexing means take its floor and its ceil.

So the 0.5-th element would give you the 0th element and the 1st element.

The 0th element is the last element.


C,262 260
Golfed code (debugging code and unnecessary whitespace removed. Changed from input via stdin to input via command line, and took advantage of the opportunity to declare variable i there. Latest edit: code moved into brackets of for loops to save two semicolons.)
t[420],j,l,x,y;f(p,d){int z,q,k;for(k=6;k--;t[q]&!t[p+z]?t[q]=0,f(q,d+1),t[q]=1:0)z="AST?-,"[k]-64,q=p+z*2;l=d>l?d:l;}main(int i,char**s){for(i=840;i--;x>3&y>5&x+y<23|x<13&y<15&x+y>13?i>420?t[i-420]=49-s[1][j++]:t[i]||f(i,0):0)x=i%20,y=i/20%21;printf("%d",l);}

Explanation
This relies on a 20x21 board which looks like this, initially filled with zeroes when the program starts (this ASCII art was generated by a modified version of the program, and as the i loop counts downwards, zero is in the bottom right corner):
....................
....................
...............#....
..............##....
.............###....
............####....
.......#############
.......############.
.......###########..
.......##########...
.......#########....
......##########....
.....###########....
....############....
...#############....
.......####.........
.......###..........
.......##...........
.......#............
....................
....................

Loop i runs through this board twice, using x and y to calculate whether a square actually belongs to the checkerboard or not (this requires 6 separate inequalities in x and y.)
If it does, the first time round it fills the squares, putting a 0 (falsy) for a 1 (occupied) and a 1 (truthy) for a 0 (unoccupied). This inversion is important, because all out-of-bounds squares already contain a 0, which means they resemble occupied squares and it is clear they can't be jumped into, without the need for a specific check.
The second time round, if the square is occupied (contains 0) it calls the function f that searches for the moves.
f searches recursively in the 6 possible directions encoded by +/-1 (horizontal), +/-20 (vertical) and +/-19 (diagonal) encoded in the expression "AST?-,"[k]-64. When it finds a hit, it sets that cell to a 0 (occupied) before calling itself recursively, then sets it back to 1 (empty) when the function is returned. The cell value must be changed before the recursive call to prevent hopping into that cell more than once.
Ungolfed code
char s[999];                           //input string.
t[420],i,j,l,x,y;                      //t=board. i=board counter, j=input counter. l=length of longest hop found so far.

f(p,d){                                //p=position, d= recursion depth.
  //printf("%d,%d ",p,d);              //debug code: uncomment to show the nodes visited.
  int k,z,q;                           //k=counter,z=displacement,q=destination
  for(k=6;k--;)                        //for each direction
    z="AST?-,"[k]-64,                  //z=direction
    q=p+z*2,                           //q=destination cell
    t[q]&!t[p+z]?                      //if destination cell is empty (and not out of bounds) and intervening cell is full
      t[q]=0,f(q,d+1),t[q]=1           //mark destination cell as full, recurse, then mark it as empty again.
      :0;
  l=d>l?d:l;                           //if d exceeds the max recorded recursion depth, update l
}

main(){
  gets(s);                             //get input
  for(i=840;i--;)                      //cycle twice through t
    x=i%20,                            //get x
    y=i/20%21,                         //and y coordinates
    x>3&y>5&x+y<23|x<13&y<15&x+y>13?   //if they are in the bounds of the board
      i>420?
        t[i-420]=49-s[j++]             //first time through the array put 0 for a 1 and a 1 for a 0 ('1'=ASCII49)
        :t[i]||f(i,0)                  //second time, if t[i]=0,call f().
       //,puts("")                     //puts() formats debug output to 1 line per in-bounds cell of the board
      :0;
  printf("%d",l);                      //print output
}


Python, 290

def g(o,u=1):
 s=['|']*o
 for i in range(o,n-1,2):v=r[i+1]in a[:a.index(r[i])]*u;s+=['|X'[v]];r[i:i+2]=r[i:i+2][::1-2*v]
 print'  '*(1-o)+'   '.join(s+['|']*(o^n%2))*u+'\n'*u+(' / \\'*n)[2*o:][:n*2]
a=map(int,raw_input().split())
n=len(a)
r=range(1,n+1)
o=1
g(1,0)
g(0)
while r!=a:g(o);o^=1

I went for a fairly basic approach, but it turned out a bit longer than I was hoping. It considers the list in pairs and decides whether or not to swap each pair. This is repeated for every intersecting row until the list matches the input.

Example:

$ python path.py
5 3 8 1 4 9 2 7 6
 \ / \ / \ / \ / \
  |   |   |   X   |
 / \ / \ / \ / \ /
|   X   X   X   X
 \ / \ / \ / \ / \
  X   X   X   X   |
 / \ / \ / \ / \ /
|   X   X   |   X
 \ / \ / \ / \ / \
  X   X   X   |   |
 / \ / \ / \ / \ /
|   |   |   X   |
 \ / \ / \ / \ / \


Husk, 20 bytes

ḟȯ⁰¦ṁ∫ṫ!¡Sof~Λ€∫×:¹g

Try it online!

Returns one solution, or an empty list if it doesn't exist.
The last test case (n=15) finishes in 3.8 seconds on TIO.

Explanation

The program has two parts.
In the first part (¡ and to the right of it), we construct an infinite list whose kth element is a list containing all length-k lists whose slice sums are in S.
We do this inductively, starting from the 1-element slices of S, and at each step prepending each element of S to each list, and keeping those whose prefix sums are in S.
In the second part (! and to the left of it), we take the nth element of the list, which contains length-n lists.
Of these, we select the first one whose slice sums actually contain every element of S.

In the code, let's first replace o and ȯ (which compose two and three functions into one) by parentheses for clarity.

¡S(f~Λ€∫)×:¹g  First part. Input is a list, say S=[1,2,3]
            g  Group equal adjacent elements: [[1],[2],[3]]
¡              Iterate function:
                Argument is a list of lists, say [[1,1],[1,2],[2,1]]
         ×      Mix (combine two lists in all possible ways)
          :     by prepending
           ¹    with the list S: [[1,1,1],[1,1,2],[2,1,1],[1,2,1],[2,1,2],[3,1,1],[2,2,1],[3,1,2],[3,2,1]]
   f            Filter by condition:
        ∫        Cumulative sums: [[1,2,3],[1,2,4],[2,3,4],[1,3,4],[2,3,5],[3,4,5],[2,4,5],[3,4,6],[3,5,6]]
     ~Λ          All of the numbers
 S     €         are elements of S: [[1,1,1]]
                 Only this list remains, since the other cumulative sums contain numbers not from S.
               Result of iteration: [[[1],[2],[3]],[[1,1],[1,2],[2,1]],[[1,1,1]],[],[],[]...

ḟ(⁰¦ṁ∫ṫ)!      Second part. Implicit input, say n=2.
        !      Take nth element of above list: [[1,1],[1,2],[2,1]]
ḟ              Find first element that satisfies this:
                Argument is a list, say [1,2]
      ṫ         Tails: [[1,2],[2]]
    ṁ           Map and concatenate
     ∫          cumulative sums: [1,3,2]
 ȯ ¦            Does it contain all elements of
  ⁰             S? Yes.
               Result is [1,2], print implicitly.

There are some parts that need more explanation.
In this program, the superscripts ⁰¹ both refer to the first argument S.
However, if α is a function, then α¹ means "apply α to S", while ⁰α means "plug S to the second argument of α".
The function ¦ checks whether its first argument contains all elements of the second (counting multiplicities), so S should be its second argument.

In the first part, the function that ¡ uses can be interpreted as S(f~Λ€∫)(×:)¹.
The combinator S behaves like Sαβγ -> (αγ)(βγ), which means that we can simplify it to (f~Λ€∫¹)(×:¹).
The second part, ×:¹, is "mix with S by prepending", and its result is passed to the first part.
The first part, f~Λ€∫¹, works like this.
The function f filters a list by a condition, which in this case is ~Λ€∫¹.
It receives a list of lists L, so we have ~Λ€∫¹L.
The combinator ~ behaves like ~αβγδε -> α(βδ)(γε): the first argument is passed to β, the second to γ, and the results are combined with α.
This means that we have Λ(€¹)(∫L).
The last part ∫L is just the cumulative sums of L, €¹ is a function that checks membership in S, and Λ takes a condition (here €¹) and a list (here ∫L), and checks that all elements satisfy it.
Put simply, we filter the results of the mixing by whether their cumulative sums are all in S.


Python 3.6, 137 129 bytes

from datetime import*
def f(k):g=[*map(int,k.split('-'))];n=g[2];return f"{date(*g):%-d{'tsnrhtdd'[n%5*(n^15>4>n%10)::4]} %B %Y}"

Try it online!


Gregorian to Noxu Time System Conversion

APL, 87

t[3]←(1+3⌷t←137 91 4 100⊤⍎2⍕⎕÷864)⌷'Looplab' 'Sevit' 'Hexteria' 'Sinpad'
'  '⎕R'-'⍕t

APL has an advantage in these time system conversion challenges due to the built-in encode function, at the cost of expensive string manipuation

Explanation
(using 1357510372 as example)

⎕÷864 takes user input from screen, divide by 864 (1571192.56018519)
⍎2⍕ and round to 2 dp.  (1571192.56)
137 91 4 100⊤ Then, converts to Noxu Time System (43 14 3 92.56)
t← and assign that to variable t.
1+3⌷ take the 3rd item from t, add 1 to account for 1-based indexing, (4)
(...)⌷'Looplab' 'Sevit' 'Hexteria' 'Sinpad' convert to Skizzle name, (Sinpad)
t[3]← and finally plug back into the 3rd item of t.

⍕t Convert t to a string representation, (43 14  Sinpad  92.56)
'  '⎕R'-' and replaces 2 spaces with a dash (43 14-Sinpad-92.56)


Implement functional programming paradigms

Haskell, many previous byte counts  127 * 0.9 = 114.3 bytes

f#(a:b)=f a:f#b;f#x=x
(f&x)0=x;(f&x)i=f$f&x$i-1
i=id
r x=i%(1,x)
(g?x)(a:b)=g(g?x$b)a;(g?x)y=x
f%(a,b)|a>b=[]|1<2=f a:f%(a+1,b)

No loops, just recursion.

# is map: (*2) # [1,2,3] -> [2,4,6]

& is nest: ((*2) & 3) 4 -> 48

i is apply: i (*2) 7 -> 14

r is range: r 4 -> [1,2,3,4]

? is fold: ((+) ? 0) [1,2,3,4] -> 10

% is table: (*2) % (2,4) -> [4,6,8]

As requested an ungolfed version with comments. Note, & and ? are ternary infix operators, which require additional parentheses when called or pattern matched.

f # (a:b) = f a : f#b        -- map on a list (a->head, b->tail) is f a in front of mapping f to b
f # x     = x                -- map on the empty list is the empty list
                             -- (non empty lists are caught in the line before)

(f & x) 0 = x                -- nesting zero times is x
(f & x) i = f $ f&x $ i-1    -- nesting i times is f (nesting one time less)

i=id                         -- apply in Haskell is just the identity function

r x = i % (1,x)              -- defined via the "table" of the identity function from 1 to x

(g ? x) (a:b) = g (g?x$b) a  -- folding g into a list (a->head, b->tail) is g applied to (folding g into b) and a
(g ? x) y     = x             -- folding the empty list is x
                             --  again, y must be the empty list, else it would have been handled by the previous line

f % (a,b)
  |a>b       = []                -- if iMin is greater than iMax, the table is empty
  |otherwise = f a : f%(a+1,b)   --  otherwise f a in front of the table with iMin increased by one

Thanks to @dfeuer and @Zgarb for some useful hints


Python 2, 123 121 119 111 109 108 bytes

Saved two bytes thanks to caird coinheringaahing; using the actual unprintable ASCII character instead of escaping it (\33)
Could (and did) save a byte by writing an entire program using input() instead of defining a function
Saved seven bytes thanks to ElPedro; using the fact that str(90+n) with 0<=n<=9 is "9%s"%n
Saved two three bytes by using string formatting rather than string concatenation

N=input()
for(n)in"2543":Z="_"*N;print"[9%sm /"%n+~-~-N*"-"+"\ \n/%s\\\n"%Z+~-N/2*("|%s|\n"%" "*N)+"|%s|"%Z

Try it online!

Uses ANSI escape codes for coloring the houses.


Generating PBM bitmap files from ASCII text

Perl, 164 bytes, no zlib/gzip compression

After sleeping on the problem, I managed to figure out a much shorter solution than my first one.  The trick is to take advantage of a minor loophole in the rules: the characters need to fit in 8 by 8 pixels each, but nothing says they have to fill all that space.  So I drew my own 4 by 5 pixel font, allowing me to pack two characters into 5 bytes.

The output looks like this:

 (scaled x 4)

     (original size)

Before giving the actual code with the embedded font data, let me show a de-golfed version:

y/A-Z!./\0-\033/ for @a = <> =~ /./g;
say "P4 " . 8*@a . " 8";
for $p (qw'PACKED FONT DATA') {
    print chr vec $p, ord, 4 for @a;
}

In the actual code, the PACKED FONT DATA is replaced by a binary string consisting of eight whitespace-delimited rows (four 14-byte rows and one 13-byte one, plus three single null bytes for the blank rows).  I deliberately designed my font so that the packed data contains no whitespace, single quotes or backslashes, so that it could be encoded in qw'...'.

Since the packed font string contains unprintable characters, I've provided the actual script as a hex dump.  Use xxd -r to turn it back into executable Perl code:

0000000: 792f 412d 5a21 2e2f 002d 1b2f 666f 7240  y/A-Z!./.-./for@
0000010: 613d 3c3e 3d7e 2f2e 2f67 3b73 6179 2250  a=<>=~/./g;say"P
0000020: 3420 222e 382a 4061 2e22 2038 223b 666f  4 ".8*@a." 8";fo
0000030: 7224 7028 7177 2700 20e6 e6ff 9612 8999  r$p(qw'. .......
0000040: e6e6 7759 99f5 0420 9999 8898 128a df99  ..wY... ........
0000050: 9928 5999 1504 20ef 98ee fb12 8cb9 e9e9  .(Y... .........
0000060: 2659 6965 0420 9999 8899 928a 9989 ab21  &Yie. .........!
0000070: 599f 8220 e9e6 8f96 62f9 9986 972e 2699  Y.. ....b.....&.
0000080: f284 2000 2000 2729 7b70 7269 6e74 2063  .. . .'){print c
0000090: 6872 2076 6563 2470 2c6f 7264 2c34 666f  hr vec$p,ord,4fo
00000a0: 7240 617d                                r@a}

Here's how it works:

The first line (in the de-golfed version) reads a single line of input, splits it into an array of characters (conveniently omitting any trailing newlines) and maps the letters A to Z and the characters ! and . to the character codes 0 to 28, which normally correspond to unprintable control characters in ASCII / Unicode.  (A minor side effect of this is that any tabs in the input get printed as Js.)  The space character is left unmapped, since the output loop turns any codes above 28 into blanks anyway.
The second line just prints the PBM header.  It uses the Perl 5.10 say feature, so you need to run this script with perl -M5.010 for it to work.
The output loop takes a whitespace-delimited list of packed image rows and assigns each of them into $p in turn.  (I designed the font so that the packed data wouldn't contain any whitespace or ' characters.)  It then loops over the input characters in @a, using Perl's vec command to extract the 4-bit nibble corresponding to the mapped character code from the image row, pads it to an 8-bit byte and prints it.

Old answer, 268 bytes:

This is a quick and dirty first attempt.  I stole PleaseStand's font and compressed it along with my source code.  Since the resulting script is mostly unprintable, here's a hexdump; use xxd -r to turn it into executable Perl code:

0000000: 7573 6520 436f 6d70 7265 7373 275a 6c69  use Compress'Zli
0000010: 623b 6576 616c 2075 6e63 6f6d 7072 6573  b;eval uncompres
0000020: 7320 2778 da85 d03d 4b03 4118 85d1 452c  s 'x...=K.A...E,
0000030: b69c 72cb 7519 4894 552c 2c02 3319 ee5c  ..r.u.H.U,,.3..\
0000040: d7b8 5a89 6093 4634 7e82 c490 6c91 8597  ..Z.`.F4~...l...
0000050: 80fe 7267 d660 23ae e52d 0e0f dcd6 f8c3  ..rg.`#..-......
0000060: e9d1 5e6e ccec a15c ddb5 c5d5 495e 94a3  ..^n...\....I^..
0000070: 83b7 c7f9 73f3 5216 f9a8 787a 5fea 666c  ....s.R...xz_.fl
0000080: 9dd1 b763 dd98 76f8 2df6 0799 5811 7144  ...c..v.-...X.qD
0000090: 4acc ee9d b8b0 c90f 7e4a 8264 6016 cbd7  J.......~J.d`...
00000a0: 79f3 1b91 047c 4055 409e 9e54 1dda ed41  y....|@U@..T...A
00000b0: 9a20 8080 6adc 5c47 8488 7495 f621 01d7  . ..j.\G..t..!..
00000c0: 6b6c 902e b6c8 2a6a 6643 f56f e99c 115d  kl....*jfC.o...]
00000d0: 5c7a f1b2 13d0 3453 790f da74 c813 751d  \z....4Sy..t..u.
00000e0: 11ce d821 ad90 247f 2292 5b54 c14f 3c4e  ...!..$.".[T.O<N
00000f0: 49c5 4c53 a1a7 c478 391c 714c f113 0747  I.LS...x9.qL...G
0000100: ab6c 4482 9fd2 177a 5677 6327            .lD....zVwc'

The decompressed Perl code consists of the following preamble:

y;A-Z.! ;;cd,say"P4 ",8*length," 8"for$t=<>

followed by eight repetitions of the following code:

;$_=$t;y(A-Z.! )'BITMAP DATA HERE';print

with BITMAP DATA HERE replaced with 29 bytes encoding one row of the font.


Get the date of the nth day of week in a given year and month

MediaWiki Template, 19 bytes

{{#time:r|{{{1}}}}}

This is a MediaWiki Template ParserFunctions port of this PHP answer

Note: #time use PHP strtotime internally.

Sample Input

  {{#time:r|second saturday of March 2019}}

Sample Output

  Sat, 09 Mar 2019 00:00:00 +0000


awk, 64 56 54 bytes
/^$/{i=0}/./{if(!i++)print"# This is not pythonic!"}1

Test:
echo '/^$/{i=0}/./{if(!i++)print"# This is not pythonic!"}1' > solution.awk
awk -f solution.awk < pyth.py
awk -f solution.awk < pyth.py

Explanation:
/^$/ - matches empty line,
/./ - matches non-empty line,
1 - matches each line. No body is equivalent to {print;} - each line of input is printed.


Find the Number With the Highest Sum of Neighbors

MATL, 20 15 13 12 bytes

t1Y6Z+tuX>=)

Saved 5 bytes thanks to Emigna, 2 thanks to Giuseppe, and another thanks to Luis Mendo.
Try it online!

Explanation

t1Y6Z+tuX>=)
t                  Duplicate the (implicit) input.
 1Y6               Push the array [0 1 0; 1 0 1; 0 1 0].
    Z+             Convolve with the input.
       uX>         Get the maximum unique element...
      t   =        ... and compare elementwise.
           )       Index into the input.


MATLAB, 163 159 146 78 bytes
function m=f(m,y,x);[~,i]=bwfill(m~=m(y,x),x,y,8);m=m*0;m(i)=1;m=bwfill(m,'h')

Thanks @rahnema1 for -66 bytes!!!
Now it does work on Try it online! BUT a few adjustments were needed, as MATLAB and Octave are not entirely compatible.
Explanation
First we make a binary image that just masks all the characters that are equal to the initial character. Then we determine the connected component the initial character is in.
% determine the connected component that is contains initial character

[~,i]=bwfill(m~=m(y,x),x,y,8);     % i contains the indices of the connected component
m=m*0;m(i)=1;                      % create an image of the connected component

After that we create an image of that connected component and apply fill all the "holes" in the image.
m=bwfill(m,'h')


Write a function that returns past tense of given verb

sed, 76 characters

Does a sed script count as a function for this problem?

s/\([^aeiou]\)y$/\1i/
s/\([^aeiou][aeiou]\)\([^aeiouy]\)$/\1\2\2/
s/e\?$/ed/


Write program in your favorite language in another language

C in C++
#include <stdio.h>

int main(int argc, char** argv)
{
        printf("Hello world!\n");
        return 0;
}


05AB1E, 16 15 bytes
þIáÇ32%«ODXgÖ*Ā

Input as a list of characters.
-1 byte implicitly thanks to @ovs.
Try it online or verify all test cases.
Explanation:

þ                # Only leave the digits of the (implicit) input-list
 Iá              # Push the input-list again, and only leave its letters
   Ç             # Convert each letter to its codepoint integer
    32%          # Take modulo-32 on each codepoint
       «         # Merge it to the list of digits
        O        # Sum this list
         D       # Duplicate this sum
          Ig     # Push the input-list again, and pop and push its length
            Ö    # Check if the sum is divisible by this length
             *   # Multiply it by the duplicated sum
              Ā  # And check that this is NOT 0
                 # (after which the result is output implicitly)

3 bytes (D*Ā) are used for edge-cases 0/00/000/etc.


Python 2, 53 40
lambda x,y,p,q:y-2<q>=abs(x-p)+q/7+y/8*5

The king has coordinates (x, y) and the pawn (p, q).
There are three significant cases:

The pawn is on rank 7 and the king on rank 8. To capture the pawn, the king must be on the same file or an adjacent one.
Result: q = 7  ⋀  y = 8  →  |x - p| ≤ 1

The pawn is on rank 7. To capture the pawn, the king must be within six files.
Result: q = 7  →  |x - p| ≤ 6

The pawn is on a lower rank. To capture the pawn, the king must be able to reach the promotion square at most one move after the pawn.
Result: q < 7  →  |x - p| ≤ q  ⋀  y - 1 ≤ q

My solution is just these conditions golfed down. Hopefully there aren't mistakes this time.


JavaScript (ES6), 94 bytes

f=x=>[...x].reduce((p,z)=>p+!!z.trim()+2*/[Bg08$%&]/.test(z)+/[ADOPQRabdeopq469@#]/.test(z),1)

Demo

As the code is in ES6, the demo only works in ES6-compatible browsers. At time of writing, this includes Firefox, Edge, and Chrome/Opera with experimental JavaScript features enabled.

f = x => [...x].reduce((p, z) => p + !!z.trim() + 2 * /[Bg08$%&]/.test(z) + /[ADOPQRabdeopq469@#]/.test(z), 1)

// Snippet stuff
var v = function() {document.getElementById('Z').textContent = f(this.value)};
document.getElementById('I').addEventListener('keyup', v, false);
document.getElementById('I').addEventListener('change', v, false);
textarea {width: 100%}

Input: <textarea id=I></textarea>

Output: <output id=Z>1</output>


Output a shuffled deck using random input


Jelly,  14 12 11  9 bytes

-2 bytes thanks to ETHproductions (use the minimum dyad, «)

I’«0Ṛ+\Ṛ+

A monadic link taking and returning lists of integers.

Try it online! or see the test suite.

I really don't think this is Lazy™ enough!

How?

I’«0Ṛ+\Ṛ+ - Link: list of integers, a              e.g. [ 8, 3, 3, 4, 6, 2]
I         - increments between consecutive items of a   [-5, 0, 1, 2,-4 ]
 ’        - decrement (vectorises)                      [-6,-1, 0, 1,-5 ]
   0      - literal 0
  «       - minimum of decremented increments and zero  [-6,-1, 0, 0,-5 ]
    Ṛ     - reverse                                     [-5, 0, 0,-1,-6 ]
      \   - cumulative reduce with:
     +    -   addition                                  [-5,-5,-5,-6,-12]
       Ṛ  - reverse                                     [-12,-6,-5,-5,-5]
        + - addition (with a)                           [-4,-3,-2,-1, 1, 2]


Build a typing speed test / measuring CPM

Bash - 217 212 199 196 chars

Not gonna win but it was fun

declare -A W
for w in `shuf -n10`;do C+=$w;echo -\> $w;W[$w]=OK;done
SECONDS=0
for((;${#W[*]};));do read r;echo ${W[$r]-WRONG};unset W[$r];done
echo --\> You have scored $((60*${#C}/SECONDS)) CPM!

Under 200 chars now!

Takes wordlist file as an argument
Now takes word list on standard input. Paste it in the terminal and press ^D

Implemented suggestion from manatwork


Wolfram Language (Mathematica), 76 71 bytes

If[#<2,1,Min[#+Reverse@#&/@{#0/@Range[#-1],#0/@Most@Rest@Divisors@#}]]&

Try it online!

The recursive approach: define f[n] to be the minimum of f[k]+f[n-k]over all k less than n, and f[d] + f[n/d]over all divisors of n (other than 1 and n itself).


Perl, 212 191 181 168 bytes

$_=<>;/^(((.*?)(.*?))\2+)\3$/;$x=$1x4;while(<>){chop;$x=~/\Q$_\E/&&next;for$i(0..y///c-1){for$r(split//,$x){$b=$_;$b=~s/(.{$i})./$1$r/;$x=~/\Q$b\E/&&die$i,$",$.-1,$/}}}

This version uses an optimized trick for catching the reply unit, learned in Dennis' answer.
Optimization by using the property that all lines have equal lengths.
Line end is also needed for the last line, otherwise chomp instead of chop should be used.
Optimizations of ardnew's comment added.

Old version, 212 bytes:

$_=<>;chop;/^(.+?)\1+(??{".{0,".(-1+length$1).'}'})$/;$;=$1;while(<>){$x=$;x length;chop;$x=~/\Q$_\E/&&next;for$i(0..-1+length$_){for$r(split//,$;){$b=$_;$b=~s/(.{$i})./$1$r/;$x=~/\Q$b\E/&&exit print$i,$",$.-1}}}

Ungolfed version:

$_ = <>;  # read first line
/^(((.*?)(.*?))\2+)\3$/;
# The repeat unit \2 consists of \3 and \4,
# and the start part \2 can be added at the end (as partial or even full unit).
$x = $1 x 4; # $x is long enough to cover each following line

# Old version:
# /^(.+?)\1+(??{ ".{0," . (-1 + length $1) . '}' })$/;
# $a = $1; # $a is the repeat unit.
# The unit is caught by a non-greedy pattern (.+?) that is
# repeated at least once: \1+
# The remaining characters must be less than the unit length.
# The unit length is known at run-time, therefore a "postponed"
# regular expression is used for the remainder.

# process the following lines until the error is found
while (<>) {
    # old version:
    # $x = $a x length;
    # $x contains the repeated string unit, by at least one unit longer
    # than the string in the current line
    chop; # remove line end of current line
    $x =~ /\Q$_\E/ && next;
          # go to next line, if current string is a substring of the repeated units;
          # \Q...\E prevents the interpretation of special characters
    # now each string position $x is checked, if it contains the wrong character:
    for $i (0 .. y///c - 1) {  # y///c yields the length of $_
        for $r (split //, $x) { #/ (old version uses $a)
            # replace the character at position $i with a
            # character from the repeat unit
            $b = $_;
            $b =~ s/(.{$i})./$1$r/;
            $x =~ /\Q$b\E/
               && die $i, $", $. - 1, $/;
               # $" sets a space and the newline is added by $/;
               # the newline prevents "die" from outputting line numbers
        }
    }
}


Count the number of vowels in each word of a string

C, 113 108 103 96 bytes

Thanks @andrea-biondo for a particularly nice 5 byte saving.

main(a,v,c)char**v;{do{for(a=0;c=*v[1]++%32;2016%(c+27)||a++);printf("%d ",a);}while(v[1][-1]);}

This still feels sort of bloated so hopefully I can get it down quite some bytes later tonight.

The interesting part is perhaps that

!(124701951%((c-65&31)+33))

will be 1 if c is an (upper or lower case) ASCII vowel, and 0 for other characters a-zA-Z. The subexpression c-65&31 maps 'a' and 'A' to 0, 'b' and 'B' to 2, etc. When we add 33 the vowels correspond to the numbers 33, 37, 41, 47, 53 respectively, all of which are (conveniently) prime. In our range only such numbers will divide 124701951 = 33*37*41*47*53, ie only for vowels will the remainder of 124701951%(...) be zero.

EDIT: In this way one can consider the expression !(n%((c-65&31)+s)) where (n,s) = (124701951, 33) as determining whether the character c is a vowel. In the comments @andrea-biondo pointed out that the pair (n,s) = (2016,28) can also be used in this expression to determine vowelhood. I'll leave the current explanation in terms of primes above, but the reason this shorter pairing works is again because in the range 28--53 the only numbers with prime factors entirely in the set of prime factors of 2016 are 28, 32, 36, 42, 48, which correspond precisely to the vowels.

EDIT2: Another 5 bytes saved since (c-65&31)+28 can be shortened to c%32+27.

EDIT3: Converted to a do-while loop to finally get it below 100 bytes.

Test cases:

$ ./vowelc "This is the first test case"
1 1 1 1 1 2
$ ./vowelc "one plus two equals three"
2 1 1 3 2
$ ./vowelc "aeiou AEIOU"
5 5
$ ./vowelc "psst"
0


Distribute a number into a list of values as equal as possible whose sum is equal to that number

Python 2, 48 43 bytes

Returns 0 on error.

lambda m,n:m/n and[m/n]*(n-m%n)+m%n*[m/n+1]

Try it online!

41 bytes (with @xnor's trick)

Throws NameError on error.

lambda m,n:[m/n or _]*(n-m%n)+m%n*[m/n+1]

Try it online!


Maintain diagonal symmetry when placing N items on a square grid

Python 2, 116 113 112 101 bytes

lambda s,n:[[[n>i<s-(s+n&1),[i*~-i+2*j,j*~-j+2*i][i<j]<n-s][j!=i]for j in range(s)]for i in range(s)]

Try it online!
Input: 2 integers s and n
Output: A 2D list of True and False, representing x and . respectively.
Explanation
The strategy is to put as many xs on the diagonal as possible.

If \$s\$ and \$n\$ has the same parity, then we can fill \$min(s,n)\$ diagonal squares.
If \$s\$ and \$n\$ has different parity, then we can fill \$min(s-1,n)\$ diagonal squares.

The remaining xs can be split symmetrically between the 2 triangular half of the grid. For the bottom triangle, we fill from top to bottom, where each row is filled left to right. The upper triangle mirrors the bottom triangle (fill left to right, each column from top to bottom)
Thus, we can determine if a square is filled just based on its indices \$(i,j)\$:

If \$i=j\$ (the square is on the diagonal), then that square is filled if \$i<n\$ and \$i<s-t\$, where \$t\$ is 0 or 1 depending on whether \$s\$ and \$n\$ have the same or different parity.
The following snippet evaluates to True or False if the diagonal square should be filled or not.

[n>i<s-(s+n&1), ...case when square is not diagonal... ][j!=i]

If \$i>j\$ (the square is in lower triangle), then the number of squares in the lower triangle before this square (in fill order) is \$m = \frac{i(i-1)}{2} + j\$. Thus if this square is filled, then the number of squares filled before it is \$2m = i(i-1)+2j\$. We need to make sure that \$2m<n-s\$, otherwise the diagonal cannot be filled to the maximum.
Similarly, if \$i>j\$, then we fill if \$j(j-1)+2i<n-s\$.
The following snippet evaluates to True or False if the non-diagonal square is filled or not:

[i*~-i+2*j,j*~-j+2*i][i<j]<n-s

Combined together, this big expression evaluates to whether a square \$(i,j)\$ should be filled:
[n>i<s-(s+n&1),[i*~-i+2*j,j*~-j+2*i][i<j]<n-s][j!=i]

Thanks @ovs for saving 4 bytes in a previous solution!


Bash (100 89 chars)

for x in a-gq-tvwxz h-puy\'
do grep -iE ^[$x]*$ /usr/share/dict/words|tr '
' \
echo
done

Note that 21 chars go to the full path to the words file: if we're allowed to assume that pwd is /usr/share/dict then 16 of those can be saved.

Credit to chron for the shorter regexes.


Bash, 100%, 100 bytes

sed sX..s.2./s.XX|grep -Po '(?<=>)[^<]+?(?=(,(?! W)| [-&–5]| ?<| [0-79]\d| ?\((?!E|1\.)))'|head -1

Try it online on Ideone.

Verification

$ wget -q https://gist.githubusercontent.com/vihanb/1d99599b50c82d4a6d7f/raw/cd8225de96e9920db93613198b012749f9763e3c/testcases
$ grep -Po '(?<= - ).*' < testcases > input
$ grep -Po '^.*?(?= - )' < testcases > output
$ while read line; do bash headers.sh <<< "$line"; done < input | diff -s - output
Files - and output are identical


R, 16 bytes

T=a=1+!T;T=T-1;a

Try it online!
Works with \$n=1\$ and \$m=2\$.

Previous version:
R, 24 23 21 19 bytes
-4 bytes thanks to Dominic van Essen

T=a=1+0^T^2;T=T-1;a

Try it online!
Works with \$n=1\$ and \$m=2\$. This uses the fact that
\$0^k = \begin{cases} 1 & \text{ if } k=0\\0& \text { otherwise.}\end{cases}\$
Therefore, when the code is repeated \$k\$ times, we output \$1+0^{(2-k)^2}\$, which is worth \$2\$ when \$k=2\$, and \$1\$ otherwise.


Python 3, 78 77 75 70 68 62 bytes

f=lambda n,k=3,m=1,j=0:k<n and-m%k*j*2/k+f(n,k+2,m*k**4,m%k/k)

Thanks to @xnor for golfing off 2 4 bytes and paving the way for 4 more!

Try it online!

Background

Recall that Wilson's theorem states that for all integers k > 1,

where a ≡ b (mod d) means that a - b is evenly divisible by d, i.e., a and b have the same residue when divided by d.

In Wilson Theorems for Double-, Hyper-, Sub- and Super-factorials, the authors prove generalizations for double factorials, on which this answer builds. The double factorial of an integer k ≥ 0 is defined by

Theorem 4 of the aforementioned paper states the following.

Elevating both sides of the congruences to the fourth power, we deduce that

for all odd primes p. Since 1!! = 1, the equivalence holds also for p = 2.

Now, doing the same to Wilson's theorem reveals that

Since

it follows that

whenever p is prime.

Now, let k be an odd, positive, composite integer. By definition, there exist integers a, b > 1 such that k = ab.

Since k is odd, so are a and b. Thus, both occur in the sequence 1, 3, …, k - 2 and

where | indicates divisibility.

Summing up, for all odd integers k > 1

where p(k) = 1 if k is prime and p(k) = 0 if k is composite.

How it works

When the function f is called with a single argument, k, m, and j are initialized as 3, 1, and 0.

Note that ((k - 2)!!)4 = 1!!4 = 1 = m. In fact, the equality m = ((k - 2)!!)4 will hold at all times. j is a float and will always be equal to ((k - 4)!!)4 % (k - 2) / (k - 2).

While k < n, the right argument of and will get evaluated. Since j = ((k - 4)!!)4 % (k - 2) / (k - 2), as proven in the first paragraph, j = 1/(k - 2) if k - 2 is prime and j = 0 if not. Likewise, since m % k = ((k - 2)!!)4 equals 1 if k is prime and 0 if not, -m % k = k - 1 if k is prime and -m % k = 0 if not. Therefore, -m%k*j*2/k evaluates to 2(k - 1)/(k(k - 2)) = ((k - 2) + k)/(k(k - 2)) = 1/k + 1/(k - 2) if the pair (k - 2, k) consists of twin primes and to 0 if not.

After computing the above, we add the result to the return value of the recursive call f(n,k+2,m*k**4,m%k/k). k gets incremented by 2 so it only takes odd values‡†, we multiply m by k4 since mk4 = ((k - 2)!!)4k4 = (k!!)4, and pass the current value of m % k / k – which equals 1/k if the "old" k is a prime and 0 if not – as parameter j to the function call.

Finally, once k is equal to or greater than n, f will return False and the recursion stops. The return value of f(n) will be the sum of all 1/k + 1/(k - 2) such (k - 2, k) is a twin prime pair and k < n, as desired.

‡ The results from the Background paragraph hold only for odd integers. Since even integers cannot be twin primes, we can skip them safely.


Python 2.7, 34 bytes

lambda x:max(x,[18,1.4]['.'in`x`])


MATL, 48 bytes
tZyyX:UX>*Yat48-tt0>*3#fbbhb~2#fh-*s7M+'X'wZ}4$(

The background character is space. Input is a 2D char array with rows separated by semicolons. So the tests cases have respective inputs:
['    2'; ' 0   '; '   3 ']
[' 1 '; '   '; '1 0']
['0 1  1']
['  2 0 1   ']
['     3'; '      '; '   0  '; '      '; '      '; '2     ']
['90'; ' 8']

The output includes a significant amount of padding whitespace.
Try it online!


How can I golf this JavaScript code, if at all?

Save 3 bytes by assigning document to a variable:

(d=document).write`YOU ARE IN THE BEDROOM.
YOU SEE CRAB NICHOLSON.
HE HAS NO MITTENS.
HIS CLAWS ARE MENACING.
OBVIOUS EXITS ARE:
BATHROOM, KITCHEN, LIVING ROOM
AND CRAB NICHOLSON'S
ULTIMATE LAIR OF AWESOMENESS`;d.body.style.background="#000"

Save 2 bytes by reusing ' CRAB NICHOLSON':

(d=document).write(`YOU ARE IN THE BEDROOM.
YOU SEE${c=' CRAB NICHOLSON'}.
HE HAS NO MITTENS.
HIS CLAWS ARE MENACING.
OBVIOUS EXITS ARE:
BATHROOM, KITCHEN, LIVING ROOM
AND${c}'S
ULTIMATE LAIR OF AWESOMENESS`);d.body.style.background="#000"

Save 1 byte by using .join`<br>`:

(d=document).write(`YOU ARE IN THE BEDROOM._YOU SEE${c=' CRAB NICHOLSON'}._HE HAS NO MITTENS._HIS CLAWS ARE MENACING._OBVIOUS EXITS ARE:_BATHROOM, KITCHEN, LIVING ROOM_AND${c}'S_ULTIMATE LAIR OF AWESOMENESS`.split`_`.join`
`);d.body.style.background="#000"

Further golfs suggested by @Night2:

Save 14 bytes by using .bgColor=0:

(d=document).write(`YOU ARE IN THE BEDROOM._YOU SEE${c=' CRAB NICHOLSON'}._HE HAS NO MITTENS._HIS CLAWS ARE MENACING._OBVIOUS EXITS ARE:_BATHROOM, KITCHEN, LIVING ROOM_AND${c}'S_ULTIMATE LAIR OF AWESOMENESS`.split`_`.join`
`);d.body.bgColor=0

Save 7 bytes by 'forgetting' to close the  tag (YMMV):

(d=document).write(`YOU ARE IN THE BEDROOM._YOU SEE${c=' CRAB NICHOLSON'}._HE HAS NO MITTENS._HIS CLAWS ARE MENACING._OBVIOUS EXITS ARE:_BATHROOM, KITCHEN, LIVING ROOM_AND${c}'S_ULTIMATE LAIR OF AWESOMENESS`.split`_`.join`
`);d.body.bgColor=0


Convert a string to its Rövarspråket equivalent

Retina, 14 + 5 = 19 bytes

Retina is a language that is essentially just .NET regex with as little overhead as possible. The code for this program consists of two files:

i`[b-z-[eiou]]

$0o$0

This reads the input on STDIN and prints the output to STDOUT.

If you call the files pattern.rgx and replacement.rpl, you can run the program simply like

echo "hello" | ./Retina pattern.rgx replacement.rpl

Explanation

This is pretty straightforward, but let me add some explanation anyway (mostly about how Retina works). If Retina is invoked with 2 files it is automatically assumed to operate in "Replace mode", where the first file is the regex and the second file is the pattern.

Retina can be configured (which includes RegexOptions and other options) by prepending the regex with ` and a configuration string. In this case I'm only giving it i which is the normal regex modifier for case insensitivity.

As for the regex itself, it uses .NET's character class subtraction to match any consonant in the ASCII range. The replacement then just writes the match back twice with an o in between.


05AB1E, 10 ... 172 distinct bytes

\]^_abcdefghiijklmnopqrstuvwxyz{|}}}~ƵƵ€Λ‚„…†‡ˆ‰ŠĆĆĆŽƶĀ‘‘’’““””••–—™š›œćŸā¡¢¢¢¤¤¦§¨©ª«¬®¯°±´¶·¸º»¼½½¾¿ÀÁÁÂÃÄÅÇÌÍÐÐÐÐÐÐÑÒÓÔÕÖ×ØÙÚÛÜÝßàáâãäåçèéêëìíîïðñòóôõö÷úü
 -.0123456789;<>@ABCDDDHKKOPQRSTUVWXYZ

Try it online! or validate all test cases (note: the "all test cases" version omits ] and ë, since those don't play well with the header and footer required to run the code repeatedly).

Uses the 05AB1E code page. Validate restricted-source and scoring.

The useful code is just:

Ć            # append the first character of the input to the input
 Ç           # convert to a list of codepoints
  ü-         # pairwise subtraction
    1@       # >= 1?
      D      # duplicate
       O     # sum
        Q    # equal?
         Z   # maximum

The rest amounts to NOOPs.


So, I'll take the easy way:

string s = "";

So, s.Length is now 0, so far so good. But how can we get ReferenceEquals(s, string.Empty) to false.

Piece of cake, just put that into your class:

public static new bool ReferenceEquals(object a, object b) => false;

and the above call will result in false.

I will look for some more sneaky methods, so.


Bash, 44

2 bytes saved thanks to @NahuelFouilleul
2 bytes saved thanks to @manatwork

printf "${f=^[[3%dm.}$f$f
" 1 3 5 3 2 6 5 6 4

Here, blocks are . characters.  ^[ is a literal ASCII escape character (0x1b).

You can recreate this script as follows:
base64 -d <<< cHJpbnRmICIke2Y9G1szJWRtLn0kZiRmCiIgMSAzIDUgMyAyIDYgNSA2IDQ= > rgbgrid.sh


Trump needs your help to stop the Starman!

Julia, 146 142 121 120 bytes

n->split("Pippi Lucas Ness Travis")[2any(isinteger,sqrt([5n^2+4,5n^2-4]))+(n∈[2;[(g=golden)^i+(-g)^-i for i=1:n]])+1]

This creates an unnamed function that returns a boolean. To call it, give it a name, e.g. f=n->....

Ungolfed:

function trump(n::Integer)
    # Determine if n is a Fibonacci number by checking whether
    # 5n^2 ± 4 is a perfect square
    F = any(isinteger, sqrt([5n^2 + 4, 5n^2 - 4]))

    # Determine if n is a Lucas number by generating Lucas
    # numbers and testing for membership
    # golden is a built-in constant containing the golden ratio
    L = n ∈ [2; [golden^i + (-golden)^-i for i = 1:n]]

    # Select the appropriate Earthbound charater using array
    # indexing on a string split into an array on spaces
    return split("Pippi Lucas Ness Travis")[2F+L+1]
end

Fixed an issue and saved 7 bytes thanks to Glen O!


Inspired by @EMBLEM's answer here.

You can put a package's functions in the global namespace when you import them like so:

package main

import ."fmt"

func main() {
    Printf("Hello World!")
}


05AB1E, (5?) 7 bytes
Rightmost two bytes are output formatting
áÇ32%ðý

A port of my Jelly answer, but O5AB1E is more terse for the alphabet filtering.
Try it online!
How?
áÇ32%ðý - take input implicitly
á       - filter keep alphabetical characters
 Ç      - to ordinals
  32    - thirty-two
    %   - modulo (vectorises)
     ð  - push a space character
      ý - join


32-bit Python 2.x (19)

hash(w*9)%537105043

RSA uses a semiprime modulus, and that makes it secure, so using one with my hash algorithm should surely make it even better!1

This is a pure math function, works for all strings (hell, works for any hashable Python object), and doesn't contain any conditionals or special-casing! 32-bit Python can typically be called as python-32 on most systems that have both installed2.

I've tested this, and it returns 18,278 different values for the 18,279 3-letter-or-less uppercase strings. Assigning this to a function takes 11 more bytes:

h=lambda w:hash(w*9)%537105043

and h('YES') == h('NO') == 188338253.

64-bit Python 2.x (19)

hash(w*2)%105706823

Same deal as above.

To come up with these numbers, a little bit of modular math was used. I was looking for a function f and a modulus n such that hash(f('YES')) % n == hash(f('NO')) % n. This is equivalent to testing that n divides d = hash(f('YES')) - hash(f('NO')), i.e. we only have to check the factors of d for suitable values of n.

The ideal n is in the neighbourhood of 20000**2 to reduce the chance of a birthday paradox collision. Finding a suitable n turns out to be a bit of trial and error, playing with all the factors of d (there usually aren't many) and different choices for the function f. Notice though that the trial and error is only needed because I wanted to make n as small as possible (for golfing). If that wasn't a requirement, I could just choose d as my modulus, which is usually sufficiently large.

Note too that you can't pull this trick off using just f(s) = s (the identity function) because the rightmost character of the string has essentially a linear relationship (actually an XOR relationship) with the final hash (the other characters contribute in a much more nonlinear way). The repetition of the string therefore ensures that the differences between the strings are amplified to eliminate the effect of changing only the rightmost character.

1 This is patent nonsense.
2 Python string hashing depends on major version (2 vs 3) and bitness (32-bit vs 64-bit). It does not depend on platform AFAIK.


Python 2, 64 59 bytes
Input is a list of integers, 0 for select and 1 for paste. Outputs by modifying the input list.

def c(o,p=[]):
 for y in o*1:p=[o*1,p][y];o[len(o)/2:0]=p*y

Try it online!
Commented:

def c(o, p=[]):
    # o is the current output, p the current clipbord value
    # Iterate over a copy of the input list
    for y in o*1:
        # If y==0 (select) assign a copy of o to p
        p=[o*1,p][y]
        # Replace the empty slice at index len(o)/2 with:
        #  - a copy of p if y==1 (paste)
        #  - an empty list otherwise
        o[len(o)/2:0]=p*y

Try it online!


JavaScript (ES6), 287 bytes

(a,b)=>[...a].map((l,i)=>{p=k[g="indexOf"](l);q=k[g](o=b[i]);r=r?l==s|o==s?~m[g](l)&&~m[g](o):(x=(p%28/2|0)-(q%28/2|0))<2&x>-2&(y=(p/28|0)-(q/28|0))<2&y>-2:0},r=k=`\`~1!2@3#4$5%6^7&8*9(0)-_=+  \t qQwWeErRtTyYuUiIoOpP[{]}\\|  aAsSdDfFgGhHjJkKlL;:'"
     zZ${m="xXcCvVbBnNmM,<"}.>/?`,m+=s=" ")|r

Explanation

Returns 1 for true and 0 for false.

Note that the \t should be a literal tab character.

(a,b)=>
  [...a].map((l,i)=>{               // for each character l at index i in word A
      p=k[g="indexOf"](l);          // p = index of l in k
      q=k[g](o=b[i]);               // o = letter in word B, q = index of o in k
      r=r?                          // if r
        l==s|o==s?                  // if l or o is a space
          ~m[g](l)&&~m[g](o)        // check the space-matching characters for l and o
        :
          (x=(p%28/2|0)-(q%28/2|0)) // X distance between letters A and B
            <2&x>-2&                // if distance is 2 or greater, r = 0
          (y=(p/28|0)-(q/28|0))     // Y distance between letters A and B
            <2&y>-2                 // if distance is 2 or greater, r = 0
      :0                            // do nothing if r == 0
    },
    r=                              // r = result

    // Keyboard string, each row is 28 characters long, using spaces as padding
    k=`\`~1!2@3#4$5%6^7&8*9(0)-_=+  \t qQwWeErRtTyYuUiIoOpP[{]}\\|  aAsSdDfFgGhHjJkKlL;:'"
     zZ${m="xXcCvVbBnNmM,<"}.>/?`,

    m+=                             // m = list of characters that are adjacent to space
    s=" "                           // add space to the list, s = space character
  )
  |r                                // return r

Test

var solution = (a,b)=>[...a].map((l,i)=>{p=k[g="indexOf"](l);q=k[g](o=b[i]);r=r?l==s|o==s?~m[g](l)&&~m[g](o):(x=(p%28/2|0)-(q%28/2|0))<2&x>-2&(y=(p/28|0)-(q/28|0))<2&y>-2:0},r=k=`\`~1!2@3#4$5%6^7&8*9(0)-_=+  \t qQwWeErRtTyYuUiIoOpP[{]}\\|  aAsSdDfFgGhHjJkKlL;:'"
     zZ${m="xXcCvVbBnNmM,<"}.>/?`,m+=s=" ")|r
A = <input type="text" id="A" value="John Doe" />

B = <input type="text" id="B" value="Jonh Deo" />

<button onclick="result.textContent=solution(A.value,B.value)">Go</button>


Codegolf Rainbow : Fun with Integer-Arrays

Pyth, 14 bytes

thS.ef<b*+tkyy

Test suite!

How?

Algortihm

First off, let's derive the formula this answer is based off. Let's call the function that gives the necessary amount of colour particles \$C(n, i)\$, where \$n\$ is the number of layers and \$i\$ is the index of the colour, 0-based. First, we note that for the \$n^\text{th}\$ layer alone (where \$n\$ is 1-indexed, in this case), we need \$L(n, i)=i+3+8(n-1)\$ colour particles. Keeping this in mind, we sum the results of each \$L(k, i)\$ for each layer \$k\$:

$$C(n, i)=\color{red}{\underbrace{(i+3)}_{1^\text{st} \text{ layer}}} + \color{blue}{\underbrace{(i+3+8)}_{2^\text{nd} \text{ layer}}}+\cdots + \color{green}{\underbrace{[i+3+8(n-1)]}_{n^\text{th} \text{ layer}}}$$
$$C(n, i)=(i+3)n+8\left(0+1+\cdots +n-1\right)$$
$$C(n, i) = (i+3)n+8\cdot\frac{(n-1)n}{2}=(i+3)n+4n(n-1)$$
$$C(n, i)=n(i+3+4n-4)\implies \boxed{C(n,i)=n(4n+i-1)}$$

Therefore, we now know that the maximum number of possible layers, call it \$k\$, must satisfy the inequality \$C(k, i) \le I_i\$, where \$I_i\$ is the \$i^\text{th}\$ element of the input list.

Implementation

This implements the function \$C\$, and iterates (.e) over the input list, with \$k\$ being the index (0-based) and \$b\$ being the element. For each value, the program searches the first positive integer \$T\$ for which \$b<C(T, i)\$ (the logical negation of \$C(T, i)\le b\$, the condition we deduced earlier), then finds the minimum result and decrements it. This way, instead of searching for the highest integer that does satisfy a condition, we search for the lowest that does not and subtract one from it to make up for the offset of 1.


Python, 179 chars

i=input()
a=i%4*2+1
b=i/4%4*2
c=i/16%6
d=i/96*5
s='NNRKRNRNKRNRKNRNRKRNRNNKRRNKNRRNKRNRKNNRRKNRNRKRNN'[d:d+5]
s=s[:c]+'Q'+s[c:]
if a>b:a,b=b,a
print s[:a]+'B'+s[a:b-1]+'B'+s[b-1:]

Builds it backwards from the description order so we don't have to count the spaces that are already taken.


Linear Function Solver from Two Points (x,y)

GNU dc, 30 24 bytes
[sysxly-rlx-/dlx*lyr-]sL

Defines a macro L such that
(x1, y1, x2, y2) should be pushed to the stack in that order before calling, and after calling L, (a, c) may be popped from the stack (in reverse order of course - it is a stack).
Testcase (save as "linear.dc" and run dc linear.dc):

[sysxly-rlx-/dlx*lyr-]sL   # Define L macro

10                         # Push x1 to the stack
22.5                       # Push y1 to the stack
5                          # Push x2 to the stack
12.5                       # Push y2 to the stack

lLx                        # Call L macro
f                          # Dump the stack

Output is:

$ dc linear.dc
2.5
2
$

Explanation of L macro:

sy pop y2 to y register
sx pop x2 to x register
ly push y register (y2)
- subtract y2 from y1
r swap (y1 - y2) and x1 on stack
lx push x register (x2)
- subtract x2 from x1
/ divide (y1 - y2) by (x1 - x2) to get gradient
d duplicate gradient
lx push x register (x2)
* multiply (x2) by gradient
ly push y register (y2)
r swap (y2) and (x2 * gradient) on stack
- subtract (x2 * gradient) from (y2)


For 2 arrays, subtract every element in one array from the position-matching element in the other

R, 3 chars
(following Chris' counting method that includes the variable names in the count)
a-b

a and b can be defined as follows:
a <- c(10,11,12)
b <- c(1,2,3)

(c is the array construction function in R)


Jelly, 7 bytes

SH_÷@HP

Try it online!

Explanation

Let’s read this chain:

The implicit argument is a list [a, b, c].
First we read S. This takes the sum: a + b + c.
Then, we read H. This halves it: (a + b + c)/2. (This is s.)
Then, we read a dyad _ (subtract), followed by another dyad. This is a hook: it lacks a right argument, so it receives the argument to this chain, [a, b, c], giving us [s-a, s-b, s-c]. (This is the fifth chain pattern in the table here.)
Then, we read the dyad-monad pair ÷@H. This is a fork: ÷@ is division with the arguments flipped, and H is halve, so our working value gets Half the argument to this chain ÷’d by it. This vectorizes; we’re left with [(a/2)/(s-a), (b/2)/(s-b), (c/2)/(s-c)]. (This is the second chain pattern in the table here.)
Finally, we take the product with P, getting us abc/(8(s-a)(s-b)(s-c)).

View a tree-like graph of how the links fit together.


JavaScript (ES6),  128 125  124 bytes
Saved 1 bytes thanks to @OlivierGrégoire
Outputs each version on a separate line. Ordered from highest to lowest major version, and from lowest to highest revision.

f=(r=v=28)=>v?r<parseInt('0111131000244655ah002678b8940'[v],36)?(1+v/10).toFixed(1)+(r|v>22?'.'+r:'')+`
`+f(r+1):f(+!v--):''

Try it online!
How?
The major and minor versions are held in the variable \$v \in [0..27]\$:

major = \$\lfloor v/10+1\rfloor\$
minor = \$v \bmod 10\$

The revision is held in the variable \$r\ge0\$. The maximum value of \$r\$ depends on \$v\$ and is stored in a lookup table encoded in Base-36. Any \$0\$ in this table means that this version was not released at all.
Besides, we use the test \$v>22\$ to know whether the revision should be included even when it's \$0\$ (starting with Python 3.3.0).


Use \def
\def is an incredibly powerful tool when it comes to golfing.  \def allows you to assign something to a variable.
This can be used simply with the to save a number you may use a bunch of times for instance
\def\x{1456}

Will define 1456 as \x for future use much like saving a variable might in a programming language.
However \def is much more powerful than that, because \def doesn't define a variable it defines a snippet of code to be substituted into the program whenever it is called.
For example say you want to draw some rectangles using \draw  you might write the following code:
\draw(0,0)rectangle(3,4)rectangle(8,0);\draw(2,2)rectangle(3,3);

Using \def this could be written as:
\def\x{)rectangle(}\draw(0,0\x3,4\x8,0);\draw(2,2\x3,3);


Is my kids' alphabet mat properly grouped by colors?

MATL, 16 15 bytes

1e"G@=4&1ZI1>vzg

Input is a 2D char array (with rows separated by ;). Output is 0 if input qualifies, or 1 otherwise.

Try it online! Or verify all test cases.

Explanation

The code essentialy checks if each char in the input has only one connected component, considering 4-connectivity (that is, no diagonals).

Repeated chars are processed repeatedly (which is golfier than deduplicating).

1e       % Implicit input. Reshape into a row vector of chars
"        % For each char
  G      %   Push input again
  @      %   Push current char
  =      %   Equal (element-wise)? Gives a matrix of zeros and ones, where one
         %   represents the presence of the current char
  4      %   Push 4. This will indicate 4-connectivity
  &1ZI   %   Matrix with labels of connected componnents. Inputs are a number (4)
         %   to indicate connectivity, and a binary matrix. The output is a matrix
         %   the same size as the input where each connected componnent of ones
         %   in the input is replaced by a different integer starting at 1
  1>     %   Greater than 1 (element-wise)? The result is a matrix. If the result
         %   is true for some entry the input doesn't qualify
  v      %   Concatenate vertically with results from previous iterations
  z      %   Number of nonzero/true values
  g      %   Logical. Converts nonzero to true
         % Implicit end. Implicit display. False / true are displayed as 0 / 1


Haskell, 1007 One Thousand and One Bytes 923 900 830 bytes

I happened to have already made a happycube solver, now I just need to golf it. Taking a ten byte penalty for using fancy block elements:

import Data.List
r=reverse;z=zipWith;f=foldl1;t=take;g=t 4;d=drop;m=map
n x=t 5x:n(d 4x)
u v a b=init a++v max(last a)(b!!0):d 1b
a!b|k<- \x y->last$' ':[a|b!!x!!y>0]=(k 0<$>[0..4]):((\i->k 3(4-i):[a,a,a]++[k 1i])<$>[1..3])++[k 2<$>[4,3..0]]
p y|(e:v)<-m(g.n.cycle.m(read.pure))$"0":(lines$y),[j,k,l,x,y,r]<-x v=mapM putStrLn$f(u z)$f(z(u id))<$>z(z(!))[a,"▒█▒█",a][[e,k,e,e],[l,j,x,r],[e,y,e,e]];a=" ░  "
x(p:q)=[p:u|x<-permutations q,u@[e,g,y,k,l]<-sequence$(\c->nub$[c,r.m r$c]>>=g.m g.tails.cycle)<$>x,and$zipWith4(\a n b m->all(==1).init.d 1$z(+)(a!!n)$r$b!!m)([l,e,p,p,p,p,e]++u)[3,3,0,3,1,2,0,1,2,2,2,1](y:g:u++[y,k,k,l,g])[1,0,2,1,3,0,0,0,3,1,2,3]++z((((==1).sum.m(!!0)).).z(!!))[[p,e,g],[y,p,e],[k,p,g],[k,p,y],[l,y,e],[l,y,k],[l,g,e],[l,g,k]][[0,3,1],[0..2],[0,3,2],[1..3],[0,1,1],[3,2,2],[1,0,0],[2,3,3]]]!!0

That's a mouthful. Usage:

*Main> mapM_ (\s->p s>>putStrLn"")["0010010101010101\n0010001011011010\n0101001001010010\n0010110100101101\n0010110110101101\n0010001011010101","0001110110101101\n1010010111011101\n0101010101010010\n1010001000100011\n1010001001010001\n0110010100100010","0101001011011010\n0010001000100010\n0101001011010010\n0101010101011010\n0101101001011101\n1010001001011101"]
     ░ ░
     ░░░
    ░░░░░
     ░░░
▒▒ ▒▒░█░▒▒ ▒█ █
 ▒▒▒█████▒▒▒█████
▒▒▒▒▒███▒▒▒▒▒███
 ▒▒▒█████▒▒▒█████
  ▒ ░█░█▒▒ ▒▒ █ █
    ░░░░
     ░░░░
    ░░░░
     ░ ░

      ░
     ░░░░
    ░░░░
     ░░░░
▒▒ ▒▒░░██ ▒ ▒█ █
▒▒▒▒█████▒▒▒▒███
 ▒▒▒▒███▒▒▒▒▒████
▒▒▒▒█████▒▒▒████
▒▒ ▒█░█░█ ▒ █ █
     ░░░░
    ░░░░
     ░░░░
     ░ ░

    ░░ ░
    ░░░░░
     ░░░
    ░░░░░
  ▒ ▒█░█░ ▒ ▒ █
▒▒▒▒▒███▒▒▒▒▒███
 ▒▒▒█████▒▒▒█████
▒▒▒▒▒███▒▒▒▒▒███
 ▒ ▒██░██ ▒   █
     ░░░░
    ░░░░
     ░░░░
    ░░ ░░

Some of the examples have more than one solutions, that's why some of the outputs look different. Ungolfed:

import Data.List (nub, transpose, (\\))
import Control.Monad (guard)

newtype CubePiece = CubePiece [[Int]] deriving Eq
newtype Solution = Solution [CubePiece]

side :: Int -> CubePiece -> [Int]
side n (CubePiece c) = c!!n

corner :: Int -> CubePiece -> Int
corner n (CubePiece c) = head $ c!!n

strToCube str = CubePiece $ hs' . (\x@(a:_)->x++[a]) $ l
  where
    l = map (read.pure) str
    hs' [a] = []
    hs' x = take 5 x : hs' (drop 4 x)

orientations :: CubePiece -> [CubePiece]
orientations (CubePiece cube) = map CubePiece $ nub $ (take 4 . iterate rotate $ cube) ++
  (take 4 . iterate rotate . reverse . map reverse $ cube)
  where
  rotate (a:as) = as++[a]

sideFits ::  (CubePiece, Int) -> (CubePiece, Int) -> Bool
sideFits (c1,n1) (c2,n2) = case (zipWith (+) a b) of
  [_,1,1,1,_] -> True
  _ -> False
  where
  a = side n1 c1
  b = reverse $ side n2 c2

cornerFits :: (CubePiece, Int) -> (CubePiece, Int) -> (CubePiece, Int) -> Bool
cornerFits (c1,n1) (c2,n2) (c3,n3) = a + b + c == 1
  where
  a = corner n1 c1
  b = corner n2 c2
  c = corner n3 c3

printSolution str = putStrLn . specialUnlines . map rivi $
  [[empty,gshow '░' c2,empty,empty],[gshow '▒' c3,gshow '█'c1,gshow '▒'c4,gshow '█'c6],[empty,gshow '░'c5,empty,empty]]
  where
  Solution [c1,c2,c3,c4,c5,c6] = solve . map strToCube . lines $ str
  empty = replicate 5 "     "
  rivi = map (foldl1 specialConcat) . transpose
  specialUnlines = unlines . foldl1(\a b->init a++[zipWith max(last a)(head b)]++tail b)
  specialConcat a b
    | last a==' '=init a++b
    | otherwise = a++tail b

gshow char (CubePiece c) =
  [ map (k 0) [0..4]
  , (k 3 3) : m ++ [(k 1 1)]
  , (k 3 2) : m ++ [(k 1 2)]
  , (k 3 1) : m ++ [(k 1 3)]
  , map (k 2)[4,3..0]
  ]
  where
  k n1 n2 = if (c!!n1)!!n2 == 1 then char else ' '
  m=replicate 3 char

solve :: [CubePiece] -> Solution
solve pieces = Solution $ head $ do
  let c1' = pieces!!0
  let c1 = c1'

  c2'  <- pieces \\ [c1']
  c2   <- orientations c2'
  guard $ sideFits (c1,0) (c2,2)

  c3'  <- pieces \\ [c1',c2']
  c3   <- orientations c3'
  guard $ sideFits (c1,3) (c3,1)
  guard $ sideFits (c2,3) (c3,0)
  guard $ cornerFits (c1,0) (c2,3) (c3,1)

  c4'  <- pieces \\ [c1',c2',c3']
  c4   <- orientations c4'
  guard $ sideFits (c1,1) (c4,3)
  guard $ sideFits (c2,1) (c4,0)
  guard $ cornerFits (c1,1) (c2,2) (c4,0)
  c5' <- pieces \\ [c1',c2',c3',c4']
  c5 <- orientations c5'
  guard $ sideFits (c1,2) (c5,0)
  guard $ sideFits (c4,2) (c5,1)
  guard $ sideFits (c3,2) (c5,3)
  guard $ cornerFits (c5,0) (c1,3) (c3,2)
  guard $ cornerFits (c5,1) (c1,2) (c4,3)

  c6' <- pieces \\ [c1',c2',c3',c4',c5']
  c6 <- orientations c6'
  guard $ sideFits (c6,0) (c2,0)
  guard $ sideFits (c6,1) (c3,3)
  guard $ sideFits (c6,2) (c5,2)
  guard $ sideFits (c6,3) (c4,1)
  guard $ cornerFits (c6,0) (c4,1) (c2,1)
  guard $ cornerFits (c6,3) (c4,2) (c5,2)
  guard $ cornerFits (c6,1) (c3,0) (c2,0)
  guard $ cornerFits (c6,2) (c3,3) (c5,3)
  return $ [c1,c2,c3,c4,c5,c6]

main = mapM_ printSolution ["0010010101010101\n0010001011011010\n0101001001010010\n0010110100101101\n0010110110101101\n0010001011010101","0001110110101101\n1010010111011101\n0101010101010010\n1010001000100011\n1010001001010001\n0110010100100010","0101001011011010\n0010001000100010\n0101001011010010\n0101010101011010\n0101101001011101\n1010001001011101"]


Python 2, 132 115 bytes

-17 bytes thanks to Leaky Nun

x,n=input()
o=[]
i=1
while x:
 t=x[0]
 while[t+i]==x[i:i+1]:i+=1
 o+=[[t,'-',t+i-1],x[:i]][i<n];x=x[i:];i=1
print o

Try it online!


Pyth - 11 bytes
This will eventually guess the correct answer. On average 2500 tries. Literally just takes random guesses no matter what the input is. Since you can't define rateGuess in pyth just takes (uneeded) input from stdin and outputs to stdout.
Ofql{T4^UT4

O         Pick random
 f        filter
  ql{T4   set length is four (checks for duplicates)
  ^  4    Caretesian product with 4 repeats
   UT     Unary range till 10


Hexagonal coordinates: Polar to Cartesian


Python, 39 bytes

f=lambda n:4**(n>1)*(n<16)or 2*f(n**.5)

Counts how many times one must take the square root for n to be below 16, with some special-casing to avoid outputs of 2.

If 2 were included, we could do

f=lambda n:n<2or 2*f(n**.5)

with True for 1.

41 bytes:

f=lambda n,i=1:i*(2**i>n)or f(n,i<<1+i%2)

Repeatedly doubles the exponent i until 2**i>n. Skips from i=1 to i=4 by shifting an additional bit when i is odd.

Alt 45 bytes:

f=lambda n,i=4:4**(n>1)*(2**i>n)or 2*f(n,i*2)


JavaScript (ES6),  184 178  173 bytes
Takes input as (initial_board)(target_board). Returns \$0\$ or \$1\$.

a=>g=b=>a+''==b|a.some((r,y)=>r.some((v,x,A,X,R)=>[-1,0,1,2].some(h=>(A=a[y+(R=~-h%2)]||0)[X=x+(h%=2)]&v>(R=a[y+R*2]||0)[h+=x+h]&&g(b,A[X]=r[x]=R[h]++)&(A[X]=r[x]=R[h]--))))

Try it online!
(removed the last two test cases that take too much time for TIO)
Commented
a =>                             // main function taking the initial board a[]
  g = b =>                       // g = recursive function taking the target board b[]
    a + '' == b |                // yield a truthy result if a[] is matching b[]
    a.some((r, y) =>             // for each row r[] at position y in a[]:
      r.some((v, x, A, X, R) =>  //   for each value v at position x in r[]:
        [-1, 0, 1, 2]            //     list of directions (West, North, East, South)
        .some(h =>               //     for each direction h:
          ( A =                  //       A = a[y + dy]
            a[y + (R = ~-h % 2)] //       R = dy
            || 0                 //       use a dummy row if we're out of the board
          )[X = x + (h %= 2)]    //       h = dx, X = x + dx
          &                      //       yield 1 if there's a peg on the skipped cell
          ( R =                  //       R = target row
            a[y + R * 2]         //         = a[y + 2 * dy]
            || 0                 //       use a dummy row if we're out of the board
          )[h += x + h]          //       h = x + 2 * dx = target column
          < v                    //       yield 1 if there's no peg on the target cell
          &&                     //       and there's a peg on the source cell (0 < 1)
          g(                     //       if the above result is true, do a recursive call:
            b,                   //         pass b[] unchanged
            A[X] = r[x] =        //         clear the source and skipped cells
            R[h]++               //         set the target cell
          ) & (                  //       and then restore the board to its initial state:
            A[X] = r[x] =        //         set the source and skipped cells
            R[h]--               //         clear the target cell
          )                      //
        )                        //     end of some() over directions
      )                          //   end of some() over columns
    )                            // end of some() over rows


Pyth, 11 bytes
u++GHG<GhQk

Simple reduction.


Jelly, 8 bytes

Œ!Z>2\Sċ

Try it online! (takes a while) or verify the smaller test cases.

How it works

Œ!Z>2\Sċ  Main link. Arguments: n, m

Œ!        Generate the matrix of all permutations of [1, ..., n].
  Z       Zip/transpose, placing the permutations in the columns.
   >2\    Compare columns pairwise with vectorizing greater-than.
          This generates a 1 in the column for each rise in that permutation.
      S   Compute the vectorizing sum of the columns, counting the number of rises.
       ċ  Count how many times m appears in the computed counts.


Reconstruct a 3d arrangement of cubes from two of its projections

APL (Dyalog Unicode), 11 bytes

+.(⌈,×)/+⌿¨

Try it online!

Takes V1 and V2 as two binary matrices inside a nested vector, and V1 is rotated so that it vertically lines up with V2. Returns doubly nested vector of (min, max).

How it works

The first column of V1 and the first column of V2 decide the first vertical layer of 4x4 cells. If n cells are shaded in V1's column and m cells in V2's, the minimum number of shaded cells in the corresponding 4x4 layer is max(m,n), and the maximum is m * n.

min          |  max
  | 1 0 1 0  |    | 1 0 1 0
-----------  |  -----------
1 | 1 0 0 0  |  1 | 1 0 1 0
1 | 1 0 0 0  |  1 | 1 0 1 0
0 | 0 0 0 0  |  0 | 0 0 0 0
1 | 0 0 1 0  |  1 | 1 0 1 0

Therefore, it suffices to count ones in each column, and evaluate sums of the pairwise max (for minimum) and pairwise product (for maximum) of the column sums.

+.(⌈,×)/+⌿¨
        +⌿¨  ⍝ In each matrix, evaluate column sums
       /     ⍝ Over the two vectors,
+. ⌈         ⍝ Evaluate the sum of pairwise max
    ,        ⍝ and
+.   ×       ⍝ the sum of pairwise product


Truncate consecutive character runs to n length

C, 81 78

Modifies the incoming string.

c,a;f(p,n)char*p;{char*s=p;for(;*p;s+=c<n)*s=*p++,a^*s?c=0:++c,a=*s;c=a=*s=0;}

Test Program

Requires two parameters, the first is the string to truncate, the second is the length limit.

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

int main(int argc, const char **argv)
{
    char *input=malloc(strlen(argv[1])+1);
    strcpy(input,argv[1]);
    f(input,atoi(argv[2]));
    printf("%s\n",input);
    free(input);
    return 0;
}

Explanation:

c,a;                 //declare two global integers, initialized to zero.
                     //c is the run length, a is the previous character
f(char*p,int n){...} //define function f to truncate input
char*s=p;            //copy p to s; p is source, s is destination
for(;*p              //while there is a source character
;s+=c<n)             //increment copied pointer if run is under the limit
*s=*p++,             //copy from source to destination, increment source
a^*s?c=0:++c,        //if previous character != current then run=0 else increment run
a=*s;                //previous character = current source character
c=a=*s=0;            //after loop, terminate destination string with NUL and reset c and a.

This works because the source pointer will always be equal to or greater than the destination pointer, so we can write over the string as we parse it.


Perl, 91 96  92 chars
$_=`curl -sL qr.net/_9`;s/<[^>]+nt="(.+)/$c+=$1/ge;say"A",s/<td.*"ans//g,C,$c+s/<tr.*"com//g

Some stuff just to break solutions of others ha ha ha :-P
show 93 more comments

href
nt="99" (ha ha crash @Fez Vrasta)
a
,show 99show 99 ha ha
href
href
href
ha ha haha :-D
jeeez, just broke my own answer! I discovered that one of the above tricks, which I thought does nothing, will start working after this answer is not edited for some time! So your solutions will work only for some time. That's why you had seen +1 more answer in your solutions..  It's a timed bomb! My answer is already prone to it :-) Aaah, found a way how to launch it NOW...


Fastest python code to find a set of winning words in this game

Here's an idea - you can avoid checking lots of words by noticing that most words have awful scores.  Say you have found a pretty good scoring play that gets you 50 points.  Then any play with more than 50 points must have a word of at least ceil(51/3)=17 points.  So any word that can't possibly generate 17 points can be ignored.

Here's some code that does the above.  We compute the best possible score for each word in the dictionary, and store it in an array indexed by score.  Then we use that array to check only words that have the required minimum score.

from itertools import permutations
import time

S={'A':0,'E':0,'I':0,'O':0,'U':0,
   'L':1,'T':1,'N':1,
   'R':2,'D':2,'S':2,
   'G':3,'B':3,'M':3,
   'C':4,'H':4,'P':4,
   'F':5,'W':5,'V':5,
   'Y':6,'K':6,'J':6,
   'Q':7,'X':7,'Z':7,
   }

def best_word(min, s):
    global score_to_words
    best_score = 0
    best_word = ''
    for i in xrange(min, 100):
        for w in score_to_words[i]:
            score = (-2*len(w)+2*(w.count('A')+w.count('E')+w.count('I')+w.count('O')+w.count('U')) +
                      3*w.count(s[0])+4*w.count(s[1])+5*w.count(s[2])+6*w.count(s[3])+7*w.count(s[4])+
                      8*w.count(s[5])+9*w.count(s[6]))
            if score > best_score:
                best_score = score
                best_word = w
    return (best_score, best_word)

def load_words():
    global score_to_words
    wlist = [l.strip().upper() for l in open('/usr/share/dict/words') if l[0].lower() == l[0]]
    score_to_words = [[] for i in xrange(100)]
    for w in wlist: score_to_words[sum(S[c] for c in w)].append(w)
    for i in xrange(100):
        if score_to_words[i]: print i, len(score_to_words[i])

def find_best_words():
    load_words()
    best = 0
    bestwords = ()
    for c1 in permutations('LTN'):
        for c2 in permutations('RDS'):
            for c3 in permutations('GBM'):
            print time.ctime(),c1,c2,c3
                for c4 in permutations('CHP'):
                    for c5 in permutations('FWV'):
                        for c6 in permutations('YJK'):
                            for c7 in permutations('QZX'):
                                sets = zip(c1, c2, c3, c4, c5, c6, c7)
                                (s1, w1) = best_word((best + 3) / 3, sets[0])
                                (s2, w2) = best_word((best - s1 + 2) / 2, sets[1])
                                (s3, w3) = best_word(best - s1 - s2 + 1, sets[2])
                                score = s1 + s2 + s3
                                if score > best:
                                    best = score
                                    bestwords = (w1, w2, w3)
                                    print score, w1, w2, w3
    return bestwords, best

if __name__ == '__main__':
    import timeit
    print timeit.timeit('print find_best_words()', 'from __main__ import find_best_words', number=1)

The minimum score gets rapidly up to 100, which means we need only consider 33+ point words, which is a very small fraction of the overall total (my /usr/share/dict/words has 208662 valid words, only 1723 of which are 33+ points = 0.8%).  Runs in about half an hour on my machine and generates:

(('MAXILLOPREMAXILLARY', 'KNICKKNACKED', 'ZIGZAGWISE'), 101)


Concentric rings on a snub square tiling

Ruby, 26 bytes

->n{~-n*12-496/4**n%4+1/n}

Try it online!

Revised version adding 1/n and subtracting 496/4**n%4 to get the +1,-3,-3,-1 offset for the first 4 terms.

Ruby, 32 bytes

->n{n>4?~-n*12:[0,1,9,21,35][n]}

Try it online!

After 4, the sequence settles down to (n-1)*12. See diagram below (the equilateral triangles have been distorted into 45 degree isosceles triangles and the entire diagram rotated 45 degrees, but it remains topologically equivalent.)


Python 2, 60 bytes

p=[0]
for i in input():p+=[n^i for n in p]
print~-p.count(0)

Try it online!
This generate the powerset from the input (based on this answer), reducing each subset by xor.
The output will be the amount of 0s (0 = all bytes/dots appear an even number of times).
In fact the xoring is done instead of the "powerset appending", but the result is the same


Decode Polybus Square/Tap Code/Prison Code

Python 2,  40  39 bytes
-1 thanks to kops! (Multiply before integer division)

lambda a:[chr(r*16/3+c+59)for r,c in a]

An unnamed function accepting an iterable of pairs which returns a list of characters.
Try it online!


Print the prime factorization of the greatest common divisor of two numbers

Python 3, 255 250  237 226 188 180 150 142 137 136 chars
a,b=map(int,input().split())
t,g='',1
while g<a:
 g,p=g+1,0
 if a%g+b%g<1:
  while a%g+b%g<1:a/=g;b/=g;p+=1
  t+='%d^%d '%(g,p)
print(t)

It's amazing how much I could shorten this by just skipping stuff (like, you know, finding the gcd)! Also I could reduce 10 more chars by making this a function that expects 2 ints, like some other answers, instead of reading from stdin.


Exponentiation to multiplication to addition

Retina, 302 bytes
I'm sure this can be golfed, but at this point, I'm just glad it works. The exponentiation and multiplication sections are both very similar, but since order of operations is important, I don't know how to combine them.
y - Exponentiation
x - Multiplication
p - Addition
\d+
$*
{1`(\(\w+\)|1+)y(\(\w+\)|1+)
>$0<
(?<=>(\(\w+\)|1+)y1*)1
$1x
>(\(\w+\)|1+)y
(
x<
)
\((1+(x1+)*)\)(?!y)
$1
(?<!1)(1+)x(\(\w+\)|1+\1)(?!1)
$2x$1
1`(\(\w+\)|1+)x1+
>$0<
(?<=>(\(\w+\)|1+)x1*)1
$1p
>(\(\w+\)|1+)x
(
p<
)
(?<!x|y)\((1+(p1+)*)\)(?!x|y)
$1
y\((1+)p([1p]*\))
y($1$2
}`y\((1+)\)
y$1
1+
$.0

Try it online - all test cases
Test case converter
Explanation
\d+                             Convert to unary
$*
{1`(\(\w+\)|1+)y(\(\w+\)|1+)    Begin loop: Delimit current exponentiation group
>$0<
(?<=>(\(\w+\)|1+)y1*)1          Replace exponentiation with multiplication
$1x
>(\(\w+\)|1+)y                  Replace garbage with parentheses
(
x<
)
\((1+(x1+)*)\)(?!y)             Remove unnecessary parentheses around multiplication
$1
(?<!1)(1+)x(\(\w+\)|1+\1)(?!1)  Maybe swap order of multiplicands
$2x$1
1`(\(\w+\)|1+)x1+               Delimit current multiplication group
>$0<
(?<=>(\(\w+\)|1+)x1*)1          Replace multiplication with addition
$1p
>(\(\w+\)|1+)x                  Replace garbage with parentheses
(
p<
)
(?<!x|y)\((1+(p1+)*)\)(?!x|y)   Remove unnecessary parentheses around addition
$1
y\((1+)p([1p]*\))               Handle the 4th test case by adding if necessary
y($1$2
}`y\((1+)\)                     End of loop
y$1
1+                              Convert unary back to decimal
$.0

You may also notice that the most commonly used group is (\(\w+\)|1+). This matches an inner expression with parentheses, or an integer. I chose to use the symbols I did so that I could use \w rather than a character class. I'm not sure if it would be better to use non-word symbols and replace some lookarounds with word borders (\b).


MATL, 17 16 bytes
1 byte removed thanks to a suggestion by Dennis
2$St!<Rz2\'oe'w)

This works in current version (15.0.0) of the language.
Try it online!
Explanation
This uses the definition of parity in terms of inversions. An inversion is a pair of elements in the second array that are in the "wrong" order compared with the first array. Since the first array need not be sorted, we first sort it and the same rearrangement needed for that sorting is applied to the second array. Then an inversion corresponds to a pair of elements that is not increasing in the second array.
Note also that the two input arrays can be swapped and the result is the same. So it's not important which array is considered to be the "original" and which the "permuted".
2$S     % implicitly take two row vectors. Sort second and apply the indices
        % of that sorting to the first
t!      % duplicate. Transpose into column vector
<       % true for elements of the column vector that exceed those of the
        % row vector. Gives a 2D array with all pairs of comparisons
R       % keep only upper triangular part of that array
z       % number of nonzero elements. This is the number of inversions
2\      % parity of that number: gives 0 or 1
'oe'w   % push string 'eo' below the top of the stack
)       % apply index to produce 'e' or 'o'. An index 1 refers to the first
        % element, whereas 0 refers to the last. Implicitly display


Jelly, 5 bytes

_ÆD⁵e

Making heavy use of Anything else that is not forbidden is allowed.

Try it online!

How it works

_ÆD⁵e  Main link. Left input: a. Right input: b. Additional input: n

_      Subtract b from a.
 ÆD    Compute all divisors of the difference.
   ⁵e  Test if n is among the divisors.


fit 22 (perhaps 23) of a specific 3d pentacube into a 5x5 cube

Plane-based analysis, 30+ points

The basic idea is explained in the comment at the top of the class. This runs for about 8 minutes on my desktop and finds 90560 22-tile solutions, possibly including symmetrical ones; since a cube has only 48 isometries, that corresponds to at least 1887 distinct solutions. However, it doesn't guarantee that there are no more: only that if there are any more, they don't have two opposite exterior faces which contain 3 cubies each of 8.

Two sample solutions:

ddbee dubb. ruut. rlktt llkk.
adbbe aduee rrutt lrkjj lookj
aa.ff qa.f. .q.vv ioov. iiojj
ggchf qgcfh qqssv impnv mipnn
gcchh gcssh ...s. .m.pn mmppn

.ggff qqgf. .q.uu .llpu oolpp
bgddf bgvdf qqvu. ooiup ollip
bbdee rbdve rrvv. .mijj mmiij
hhcea rhcae .rstt kmsnt mknjj
hccaa hc.a. .sst. ks.nt kknn.

Checking for 23-tile solutions with the same principle is a matter of changing tilesInPlane2 to 7; it runs for about one minute and finds no solutions.

I suggest redirecting stdout to a file and watching the progress reports on stderr.

import java.util.*;

// Overall approach follows a strategy proposed by Ed Pegg.
// If we place one 8-tile board on plane 0 sticking into plane 1,
// and one 8-tile board on plane 4 sticking into plane 3,
// what can fit into plane 2 sticking into planes 1 and 3?
// Since an 8-tile plane occupies at least 16/25 of the adjacent plane, we're looking to fit 4/7 of the tiles from
// plane 2 into the gaps left by the tiles from plane 0, and then the remaining 3/7 into the gaps left
// by the tiles from plane 4.
public class CodeGolf36250 {
    // Bit mask: 25 bits indicating the "main" plane, 25 bits indicating the "adjacent" plane
    static final long mainPlane = (1L << 25) - 1;
    static final long adjPlane = ((1L << 25) - 1) << 25;

    static final int tilesInPlane2 = 6;
    static final int tilesInPlanes2_3 = (tilesInPlane2 + 1) / 2; // Half rounded up

    public static void main(String[] args) {
        Set<Long> primitives = new HashSet<Long>();
        for (int x = 0; x < 4; x++) {
            for (int y = 0; y < 4; y++) {
                int tl = x + y * 5;
                // We consider only positions where we put 3 cubies in the main plane and 2 in the adjacent plane.
                // Diagram format: main plane, adj plane
                // So we have
                //  c000 c100   c001 c101
                //  c010 c110   c011 c111
                long c000 = 1L << tl, c100 = c000 << 1, c010 = c000 << 5, c110 = c100 << 5;
                long c001 = c000 << 25, c101 = c100 << 25, c011 = c010 << 25, c111 = c110 << 25;
                // ##  .#  |  ##  #.  |  #.  #.  |  .#  .#
                // #.  #.  |  .#  .#  |  ##  .#  |  ##  #.
                primitives.add(c000 + c100 + c010 + c101 + c011);
                primitives.add(c000 + c100 + c110 + c001 + c111);
                primitives.add(c000 + c010 + c110 + c001 + c111);
                primitives.add(c100 + c010 + c110 + c101 + c011);
                // ##  .#  |  ##  ..  |  ##  #.  |  ##  ..
                // #.  .#  |  #.  ##  |  .#  #.  |  .#  ##
                primitives.add(c000 + c100 + c010 + c101 + c111);
                primitives.add(c000 + c100 + c010 + c011 + c111);
                primitives.add(c000 + c100 + c110 + c001 + c011);
                primitives.add(c000 + c100 + c110 + c011 + c111);
                // #.  .#  |  #.  ##  |  .#  #.  |  .#  ##
                // ##  .#  |  ##  ..  |  ##  #.  |  ##  ..
                primitives.add(c000 + c010 + c110 + c101 + c111);
                primitives.add(c000 + c010 + c110 + c001 + c101);
                primitives.add(c100 + c010 + c110 + c001 + c011);
                primitives.add(c100 + c010 + c110 + c001 + c101);
            }
        }

        // Building full sets of tiles in the two planes uses far too much memory in the intermediate numbers
        // (in particular, the 5-tile sets).
        // It's much more efficient to see what coverings of the main plane we get and then for the high-count
        // sets we care about, to expand them to the adjacent plane.
        List<Set<TileSet>> nTiles = new ArrayList<Set<TileSet>>();
        nTiles.add(new HashSet<TileSet>()); // 0 tiles
        nTiles.get(0).add(new TileSet());
        for (int n = 1; n < 9; n++) {
            Set<TileSet> next = new HashSet<TileSet>();
            for (TileSet board : nTiles.get(n - 1)) {
                for (long prim : primitives) {
                    if ((board.sum & prim) == 0) {
                        TileSet newBoard = new TileSet();
                        newBoard.addAll(board);
                        newBoard.add(prim & mainPlane);
                        next.add(newBoard);
                    }
                }
            }
            nTiles.add(next);
            System.err.println(n+" tiles: " + next.size());
        }

        // Needed for the expansion.
        Map<Long, Set<Long>> primsByMainPlane = new HashMap<Long, Set<Long>>();
        for (Long prim : primitives) {
            Set<Long> group = primsByMainPlane.get(prim & mainPlane);
            if (group == null) primsByMainPlane.put(prim & mainPlane, group = new HashSet<Long>());
            group.add(prim);
        }

        Map<Long, Set<TileSet>> boards8ByAdjGaps = new HashMap<Long, Set<TileSet>>();
        for (TileSet board8 : nTiles.get(8)) {
            for (TileSet expandedBoard8 : expand(board8, primsByMainPlane)) {
                long expansion = (~expandedBoard8.sum) & adjPlane;
                Set<TileSet> boards8 = boards8ByAdjGaps.get(expansion);
                if (boards8 == null) boards8ByAdjGaps.put(expansion, boards8 = new HashSet<TileSet>());
                boards8.add(expandedBoard8);
            }
        }
        System.err.println(boards8ByAdjGaps.size() + " distinct gap sets in plane next to full one");

        long solutions = 0;
        int progress = 0;
        for (TileSet board : nTiles.get(tilesInPlane2)) {
            // Each board is only expanded once, but we don't keep them all around so we save a lot of memory
            for (TileSet plane2 : expand(board, primsByMainPlane)) {
                for (Map.Entry<Long, Set<TileSet>> plane0 : boards8ByAdjGaps.entrySet()) {
                    solutions += countSolutions(plane0.getKey(), plane0.getValue(), plane2, boards8ByAdjGaps);
                }
            }

            progress++;
            // Progress reports are always good for long processes...
            if (progress % 1000 == 0) System.err.println("Progress: " + progress + "; solutions: " + solutions);
        }
    }

    private static Set<TileSet> expand(TileSet board, Map<Long, Set<Long>> primsByMainPlane) {
        Set<TileSet> bexps = new HashSet<TileSet>();
        bexps.add(new TileSet());
        for (Long tileBase : board) {
            Set<TileSet> nextBexps = new HashSet<TileSet>();
            for (TileSet bexp : bexps) {
                for (Long texp : primsByMainPlane.get(tileBase)) {
                    if ((bexp.sum & texp) == 0) {
                        TileSet nextBexp = new TileSet();
                        nextBexp.addAll(bexp);
                        nextBexp.add(texp);
                        nextBexps.add(nextBexp);
                    }
                }
            }
            bexps = nextBexps;
        }
        return bexps;
    }

    private static int countSolutions(long gaps1, Set<TileSet> planes0, TileSet plane2, Map<Long, Set<TileSet>> boards8ByAdjGaps) {
        int solutions = 0;
        int fitTiles = 0;
        long unfitTiles = 0;
        for (Long tile : plane2) {
            if ((tile & adjPlane) == (tile & gaps1)) fitTiles++;
            else unfitTiles |= tile;
        }

        if (fitTiles >= tilesInPlanes2_3) {
            for (Map.Entry<Long, Set<TileSet>> planes4 : boards8ByAdjGaps.entrySet()) {
                long gaps3 = planes4.getKey();
                if ((unfitTiles & adjPlane) == (unfitTiles & gaps3)) {
                    // The Cartesian product of planes0 and planes4.getValue() are all solutions with the same
                    // plane2
                    for (TileSet plane4 : planes4.getValue()) {
                        for (TileSet plane0 : planes0) {
                            printSolutions(plane0, plane2, unfitTiles, plane4);
                            solutions++;
                        }
                    }
                }
            }
        }

        return solutions;
    }

    private static void printSolutions(TileSet plane0, TileSet plane2, long unfitTiles, TileSet plane4) {
        char[][][] cube = new char[5][5][5];
        // plane0's main plane is 0
        char tileName = 'a';
        for (Long tile : plane0) {
            populatePlane(cube[0], tile & mainPlane, tileName);
            populatePlane(cube[1], tile >> 25, tileName);
            tileName++;
        }
        for (Long tile : plane4) {
            populatePlane(cube[4], tile & mainPlane, tileName);
            populatePlane(cube[3], tile >> 25, tileName);
            tileName++;
        }
        for (Long tile : plane2) {
            populatePlane(cube[2], tile & mainPlane, tileName);
            // The tricky bit: up or down? We look to unfitTiles.
            populatePlane(cube[(unfitTiles & tile) == 0 ? 1 : 3], tile >> 25, tileName);
            tileName++;
        }

        // Print as plane0 plane1 plane2 plane3 plane4
        for (int y = 0; y < 5; y++) {
            for (int z = 0; z < 5; z++) {
                for (int x = 0; x < 5; x++) {
                    System.out.print(cube[z][y][x] == 0 ? '.' : cube[z][y][x]);
                }
                System.out.print(' ');
            }
            System.out.println();
        }
        System.out.println();
        System.out.println();
    }

    private static void populatePlane(char[][] plane, long values, char tile) {
        for (int x = 0; x < 5; x++) {
            for (int y = 0; y < 5; y++) {
                if ((values & (1 << (x + 5*y))) != 0) {
                    if (plane[y][x] != 0) throw new IllegalStateException("Collision!");
                    plane[y][x] = tile;
                }
            }
        }
    }

    static class TileSet extends HashSet<Long> {
        private long sum = 0;

        @Override
        public boolean add(Long val) {
            if ((val & sum) != 0) throw new IllegalArgumentException();
            sum |= val;
            return super.add(val);
        }
    }
}


Python 2 + sympy, 128 bytes

We locally invert the polynomial by assuming that q(x) = x, composing it with p, checking the coefficient for x2, and subtracting it from q. Let's say the coefficient was 4, then the new polynomial becomes q(x) = x - 4x2. We then again compose this with p, but look up the coefficient for x3. Etc...

from sympy import*
i=input()
p=Poly(i,var('x'));q=p*0+x
n=2
for _ in i[2:]:q-=compose(p,q).nth(n)*x**n;n+=1
print q.all_coeffs()


Find the largest root of a polynomial with a neural network

14,674,000,667 5,436,050 5,403,448 10,385 5,994 4,447  3,806 total precision

For a baseline, I investigated the following approach: Select \$M,\delta,\epsilon>0\$ such that if we sample the polynomial \$p(x)=x^3+ax^2+bx+c\$ at

$$ S:=\{-M,-M+\delta,-M+2\delta,\ldots,M\}, $$

then the largest sample point \$s^\star\in S\$ satisfying \$p(s^\star)<\epsilon\$ necessarily exists and necessarily resides within \$0.1\$ of the largest root of \$p\$. One can show that for our collection of polynomials, one may take \$M=11\$, \$\delta=0.1\$, and \$\epsilon=10^{-4}\$.

To design a neural net that implements this logic, we start with a layer of neurons that sample the polynomial on \$S\$. For each \$s\in S\$, we take

$$ x_{1,s} = s^2\cdot a + s\cdot b + 1\cdot c + s^3. $$

Next, we identify which of these are less than \$\epsilon=10^{-4}\$. It turns out that for \$s\in S\$, it holds that \$p(s)<10^{-4}\$ only if \$p(s)\leq 0\$. As such, we can use relu activations to exactly identify our samples:

$$ \frac{\mathrm{relu}(10^{-4}-t) - \mathrm{relu}(-t)}{10^{-4}} = \left\{\begin{array}{cl}1&\text{if }t\leq 0\\0&\text{if }t\geq 10^{-4}.\end{array}\right.$$

We implement this with a few layers of neurons:

$$ \begin{aligned}
x_{2,s} &= \mathrm{relu}(-1\cdot x_{1,s}+10^{-4}), \\
x_{3,s} & = \mathrm{relu}(-1\cdot x_{1,s}), \\
x_{4,s} &= 10^{4}\cdot x_{2,s}-10^{4}\cdot x_{3,s}. \end{aligned}$$

At this point, we have \$x_{4,s}=1\$ when \$p(s)<10^{-4}\$, and otherwise \$x_{4,s}=0\$. Recall that we seek the largest \$s^\star\$ for which \$x_{4,s^\star}=1\$. To this end, we label \$x_{4,M}\$ as \$x_{5,M}\$ (for notational convenience), and for each \$k\geq 1\$, we iteratively define

$$ x_{5,M-k\delta} = 1\cdot x_{4,M-k\delta}+2\cdot x_{5,M-(k-1)\delta} = \sum_{j=0}^k 2^{k-j}x_{4,M-j\delta}. $$

Thanks to this transformation, every \$x_{5,s}\$ is a nonnegative integer, and \$s^\star\$ is the unique \$s\$ for which \$x_{5,s}=1\$. We may now identify \$s^\star\$ by another application of relu activations:

$$ \mathrm{relu}(t-2)-2\cdot\mathrm{relu}(t-1)+t = \left\{\begin{array}{cl}1&\text{if }t=1\\0&\text{if }t\in\mathbf{Z}_{\geq 0}\setminus\{1\}.\end{array}\right.$$

Explicitly, we define neurons by

$$ \begin{aligned}
x_{6,s} &= \mathrm{relu}(1\cdot x_{5,s} - 2), \\
x_{7,s} &= \mathrm{relu}(1\cdot x_{5,s} - 1), \\
x_{8,s} &= 1\cdot x_{6,s} - 2\cdot x_{7,s} + 1\cdot x_{5s}.
\end{aligned} $$

Then \$x_{8,s}=1\$ if \$s=s^\star\$ and otherwise \$x_{8,s}=0\$. We linearly combine these to produce our output node:

$$ x_9 = \sum_{s\in S} s\cdot x_{8,s} = s^\star. $$

For the score, each layer has neurons with different levels of precision:
(1) \$6+3+1+9=19\$, (2) \$1+4=5\$, (3) \$1\$, (4) \$5+5=10\$, (5) \$1+1=2\$, (6) \$1+1=2\$, (7) \$1+1=2\$, (8) \$1+1+1=3\$, (9) \$3|S|\$. Furthermore, all but two of the layers have \$|S|=221\$ neurons; layer 5 has \$|S|-1\$ neurons and layer 9 has \$1\$ neuron.

Edit: Improvements: (1) We can sample the polynomial much more efficiently using finite differences. (2) We can bypass layers 2 through 4 by instead using a sigmoid activation. (3) The overflow issues in layer 5 can be averted (and subsequent layers can be combined) by more carefully applying relu activations. (4) The final sum is cheaper with summation by parts.

What follows is the MATLAB code. To be clear, prec is a function (found here) that computes the precision of a vector of weights or biases.

function sstar = findsstar2(a,b,c)

relu = @(x) x .* (x>0);

totprec = 0;

% x1 samples the polynomial on -11:0.1:11
x1=[];
for s = -11:0.1:11
    if length(x1) < 5
        w1 = [s^2 s 1];
        b1 = s^3;
        x1(end+1,:) = w1 * [a; b; c] + b1;
        totprec = totprec + prec(w1) + prec(b1);
    else
        w1 = [-1 4 -6 4];
        x1(end+1,:) = w1 * x1(end-3:end,:);
        totprec = totprec + prec(w1);
    end
end

% x4 indicates whether the polynomial is nonpositive
w4 = -6e5;
b4 = 60;
x4=[];
for ii=1:length(x1)
    x4(end+1) = sigmf(w4 * x1(ii) + b4, [1,0]);
    totprec = totprec + prec(w4) + prec(b4);
end

% x6 indicates which entries are less than or equal to sstar
x5 = zeros(size(x1));
x6 = zeros(size(x1));
x5(end) = 0;
x6(end) = 0;
for ii = 1:length(x5)-1
    w5 = [-1 -1];
    b5 = 1;
    x5(end-ii) = relu(w5 * [x4(end-ii); x6(end-ii+1)] + b5);
    totprec = totprec + prec(w5) + prec(b5);
    w6 = -1;
    b6 = 1;
    x6(end-ii) = w6 * x5(end-ii) + b6;
    totprec = totprec + prec(w6) + prec(b6);
end

% a linear combination produces sstar
w7 = 0.1*ones(1,length(x1));
w7(1) = -11;
sstar = w7 * x6;

%disp(totprec) % uncomment to display score

end


Even if you require full adherence to the ELF specification, you can squeeze it into 98 bytes:

            org     0x04B34000
            db      0x7F, "ELF", 1, 1, 1, 0 ; e_ident
            dd      0, 0
            dw      2                       ; e_type
            dw      3                       ; e_machine
            dd      1                       ; e_version
            dd      _start                  ; e_entry
            dd      phdr - $$               ; e_phoff
            dd      0                       ; e_shoff
            dd      0                       ; e_flags
            dw      0x34                    ; e_ehsize
            dw      0x20                    ; e_phentsize
phdr:       dd      1                       ; e_phnum       ; p_type
                                            ; e_shentsize
            dd      0                       ; e_shnum       ; p_offset
                                            ; e_shstrndx
            db      0                                       ; p_vaddr
_start:     inc     eax
            mov     bl, 4
            mov     dl, 12                                  ; p_paddr
            jmp     short part2
            dd      filesize                                ; p_filesz
            dd      filesize                                ; p_memsz
            dd      5                                       ; p_flags
            dd      0x1000                                  ; p_align
str:        db      'Hello world', 10
part2:      mov     ecx, str
again:      xchg    eax, ebx
            int     0x80
            jmp     short again
filesize    equ     $ - $$

Or if you prefer hex bytes:
7F 45 4C 46 01 01 01 00 00 00 00 00 00 00 00 00 02 00 03 00 01 00 00 00 35 40 B3 04 2C 00 00 00 00 00 00 00 00 00 00 00 34 00 20 00 01 00 00 00 00 00 00 00 00 40 B3 04 B2 0C EB 1C 62 00 00 00 62 00 00 00 05 00 00 00 00 10 00 00 48 65 6C 6C 6F 20 77 6F 72 6C 64 0A B9 4C 40 B3 04 93 CD 80 EB FB

The ELF specification explicitly permits different sections to overlap, so it is perfectly legal to let the program segment header table share bytes with the ELF header. Furthermore, the x86 version of the ELF standard states that the p_paddr field is ignored, as opposed to merely being unused (which typically comes with the requirement that it be set to zero. Thus it is safe to contain arbitrary bytes.

Finally, three more bytes are saved by overlapping the code with the load address.


Find the tangent of the sum of inverse tangents

Python 2, 76 72 bytes

from fractions import*
f=lambda k:Fraction(k and(k+f(k-1))/(1-k*f(k-1)))

Use the identity:

tan(A + B) = (tan(A) + tan(B)) / (1 - tan(A) * tan(B))

We have:

f(k) = 0                                    if k = 0
     = (k + f(k - 1)) / (1 - k * f(k - 1))  if k > 0

Try it online!

Thanks to Luis Mendo, save 4 bytes.


Output all the white or black squares of a chessboard

Pyth, 22 21 bytes
-1 byte by @Sp3000
fn%Chz3%sCMT2sM*<G8S8

Under the function %Chz3, dark hashes to 1, light to 0, and both to 2. If we take the parity of the sum of the ords of a chess square (that is, a1 -> [97, 33] -> (97 + 33)%2 = 0, dark squares go to 0, and light to 1. This allows us to filter by inequality.
fn%Chz3%sCMT2sM*<G8S8      implicit: z=input
               *           Cartesian product of
                <G8          first 8 letters in G (alphabet)
                   S8        with [1,...,8] implicitly stringified
             sM*<G8S8      ['a1','a2,...,'a8','b1'...'h8']
f          T               Filter that by gives truthy result to lambda T:
        sCMT                   The sum of the ords of the chars in T,
       %    2                  modulo 2
 n                            does not equal
   Chz                          ord of the first char in z,
  %   3                         modulo 3
                            Implicitly print the list.

Try it here.


JavaScript, 707 bytes (680 in web console)

javascript:(function(){l=function(s){return s.toLowerCase()};b=document.body;t=b.innerHTML;s="Actress;Actor;Daughters;Sons;Feminine;Masculine;Feminism;Masculism;Feminist;Masculist;Femininity;Masculinity;Mother;Father;Mothers;Fathers;Motherland;Fatherland;Motherhood;Fatherhood;Woman;Man;Female;Male;Females;Males;Girl;Boy;Girls;Boys;Girlfriends;Boyfriends;Grandmothers;Grandfathers;Her;His;She;He;Sister;Brother;Wives;Husbands;WomenWatch;MenWatch;Women;Men;Womensday;Mensday;Internationalwomensday;Internationalmensday;IWD;IMD";a=s.split(';');c=t.split(/\b/);d={};for(i=0;i<a.length;i+=2){x=a[i];y=a[i+1];d[x]=y;d[y]=x;d[l(x)]=l(y);d[l(y)]=l(x)}t='';for(i=0;i<c.length;++i)t+=d[c[i]]||c[i];b.innerHTML=t})()

This is a bookmarklet/favelet; set as URL of a bookmark/favorite and click to transform the loaded webpage.


Python 2, 189 186 bytes

i=65
for w in"lfa ravo harlie elta cho oxtrot olf otel ndia uliet ilo ima ike ovember scar apa uebec omeo ierra ango niform ictor hiskey ray ankee ulu".split():print'%c: %c'%(i,i)+w;i+=1

Try it online!

Previous: (this was cool, but I realised the simpler version could be made shorter by a byte)

w=''
i=65
for c in"lfAravOharliEeltAchOoxtroTolFoteLndiAulieTilOimAikEovembeRscaRapAuebeComeOierrAangOniforMictoRhiskeYraYankeEulU":
 w+=c.lower()
 if'_'>c:print'%c: %c'%(i,i)+w;w='';i+=1