JavaScript (ES6), 74 73 70 bytes

Takes input as an array of 32-bit integers. Returns a boolean.

f=([n,...a],x)=>n?[...f+''].some(_=>n&&!(x&n)&f(a,x|n,n<<=1)):!(x&-~x)

Or 66 bytes with inverted truthy/falsy values:

f=([n,...a],x)=>n?[...Array(32)].every(_=>x&n|f(a,x|n,n*=2)):x&-~x

Test cases

f=([n,...a],x)=>n?[...f+''].some(_=>n&&!(x&n)&f(a,x|n,n<<=1)):!(x&-~x)

console.log('[Truthy]')
console.log(f([0b1]))
console.log(f([0b111]))
console.log(f([0b1,0b1]))
console.log(f([0b11,0b111,0b1111]))
console.log(f([0b101,0b11,0b1]))
console.log(f([0b101,0b11,0b101]))
console.log(f([0b10001,0b11001,0b10001]))
console.log(f([0b100001,0b1001,0b1011]))
console.log(f([0b10010001,0b1001,0b1001,0b101]))
console.log(f([0b10110101,0b11001,0b100001,0b1]))
console.log(f([0b110111,0b100001,0b11,0b101]))
console.log(f([0b1001101,0b110111,0b1,0b11,0b1]))

console.log('[Falsy]')
console.log(f([0b101]))
console.log(f([0b101,0b11]))
console.log(f([0b1,0b1001]))
console.log(f([0b1011,0b1011]))
console.log(f([0b11011,0b1001101]))
console.log(f([0b1001,0b11011,0b1000001]))
console.log(f([0b1001,0b11011,0b1000001,0b10101]))

How?

f = (                       // f = recursive function taking:
  [n, ...a],                //   n = next integer, a = array of remaining integers
  x                         //   x = solution bitmask, initially undefined
) =>                        //
  n ?                       // if n is defined:
    [... f + ''].some(_ =>  //   iterate 32+ times:
      n &&                  //     if n is not zero:
        !(x & n)            //       if x and n have some bits in common,
        &                   //       force invalidation of the following result
        f(                  //       do a recursive call with:
          a,                //         the remaining integers
          x | n,            //         the updated bitmask
          n <<= 1           //         and update n for the next iteration
        )                   //       end of recursive call
    )                       //   end of some()
  :                         // else (all integers have been processed):
    !(x & -~x)              //   check that x is a continuous chunk of 1's


Jelly, 5 4 bytes
S:4‘

Try it online!
Sum, integer divide : by 4 and increment ‘.


Triangular domino tiling of an almost regular hexagon

APL (Dyalog Classic), 14 bytes

×/1+1÷1+∘,1⊥¨⍳

Try it online!

Uses 0 indexing with ⎕IO←0.

Explanation:

             ⍳     ⍝ Cartesian product of the ranges from 0 to n-1
          1⊥¨      ⍝ Sum of each element (using base 1)
         ,         ⍝ Flattened
        ∘          ⍝ Composed with
  1+1÷1+           ⍝ 1 + 1/(n+1)
×/                 ⍝ And reduced by multiplication


Proving you are the best StackExchange-User


Arbitrarily Shift Bit Array Represented As Array of 32-bit Integers

Java 306

public static int[] shiftBitArray(int[] bits, int shift) {
    BigInteger r = BigInteger.ZERO;
    for (int i = bits.length - 1; i >= 0;) r = BigInteger.valueOf(0xffffffffL & bits[i--]).or(r.shiftLeft(32));
    r = r.shiftLeft(shift);
    int[] a = new int[(int) Math.ceil(r.bitLength() / 32d)];
    for (int i = 0; i < a.length; r = r.shiftRight(32)) a[i++] = r.intValue();
    return a;
}


Find the coefficients of a rational generating function

Haskell, 63 bytes

z=0:z
(a:b)%y@(c:d)=a/c:zipWith(-)(b++z)(map(a/c*)d++z)%y
_%_=z

Try it online!

Defines an operator % returning an infinite lazy list of coefficients. The list is zero-indexed, so the constant coefficient is included.


Cycle lengths for Perfect shuffles of decks of any size

Haskell, 47 46 44 (in shuffle)
[[i|i<-[1..],mod(2^i)n<2]!!0|n<-[3,5..1001]]

the basic realization is that this is the order of 2 in the multiplicative group of modulus n+1.


Jelly, 180 174 163 bytes

60r26;“WSNME‘ȷ_Ọ;“ ¶.',!”“¢Iç÷ṀDė3H⁷'UBV“ñẸḣY]ṭżẸ-dƒjṭ{^ṣ8ḞkƊK“ẈḊbƝÑk?Æ.)Aɱ3ẎƬṠ⁵ʂ÷Gẏp⁴ṇ1ẸR ¬,F°0>ST$[?ṘȦŀẎcFẈṃijȯÆḋ“¦ḟw2ðƊhSẏ¥ẏ5ƒẉɦ⁺Ʋ⁴Ɓ¦ÞIzƥṙḊOḊ-÷~øWḤ0ṃ’ṃ€6676ḃ4¤ị

Try it online!


Get string "-" with JavaScript using only the symbols from "+[]"


Minimum number of numbers to sum to exactly n

Pyth, 12 11 bytes
lhafqsTQyEY

This takes n as the first line of input and the list on the second line.
lhafqsTQyEY     (Implicit: Q = 1st line of input; E = 2nd line)
         E      The list
        yE      Powerset (sorted by increasing length; empty set first)
   f            Filter by lambda T:
     sT         sum(T)
    q                  ==
       Q                  Q
   fqSTQyE      Sublists that sum to Q, sorted by increasing length
  a       Y     append an empty array (in case none match)
lh              take the length of the first element (0 for empty array)

Try it here.


Order a list but respect integer ordering (natural sort order)

Python 2, 68 bytes

lambda l:sorted(l,key=lambda x:int(re.sub("\D","",x)or 0))
import re

Try it online!

I used something like this to sort PDF files recently!

my entry originally didn't work but Neil fixed it (thanks!)


Map a list of indefinite size to a number!

Jelly, 18 16 bytes

List to integer, 10 8 bytes

TṪạL;³ÆẸ

Maps lists of non-negative integers to positive integers. Try it online!

Integer to list, 8 bytes

ÆE©Ḣ0ẋ®;

Maps positive integers to lists of non-negative integers . Try it online!

Background

Let p0, p1, p2, ⋯ be the sequence of prime numbers in ascending order.

For each list of non-negative integers A := [a1, ⋯, an], we map A to p0z(A)p1a1⋯pnan, where z(A) is the number of trailing zeroes of A.

Reversing the above map in straightforward. For a positive integer k, we factorize it uniquely as the product of consecutive prime powers n = p0α0p1α1⋯pnαn, where αn > 0, then reconstruct the list as [α1, ⋯, αn], appending α0 zeroes.

How it works

List to integer

TṪạL;³ÆẸ  Main link. Argument: A (list of non-negative integers)

T         Yield all indices of A that correspond to truthy (i.e., non-zero) items.
 Ṫ        Tail; select the last truthy index.
          This returns 0 if the list is empty.
   L      Yield the length of A.
  ạ       Compute the absolute difference of the last truthy index and the length.
          This yields the amount of trailing zeroes of A.
    ;³    Prepend the difference to A.
      ÆẸ  Convert the list from prime exponents to integer.

Integer to list

ÆE©Ḣ0ẋ®;  Main link. Input: k (positive integer)

ÆE        Convert k to the list of its prime exponents.
  ©       Save the list of prime exponents in the register.
   Ḣ      Head; pop the first exponent.
          If the list is empty, this yields 0.
    0ẋ    Construct a list of that many zeroes.
      ®;  Concatenate the popped list of exponents with the list of zeroes.

Example output

The first one hundred positive integers map to the following lists.

  1: []
  2: [0]
  3: [1]
  4: [0, 0]
  5: [0, 1]
  6: [1, 0]
  7: [0, 0, 1]
  8: [0, 0, 0]
  9: [2]
 10: [0, 1, 0]
 11: [0, 0, 0, 1]
 12: [1, 0, 0]
 13: [0, 0, 0, 0, 1]
 14: [0, 0, 1, 0]
 15: [1, 1]
 16: [0, 0, 0, 0]
 17: [0, 0, 0, 0, 0, 1]
 18: [2, 0]
 19: [0, 0, 0, 0, 0, 0, 1]
 20: [0, 1, 0, 0]
 21: [1, 0, 1]
 22: [0, 0, 0, 1, 0]
 23: [0, 0, 0, 0, 0, 0, 0, 1]
 24: [1, 0, 0, 0]
 25: [0, 2]
 26: [0, 0, 0, 0, 1, 0]
 27: [3]
 28: [0, 0, 1, 0, 0]
 29: [0, 0, 0, 0, 0, 0, 0, 0, 1]
 30: [1, 1, 0]
 31: [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
 32: [0, 0, 0, 0, 0]
 33: [1, 0, 0, 1]
 34: [0, 0, 0, 0, 0, 1, 0]
 35: [0, 1, 1]
 36: [2, 0, 0]
 37: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
 38: [0, 0, 0, 0, 0, 0, 1, 0]
 39: [1, 0, 0, 0, 1]
 40: [0, 1, 0, 0, 0]
 41: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
 42: [1, 0, 1, 0]
 43: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
 44: [0, 0, 0, 1, 0, 0]
 45: [2, 1]
 46: [0, 0, 0, 0, 0, 0, 0, 1, 0]
 47: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
 48: [1, 0, 0, 0, 0]
 49: [0, 0, 2]
 50: [0, 2, 0]
 51: [1, 0, 0, 0, 0, 1]
 52: [0, 0, 0, 0, 1, 0, 0]
 53: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
 54: [3, 0]
 55: [0, 1, 0, 1]
 56: [0, 0, 1, 0, 0, 0]
 57: [1, 0, 0, 0, 0, 0, 1]
 58: [0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
 59: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
 60: [1, 1, 0, 0]
 61: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
 62: [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
 63: [2, 0, 1]
 64: [0, 0, 0, 0, 0, 0]
 65: [0, 1, 0, 0, 1]
 66: [1, 0, 0, 1, 0]
 67: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
 68: [0, 0, 0, 0, 0, 1, 0, 0]
 69: [1, 0, 0, 0, 0, 0, 0, 1]
 70: [0, 1, 1, 0]
 71: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
 72: [2, 0, 0, 0]
 73: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
 74: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
 75: [1, 2]
 76: [0, 0, 0, 0, 0, 0, 1, 0, 0]
 77: [0, 0, 1, 1]
 78: [1, 0, 0, 0, 1, 0]
 79: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
 80: [0, 1, 0, 0, 0, 0]
 81: [4]
 82: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
 83: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
 84: [1, 0, 1, 0, 0]
 85: [0, 1, 0, 0, 0, 1]
 86: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
 87: [1, 0, 0, 0, 0, 0, 0, 0, 1]
 88: [0, 0, 0, 1, 0, 0, 0]
 89: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
 90: [2, 1, 0]
 91: [0, 0, 1, 0, 1]
 92: [0, 0, 0, 0, 0, 0, 0, 1, 0, 0]
 93: [1, 0, 0, 0, 0, 0, 0, 0, 0, 1]
 94: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0]
 95: [0, 1, 0, 0, 0, 0, 1]
 96: [1, 0, 0, 0, 0, 0]
 97: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1]
 98: [0, 0, 2, 0]
 99: [2, 0, 0, 1]
100: [0, 2, 0, 0]


Average number of strings with Levenshtein distance up to 4


Python 2, 13 bytes
Takes a positive integer \$ n \$ as input and returns the \$ n \$th term of the sequence.

lambda n:n&-n

Try it online!
The largest power of \$ 2 \$ that divides \$ n \$ is also the lowest set bit. The bitwise magic is a bit difficult to explain, but it uses the fact that ~n + 1 in its binary representation produces the same lowest set bit as n.
Python 2, 26 bytes
Outputs the sequence infinitely.

n=1
while 1:print-n&n;n+=1

Try it online!
Python 2, 33 bytes
Takes a positive integer \$ n \$ as input and returns the first \$ n \$ terms of the sequence.

f=lambda n:n*[0]and f(n-1)+[n&-n]

Try it online!


Whitespace/Brainfuck/Python

'''begin''''''''''''
main(args){
	parseArgs=args.Find('^++++++++^[<++++[<++<+++<+++<+>>>>a-z]<+<+<A-Z[>]>0-9]<<.<---.*$');
    for(int i=0;	Range(GetLength(parseArgs));	i++){validateArg(parseArgs(i));}
	//name
    string stockName="";
	//loop
    for(int i=0;Range(GetLength(parseArgs));i++){
	//validate
     	if(matchFound=Find('a+z+A+.Z.0+9+_+.<<*$'){
	//found
     	parseArgs(i).Split('>-.>.+');}

     	for(int j=0;Range(GetLength(parseArgs(i)));j++){
	//download
    data=ConvertTo.String(eval("curl -get	http://some-stock-ticker-source-url-here.com"));
	print;
    print data;

    //line separator

    print "--------.";
	}}
}

''finish'''''''''''''''

Wikipedia: Whitespace (programming language)
Online Whitespace Interpreter to Test Answer
Online Brainfuck Interpreter to Test Answer

   Output (Whitespace/Brainfuck):
 Hello World

 Ouput (Python):
 Nothing, but runs successfully.


Is this a valid game of Five Up (Dominoes)?

Haskell, 188 174 168 bytes

f(p:r)=[p]!r$p?p
(s!(p:r))o|b<-[p,reverse p]=or[(q:s)!r$q%o|q<-b,elem(q!!0)o,all(`notElem`s)b]
(s!_)o=1<3
p@[x,y]?r=[c|x==y,c<-p]++r
p@[x,y]%(a:r)|a/=x=a:p%r|z<-y:r=p?z

Try it online! Usage example: f [[6,6],[6,5],[5,3],[3,0]] yields True.
Ungolfed:

f :: [[Int]] -> Bool
f (p:r) = check [p] (double p p) r

check :: [[Int]] -> [Int] -> [[Int]] -> Bool
check seen open [] = True
check seen open ([x,y]:r) =
	  notElem [x,y] seen
   && notElem [y,x] seen
   && (elem x open && check ([x,y]:seen) (update [x,y] open) r
   ||  elem y open && check ([y,x]:seen) (update [y,x] open) r)

double :: [Int] -> [Int] -> [Int]
double [x,y] rest =
    if x==y
    then [x,y] ++ rest
    else rest

update :: [Int] -> [Int] -> [Int]
update [x,y] (a:rest) =
    if x==a
    then double [x,y] (y:rest)
    else a : update [x,y] rest

Try it online!


Deletion of a blank line in source code which causes unexpected functionality

Javascript

Opens an alert popup with "Hello, World!" if the blank line exists, otherwise alerts "0".

(function(){
    alert(~(arguments.callee+[]).indexOf('\n\n') && "Hello, World!");

})();

Demo

Explanation:

arguments.callee is a reference to the self-executing anonymous function.

Appending a blank array ([]) casts the function to a string, which gives you its source code.

indexOf returns -1 if the string is not found.

Performing a bitwise not operation (~) results in -1 being turned into 0, which is a falsey value.


Ruby, 114 bytes

->h,g=[0]*792{h.chunk{|x|x<0&&p}.map{|z,(x,y,*r)|g[36*y+x,r.size]=r}
puts'P3 36 22 5',g.map{|i|i>3?'5 0 0':[i]*3}}

This function takes its input as an array of ints, and writes the resulting image to STDOUT in the human readable version of PPM format. For those unfamiliar, the PPM image format is an uncompressed image format that's, essentially, a whitespace separated list of RGB values.

About PPM

More particularly, it begins with a short header of the format P3 W H M, where P3 is a magic number, W is the width of the image, H is the height of the image, and M is an int from 1 to 65536 representing the maximum possible value a color channel can have. For instance, if M = 255, then the RGB triplet (255, 255, 255) represents white. If M = 10, then (10, 10, 10) is white.

After the header, each pixel is described, row by row, by providing an RGB triplet for its color, with each value separated by spaces. It has the neat property that you can use it to represent an image as human readable text. For instance, a 3x1 pixel image containing a red pixel, a green pixel, and a blue pixel would be:

3 1 255
255 0 0   0 255 0   0 0 255

The precise whitespace used doesn't matter, so the above image is equivalent to, among many others:

3 1 255
255
 0    0          0       255        0
        0     0       255

Explanation of Code

The reason all that was necessary was to explain why, when you run the program, you'll see output that looks like this:

P3 36 22 5
0
0
0
3
0 # And so on...

It's a PPM! And it's generated like this:

# Create an array g, full of 0s, of size (36*22) to hold the image
g = [0] * 792
# Break the input array into chunks, splitting on values < 0
h.chunk{|x|x < 0 && p}
# Use each chunk to fill the subarray of g beginning at its x and y coordinates
 .map{|z,(x,y,*r)|g[36*y+x,r.size]=r}
# Print the header ...
puts'P3 36 22 5',
# ... and the colors, replacing each color id with itself repeated 3 times
# (for the various shades of gray) or '5 0 0', in the case of red, and
# separating each item with a newline.
g.map{|i|i>3?'5 0 0':[i]*3}

If you take this output and paste it into a text file, you'll be able to view it in any image viewer capable of opening PPMs.

Try it online!


score = 82 71 69 (34 ‘1’s + 23 ‘+’s + 12 parenthesis pairs)

$$\begin{multline*}
11111111111 = 1 + (1 + 1) \cdot {}
\\
(1 + 1 + 1 + (1 + 1)^{(1 + 1)^{1 + 1 + 1}}(1 + ((1 + 1)(1 + 1 + 1))^{1 + 1 + 1})) \cdot {}
\\
(1 + (1 + (1 + 1 + 1)^{1 + 1})^{1 + (1 + 1)^{1 + 1}})
\end{multline*}$$

Try it online!

Search program in Rust

This finds optimal solutions for up to about 8 digit numbers.  Don’t try it on anything larger—it will eat all your memory.

I constructed the above solution by manually writing \$11111111111 = 1 + 111110 \cdot 100001\$ and searching for optimal solutions to \$111110\$ and \$100001\$.

use std::env;

#[derive(Clone, Debug)]
enum Op {
    One,
    Add(u32, u32),
    Mul(u32, u32),
    Pow(u32, u32),
}

fn show(ops: &[Option<Op>], z: u32, prec: u32) {
    match ops[z as usize].as_ref().unwrap() {
        Op::One => print!("1"),
        Op::Add(x, y) => {
            if prec > 0 {
                print!("(");
            }
            show(ops, *x, 0);
            print!(" + ");
            show(ops, *y, 0);
            if prec > 0 {
                print!(")");
            }
        }
        Op::Mul(x, y) => {
            if prec > 1 {
                print!("(");
            }
            show(ops, *x, 1);
            show(ops, *y, 1);
            if prec > 1 {
                print!(")");
            }
        }
        Op::Pow(x, y) => {
            if prec > 2 {
                print!("(");
            }
            show(ops, *x, 3);
            print!("^{{");
            show(ops, *y, 0);
            print!("}}");
            if prec > 2 {
                print!(")");
            }
        }
    }
}

fn main() {
    for target in env::args().skip(1).map(|arg| arg.parse().unwrap()) {
        let mut ops: Vec<Option<Op>> = vec![None; target as usize + 1];
        let mut vs: Vec<Vec<u32>> = vec![];
        while !ops[target as usize].is_some() {
            let mut v: Vec<u32> = vec![];
            let mut visit = |x, op| {
                if let Some(x) = x {
                    if x <= target {
                        if ops[x as usize].is_none() {
                            ops[x as usize] = Some(op);
                            v.push(x);
                        }
                    }
                }
            };
            let level = vs.len();
            let score = level / 2;
            match level % 2 {
                0 => {
                    if score == 1 {
                        visit(Some(1), Op::One);
                    }
                    for i in 1..score.saturating_sub(1) {
                        let j = score - 1 - i;
                        for u in &vs[i * 2..i * 2 + 2] {
                            for v in &vs[j * 2..j * 2 + 2] {
                                for &x in u {
                                    for &y in v {
                                        visit(x.checked_pow(y), Op::Pow(x, y));
                                    }
                                }
                            }
                        }
                    }
                    for i in 1..score {
                        let j = score - i;
                        for u in &vs[i * 2 - 1..i * 2 + 1] {
                            for v in &vs[j * 2 - 2..j * 2 + 1] {
                                for &x in u {
                                    for &y in v {
                                        visit(x.checked_mul(y), Op::Mul(x, y));
                                    }
                                }
                            }
                        }
                    }
                }
                1 => {
                    for i in 1..score.saturating_sub(1) {
                        let j = score - 1 - i;
                        for u in &vs[i * 2..i * 2 + 2] {
                            for v in &vs[j * 2..j * 2 + 2] {
                                for &x in u {
                                    for &y in v {
                                        visit(x.checked_add(y), Op::Add(x, y));
                                    }
                                }
                            }
                        }
                    }
                }
                _ => unreachable!(),
            }
            vs.push(v);
        }
        print!("{} = ", target);
        show(&ops, target, 0);
        println!();
    }
}

Try it online!


using a Markov Chain, because this question itself as input text for example

Perl, 108 chars
What, no answers?  Here's a quick Perl solution:
$/=$,;$_=<>;push@$1,$2while/(?=(....)(.))/sg;print+($m)=/(....)/s;print while($m.=($_=$$m[rand@$m]))=~s/.//s

And this is what I got the first time I fed the question text through it:

Create a defined. There must also inclined. There must be sure to be according a Markov Chain.

(The average output length should approximately match the input length, so such a short output is quite untypical.  On the other hand, the output length is roughly exponentially distributed, so both very short and very long outputs are quite possible.)


Husk, 7 6 5 bytes
Saved 2 bytes thanks to @Zgarb
▼▲‡¦P

Takes argents in reverse order and returns 1 for True and 0 for False.
Try it online!
Explanation
    P     -- Permutations of the first argument
  ‡       -- Deep zip (vectorises function) with second argument
   ¦      --   Does x divide y
 ▲        -- Get the maximum of that list, returns [1,1...1] if present
▼         -- Get the minimum of that list, will return 0 unless the list is all 1s


Perfect scores in Martian rules football

05AB1E, 10 bytes
>PLãʒ*OyPQ

Try it online or verify all test cases.
Explanation:

>           # Increase both values in the (implicit) input-pair by 1
 P          # And take the product of those
  L         # Pop and push a list in the range [1, (G+1)*(B+1)]
   ã        # Create all possible pairs by taking the cartesian product with itself
    ʒ       # Filter those pairs [g,b] by:
     *      #  Multiply it with the (implicit) input-pair at the same positions:
            #   [G,B] * [g,b] will result in [Gg,Bb]
      O     #  Sum those: Gg+Bb
       yP   #  Take the product of the current pair: gb
         Q  #  And check that both values are the same: Gg+Bb == gb
            # (after which the result is output implicitly)

The last test case no longer times out by using an upper bound of \$(G+1)\times(B+1)\$ instead of my initial \$(2^G+2^B)\$ (byte count remains the same). Make sure to upvote @SurculoseSputum's Python answer for providing this mathematical upper bound.


Haystack, 84 bytes, Cracked

0\\1-c\
//
?10F17+c8F+4+cd8F+3+c6-c1+c,c2+c8+c|
 0   \1++c,c|
F/c++2F8
c\8F+2+cd

Try it online!

This looks (to me) rather convoluted but if you find the right subset it's a bit too easy... oh well, just to get us started :P


Python - Bytes: 4411, False +ves: 0, False -ves: 0 = Score: 4411

import base64,zlib,sys;T=eval(zlib.decompress(base64.b64decode("[encoded data, 4228 characters]")));t=T;f=1
for c in sys.argv[1]:
 C=c.lower()
 if c in t:t=t[c]
 elif f and C in t:f=0;t=t[C]
 else:t={}
print""in t

This is a python program that expects one command line argument, the word. From the list of words I constructed a trie, zlib'ed the argument and finally encoded it with base64. If the word is in the trie, the program prints True, otherwise it prints False. I wanted to create a spell checker that has 100% accuracy.

I could substantially decrease the number of characters, by not encoding the zlib'ed string (specifically, zlib'ed string is 1113 characters shorter than base 64 encoded), but I wanted to have a code that you can copy/paste directly.

Examples

$python check.py colour
True

$python check.py Colour
True

$python check.py coLoUr
False

$python check.py color
False

$python check.py Color
False

$python check.py I
True

$python check.py i
False

The trie is traversed with characters of the word, each time getting a new trie from the key of current character. If the word is in the trie, then a "" must be present in the final trie.

Ungolfed version

import base64, zlib, sys

TRIE = eval(zlib.decompress(base64.b64decode("[encoded data, 4228 characters]")))

trie = TRIE
first = True
for character in sys.argv[1]:
    CHARACTER = character.lower()
    if character in trie:
        trie = trie[character]
    elif first and CHARACTER in trie:
        first = False
        trie = trie[CHARACTER]
    else:
        print False
if "" not in trie:
    print False
print True

Construction of base 64 encoded, zlib'ed trie

f = file("dictionary","r")
END = ""
TRIE = {}

def addWord(word):
    trie = TRIE
    for character in word:
        trie = trie.setdefault(character, {})
    trie.setdefault(END, 0)

for line in f.readlines():
    l = line.replace("\n", "")
    addWord(l)

import zlib, base64
compressed = zlib.compress(str(TRIE).replace(" ", ""), 9)
print base64.b64encode(compressed)


Wumpus, 6 bytes

{~)
@O

Try it online!
Try it doubled!
Try it tripled!

Prints 1 and 3.

Explanation

I found a ton of 6-byte solutions by brute force search, but none for 5 bytes. That doesn't necessarily mean there aren't any at 5 bytes but they'd probably use weird characters or something.

I ended up picking this solution because it doesn't print any leading zeros (most of them do) and it has some interesting control flow. Let's start with the single program:

So the executed code is:

{~)O@

{   Turn the IP left by 60°.
~   Swap two implicit zeros on the stack, does nothing.
)   Increment the top zero to 1.
O   Print it.
@   Terminate the program.

Easy enough. Now the doubled program. Since the first line gets appended onto the second line, the grid extends to width 5 (and height 3) which changes the control flow significantly:

The IP goes around that loop exactly once, so the executed code is:

{~){~)){~O@

{~) As before, we end up with a 1 on top of the stack.
{   Turn left by 60° again.
~   Swap the 1 with the 0 underneath.
))  Increment the zero to 2.
{   Turn left by 60° again.
~   Swap the 2 with the 1 underneath.
O   Print the 1.
@   Terminate the program.

Finally, the tripled program is quite similar to the doubled one, but we get a couple more important commands onto that third line:

So the executed code is:

{~){~)){~~)O@

{~){~)){~
    As before. We end up with a 1 on top of the stack and a 2 underneath.
~   Swap the 1 with the 2 underneath.
)   Increment the 2 to a 3.
O   Print the 3.
@   Terminate the program.


JavaScript (ES6), 26 bytes
Takes input in little Endian.

n=>'0958634172'[n*3%77%10]

Try it online!


MATL, 6 bytes
"@N$Yd

Works in current version (13.0.0) of the language/compiler.
Input has the following form, with semicolon as row separator, and commas or spaces as column separators within each row:
[1, 2, 3; 4, 5, 6]

Try it online!
Explanation
"         % implicitly input 2D array and loop over its columns
  @       %   push column
  N$Yd    %   build block-diagonal matrix from all stack contents. Stack contents are
          %   a single column in the first iteration, or a partially built 2D array
          %   and a new column in all other iterations
          % end loop
          % implicit display

Worked example
Consider the input [1 2 3; 4 5 6]. The for loop beginning with " takes each column of the input. Within each iteration, @ pushes the current column onto the stack. So in the first iteration it pushes [1; 4]. N$ specifies that all the stack contents will be used as inputs of the following function, Yd.
This function (corresponding to MATLAB's blkdiag) "diagonally concatenates" its inputs to produce a block diagonal matrix (2D array). So in the first iteration Yd it takes one input and produces an output equal to that input, [1; 4], which is left on the stack.
In the second iteration the second column of the input, [2; 5], is pushed. Now Yd takes two 2×1 inputs, namely [1; 4] and [2; 5], and produces the 4×2 array [1 0; 4 0; 0 2; 0 5].
In the third iteration Yd takes the latter 4×2 array and the third column of the input, [3; 6], and produces the final result [1 0 0; 4 0 0; 0 2 0; 0 5 0; 0 0 3; 0 0 6].


Assembly (bootloader) 131 chars / 512 bytes compiled (actually smaller, but bootsector must be 512 bytes long.)

It is a simple boot loader. When computer starts, BIOS will load it from disk (floppy). Then it enters into graphics mode and just hangs. When user presses the power button, program will end and computer will enter to mode where is was before running program.

Tested with VirtualBox.

It will compile with nasm:

nasm -f bin file.asm -o start.img

Source code:

[BITS 16]
[ORG 0x7C00]
cli
mov AX,0x0
mov SS,AX
mov SP,0x9000
sti
mov AH,0x0
mov AL,0x13
int 0x10
times 510 - ($-$$) db 0
dw 0xAA55


MATL, 8 bytes

1)GdShYs

Try it online!

1)   % Implicit input. Get its first entry
G    % Push input again
d    % Differences
S    % Sort
h    % Concatenate
Ys   % Cumulative sum. Implicit display


Convert a decimal integer to binary only using arithmetic operators

Python 2, 30 bytes

f=lambda n:n and n%2+10*f(n/2)

Try it online!


Khinchin's constant to as many decimal places as possible in 64 bytes or less

CJam - 118

2'."*;TeT?_aN{.i9B*ZEay
G`9~eW}nE=Lr-`B}    )D>9m9"136b

Try it at http://cjam.aditsu.net/

Since stackexchange destroys some of the characters, here's a program that generates the program above; run it first, then run its output:

"2'.\""685452001065306445309714835481795693820382293994462953051152345557218859537152002801141174931847697995153465905288090 136b:c"\"136b"

Explanation:

2 pushes 2
'. pushes the dot
"…" is a string containing the rest of the digits in encoded form
128b converts the string to a number, treating the characters as digits in base 128 (via their ASCII code)


Haskell, 37 36 bytes

f v|g<-reverse.snd.span(`elem`v)=g.g

Try it online!

-1 byte thanks to xnor.

How?
f v                     -- define a function f that takes as input a list v of falsey values
  |g<-                  --   inside the definition, define a new function g that...
    reverse             --     reverses...
    .snd                --     the second element of...
    .span               --     a tuple (say (x,y)) where x is the longest prefix of elements that...
      (`elem`v)         --       belong to v...
                        --     and y is the rest of the list
  =g.g                  --   f is defined as the composition g.g (basically apply g twice)


Graphical, networked, two-(human)-player Tic-Tac-Toe

PHP, work in progress (474 chars / 2 upvotes = 237 score)

It's fully functional except it doesn't have win detection yet.

What I really like about this solution is that I only learned PHP about 3 days ago, so the code is probably terrible. :D

t.php, 474 chars (newlines can be removed and are there only for readability):

<?php
$f=file("a");$p=$_GET["p"];if($p!="x"&&$p!="o")die();
if(isset($_GET["m"])){$s=$f[0];$s[intval($_GET["m"])]=$p;fwrite(fopen('a','w'),$s.($f[1]=='x'?'o':'x'));echo"back";}
else{$i=0;while($i<9){$s=($p==$f[1]&&$f[0][$i]=='.')?'a':'div';echo"<$s href='t.php?p=$p&m=$i'>".$f[0][$i++]."</$s>";}echo $f[1]."'s turn";}
?>

reset.php, 57 chars

<?php fwrite(fopen('a','w'),"..........\nx");?>Reset done

It's live on my website. Player X should go to this URL:

http://keyboardfire.com/misc/tictactoegolf/t.php?p=x

And Player O should go here:

http://keyboardfire.com/misc/tictactoegolf/t.php?p=o

(don't worry, I added a check that only lets player "o" or "x" in so that you can't do any fancy XSS stuff :P)

To reset, go here:

http://keyboardfire.com/misc/tictactoegolf/reset.php

Obviously, it's really easy to cheat (moving for the other player, randomly resetting the board, etc.), but it's code golf so it doesn't matter :P


Check printer - Convert to English text from the input value.

Common Lisp, 95

Newline not counted in:
(lambda(n &aux(d(floor n))(c(round(*(- n d)100))))
(format()"~R dollar~P and ~R cent~P"d d c c))

Sample use (assigning it to f):
CL-USER> (f .01)
"zero dollars and one cent"
CL-USER> (f 12.34)
"twelve dollars and thirty-four cents"
CL-USER> (f 9999.99)
"nine thousand nine hundred ninety-nine dollars and ninety-nine cents"


Area-based algorithm, \$O(k^2+n\log(k))\$
Our general strategy is to instead select points (outside the sticker rectangles) from the square (-1,-1) to (1,1), then repeat if we don't get a point within the circle. On average, we will have to select \$\frac{4}{\pi}\$ points from the square for each point in the circle.
The runtime is not depend on rectangle coverage, but it does depend on measures of rectangle intersection (denoted L in the complexity analysis in the code). For the listed complexity, I use \$L=O(k)\$, which is probably not tight. If \$L=O(\log(k))\$ can be proven, then the complexity is \$O((k+n)\log(k))\$ (see get_heights for an algorithmic alternative).
Define "open area" to be the area that points could be generated in. Recall that we are using a square instead of a circle, so the total area is piece-wise linear in x.

Precompute the total open height function \$h(x)\$ (this is piece-wise constant, so store the change at each transition: either the start or end of a new rectangle). Similarly, pre-compute the cumulative areas \$\int_{-1}^{x} h(x)\$, which is piece-wise linear, so once again store the value at each transition. This can be done in \$O(k \log(k))\$ time

Precompute the intervals on which y coordinates can be distributed for a given x (again, only storing this interval on each transition). This might be able to be done in \$O(k \log(k))\$, but this algorithm only succeeds at \$O(k^2)\$ time

Generate points. For each point: (average \$\frac{4}{\pi} n\$ times for a total runtime of \$O(n\log(k))\$
a. Choose a random value \$r\$ for the area (\$O(1)\$)
b. Find \$x\$ such that \$\int_{-1}^{x} h(t) dt = r\$. This is accomplished through binary search on the pre-computed heights \$h\$ and cumulative areas \$\int h\$, so this is done in \$O(\log(k))\$ time
c. Choose a random value \$y\$ for the given x such that (x,y) is in an open area. Through similar binary search as 3b, this is done in \$O(\log(k))\$ time
d. Reject the point if it is outside the circle (constant factor 4/pi)

The total runtime is \$O(k\log(k)) + O(k^2) + O(n\log(k)) = O(k^2+n\log(k))\$
In the following example images, I used the same n=10000, so more rectangle coverage meant a higher density of points.

Full python code below, including matplotlib display:
import math
import random
# for binary search
import bisect
# matplotlib for plotting the output points
import matplotlib.pyplot as plt
import matplotlib

def find_le(ls, x):
    # find_le is O(log(|ls|))
    # Find rightmost value less than or equal to x in ls
    i = bisect.bisect_right(ls, x)
    return i-1, ls[i-1]

class Interval:
    def __init__(self, lo, hi):
        # each range is tuple (lo, hi)
        # ranges shall be sorted in ascending order
        # each range does not overlap with other ranges
        self.ranges = [(lo, hi)]

    def remove(self, lo, hi):
        new_ranges = []
        for self_range in self.ranges:
            if lo <= self_range[0] <= hi < self_range[1]:
                new_ranges.append((hi, self_range[1]))
            elif self_range[0] < lo <= self_range[1] <= hi:
                new_ranges.append((self_range[0], lo))
            elif self_range[0] < lo < hi < self_range[1]:
                new_ranges.append((self_range[0], lo))
                new_ranges.append((hi, self_range[1]))
            elif lo <= self_range[0] < self_range[1] <= hi:
                pass
            elif hi <= self_range[0] or self_range[1] <= lo:
                # no overlap
                new_ranges.append(self_range)
        self.ranges = new_ranges

    def cache_lengths(self):
        # If L is the number of subintervals of this Interval
        # then cache_lengths is O(L) ⊂ O(k)

        # in cum_lengths, (0.6, 0.7) means that the total length to the
        # left of x=0.7 in this interval is 0.6
        self.cum_lengths = [(0, -1)]
        last_length = 0
        for self_range in self.ranges:
            length = self_range[1] - self_range[0]
            self.cum_lengths.append((last_length, self_range[0]))
            last_length += length
        self.total_length = last_length

    def random_point(self):
        # If L is the number of subintervals of this Interval
        # then random_point is O(log(L)) ⊂ O(log(k))
        r = random.random()*self.total_length
        # This find_le is O(log(L))
        i, (length_left, x_left) = find_le(self.cum_lengths, (r,))
        return (r - length_left) + x_left

    def __repr__(self):
        return "I" + str(self.ranges)

def interval_complement(rects):
    # O(L) where L is the length of rects list
    interval = Interval(-1, 1)
    for rect in rects:
        interval.remove(rect.bottom, rect.top)
    return interval

class Rect:
    def __init__(self, left, right, bottom, top):
        self.left = min(left, right)
        self.right = max(left, right)
        self.bottom = min(bottom, top)
        self.top = max(bottom, top)
        self.width = self.right - self.left
        self.height = self.top - self.bottom

    def __repr__(self):
        return f"Rect({self.left}, {self.right}, {self.bottom}, {self.top})"

    def overlap(self, others):
        # returns vertical (y) overlap between self and other rects
        total_overlap = 0
        # https://pyinterval.readthedocs.io/en/latest/guide.html#operations is
        # looking so tempting right now, but unions/merges would
        # require Principle Inclusion-Exclusion which can be k^2 worst case
        starts = sorted(others, key=lambda rect: rect.bottom, reverse=True)
        ends = sorted(others, key=lambda rect: rect.top, reverse=True)
        active_rects = set()
        overlap_start = self.bottom
        while ends:
            if starts and starts[-1].bottom < ends[-1].top:
                active_rect = starts.pop()
                if not active_rects and active_rect.bottom > self.bottom:
                    # This is the start of an overlap interval
                    overlap_start = active_rect.bottom
                active_rects.add(active_rect)
            else:
                active_rect = ends.pop()
                active_rects.remove(active_rect)

                if not active_rects:
                    # This is the end of an overlap interval
                    # Rare cases of negative = started and ended below start of self
                    total_overlap += max(0, min(active_rect.top, self.top) - overlap_start)
        return total_overlap

    def as_matplotlib_rect(self):
        return matplotlib.patches.Rectangle((self.left, self.bottom), self.width, self.height)

def get_heights(rects):
    # get_heights is O(k log(k)) total
    # Sorting: O(k log(k))
    # Use these lists as a queue
    starts = sorted(rects, key=lambda rect: rect.left, reverse=True)
    ends = sorted(rects, key=lambda rect: rect.right, reverse=True)
    # list of tuples (open height starting at x, x, open intervals starting at x)
    heights = [(2, -1, Interval(-1,1))]
    active_rects = set()
    while ends:
        # inner loop performed once for k left edges and k right edges,
        # so this is O(k)
        if starts and starts[-1].left < ends[-1].right:
            # next x-pos is the start of a new rect
            rect = starts.pop()
            height_diff = rect.height - rect.overlap(active_rects)
            height = heights[-1][0] - height_diff
            active_rects.add(rect)
            # interval_complement is O(L) so this is O(k^2), not sure if it is O(k log(k))
            heights.append((height, rect.left, interval_complement(active_rects)))
        else:
            # next x-pos is the end of an old rect
            rect = ends.pop()
            active_rects.remove(rect)
            # rect.overlap is O(L) as well
            height_diff = rect.height - rect.overlap(active_rects)
            # Two choices to get O(k log(k)):
               # 1. prove that |active_rects| is O(log(k)) under the given approaches
               # 2. avoid using interval_complement on each transition using some increments approach, and avoid doing rect.overlap on each transition
            height = heights[-1][0] + height_diff
            heights.append((height, rect.right, interval_complement(active_rects)))
    heights.append((2, 1, Interval(-1,1)))
    # cum_areas is the cumulative areas from -1 to x (of not rects)
    # Not subtracting curve because we will be sampling from square
    cum_areas = [(0, -1, Interval(-1, 1))]
    last_height = 2
    for height, x, interval in heights[1:]:
        last_area, last_x, _ = cum_areas[-1]
        new_area = (x-last_x)*last_height
        cum_areas.append((last_area + new_area, x, interval))
        last_height = height
    return (heights, cum_areas)

def random_pick_points(rects, num_points):
    # random_pick_points is O((n+k) log(k))
    # Step 1. Precompute heights: O(k log (k))
    heights, cum_areas = get_heights(rects)
    total_area = cum_areas[-1][0]
    points = []
    # Step 2. Precompute vertical intervals: O(k)
    for _, _, y_interval in cum_areas:
        y_interval.cache_lengths()
    # Step 3. Sample points outside rects and within circle
    # Total time complexity of this loop is O(n log(k))
    while len(points) < num_points:
        # This loop is reached average (4/pi)*n = O(n) times
        # Each occurence has complexity O(log(k))
        # Step 3a. Choose a random area value
        area = random.random()*total_area
        # Step 3b. Choose the x value such that area is the total area
        # outside rects and within 2x2 square to the left of x
        # There are 2k+1 total cum_areas so this find_le is O(log(k))
        i, (area_left, x_left, y_interval) = find_le(cum_areas, (area,))
        height, _, _ = heights[i]
        x = x_left + (area - area_left) / height
        # Step 3c. Choose a y value uniformly in the open spaces of that x value
        # Interval.random_point() is O(log(k))
        y = y_interval.random_point()
        # Step 3d. Rejection sample until points are inside the circle
        # On average, takes constant 4/pi random points to land within the circle
        if x*x + y*y < 1:
            points.append((x, y))
    # Done!
    return points

def display_points(rects, points):
    fig, ax = plt.subplots(1)
    ax.plot(*zip(*points), 'ko', markersize=1, alpha=0.5)
    ax.axis([-1, 1, -1, 1])
    ax.add_collection(
        matplotlib.collections.PatchCollection(
            [rect.as_matplotlib_rect() for rect in rects],
            facecolor = 'r', edgecolor='None', alpha=0.5
        )
    )
    plt.show()

def display_random_points(rects, num_points):
    points = random_pick_points(rects, num_points)
    display_points(rects, points)

def random_rects(k):
    return [Rect(*[random.random()*2-1 for _ in range(4)]) for i in range(k)]

k = 20
# rects = random_rects(k)
# print("Rects:", rects)
n = 10000
# print("Points:", random_pick_points(rects, n))
display_random_points(random_rects(k), n)

Try it online I guess, if you can read a list of points.


Well that's odd... no wait, that's even!

CJam, 18 17 13 bytes

Thanks to aditsu for saving 4 bytes.

qW:O%eu~"eo"=

Try the test suite here. (The test suite is too long for the permalink. Just copy them from the challenge spec.)

Explanation

q     e# Read the input.
W:O   e# Push a -1 and store it in variable O.
%     e# Use the -1 to reverse the string, because CJam's stack-based nature and the
      e# commutativity of the operators means we can evaluate the code in postfix notation.
eu    e# Convert the string to upper case, turning 'e' into 'E' (a variable with even value
      e# 14) and 'o' into 'O' (which we've stored the odd value -1 in).
~     e# Evaluate the string as CJam code, leaving the result on the stack.
"eo"= e# Use the result as an index into the string "eo". CJam's indexing is cyclic so it
      e# automatically takes inputs modulo 2. Negative indices also work as expected.


Given a grid, starting at the center and spiraling out, and an Position what is the ID?

JavaScript (ES6), 64 bytes
Takes input in currying syntax (x)(y).
x=>y=>(d=(A=Math.abs)(A(x)-A(y))+A(x)+A(y))*d+(d-x+y)*(-y>x||-1)

Try it online!
Heavily inspired by this answer from math.stackexchange.com.


Mathematica 25 Bytes

1/2+JacobiSymbol[-1,#]/2&

Other ways of doing this:

56 bytes

(v:=1-IntegerDigits[#,2,i][[1]];For[i=1,v>0,i++];i++;v)&

58 bytes

1-Nest[Join[#,{0},Reverse[1-#]]&,{0},Floor@Log[2,#]][[#]]&


Jelly, 21 19 bytes

-;,N$ṁx"RFḣNṙ-+\ỤŒ¿

Try it online!

Based on the method from a J article on volutes.

Explanation

-;,N$ṁx"RFḣNṙ-+\ỤŒ¿  Main link. Input: integer n
-;                   Prepend -1. [-1, n]
  ,N$                Pair with its negated value. [[-1, n], [1, -n]]
     ṁ               Mold it to length n.
        R            Range. [1, 2, ..., n]
      x"             Vectorized copy each value that many times.
         F           Flatten
           N         Negate n
          ḣ          Head. Select all but the last n values.
            ṙ-       Rotate left by -1 (right by 1).
              +\     Cumulative sum.
                Ụ    Grade up.
                 Œ¿  Permutation index.


Write A Program That Outputs Its Mirror Level

GolfScript, 10 bytes

!:{)::(}:!

Try it online with Web Golfscript: N = 0, N = 1, N = 2, N = 3, N = 41

Web GolfScript has a 1024 character limit, but the Ruby interpreter handles N = 32767 perfectly:

$ curl -Ss http://www.golfscript.com/golfscript/golfscript.rb > golfscript.rb
$ echo '"!:{):"32768*":(}:!"32768*' | ruby golfscript.rb > mirror-level-32767.gs
$ ruby golfscript.rb mirror-level-32767.gs
32768

How it works

Without any input, GolfScript initially has an empty string on the stack.

In the first left half, the following happens:

! applies logical NOT to the empty string. This pushes 1.
:{ saves the integer on the stack in the variable {.

Yes, that is a valid identifier, although there's no way to retrieve the stored value.
) increments the integer on the stack.
: is an incomplete instruction.

The the subsequent left halves, the following happens:

:! (where : is a leftover from before) saves the integer on the stack in the variable !.

Yes, that is also a valid identifier. This breaks the ! command, but we don't use it anymore.
:{, ) and : work as before.

In the first right half, the following happens:

:: (where : is a leftover from before) saves the integer on the stack in the variable :.

Yes, even that is valid identifier. As with {, there's no way to retrieve the stored value.
( decrements the integer on the stack, yielding the number of left halves.
}, since it is unmatched and terminates execution immediately.

This is an undocumented feature. I call them supercomments.

The remaining code is simply ignored.


JavaScript (ES6), 75 bytes

Saved 4 bytes thanks to @Mwr247

Manipulator: (47 bytes)

(a,b,c=1,d=0,z=(1<<c)-1<<b)=>d?d<0?a&~z:a|z:a^z

Reader: (28 bytes)

(a,b,c=1)=>a>>b&(1<<c-1)*2-1

How it works

Manipulator

The first thing we need to do is figure out the number that has c bits set, starting at the bth bit. Possibly the best way to do this is z=(1<<c)-1<<b, which works like so:

b  c    1<<c     -1     <<b    z
2  1      10     01    0100    4
2  2     100    011   01100   12
2  3    1000   0111  011100   28
1  4   10000  01111  011110   30

Now we take into account d. For case 0, we flip the bits with a^z; for case 1, we set the bits to 1 with a|z; for case -1, we set the bits to 0 with a&~z.


Commodore 64 BASIC

40 print "Line 1"
30 print "Line 2"
20 print "Line 3"
10 print "Line 4"


Count how many characters are in the program's source

Bash, 10

Pretty boring, but:

Prints the code size in bytes, and nothing else.
Filename may contain spaces.

Make sure that the file doesn't have a new line at the end! If it does, it will output 11.

wc -c<"$0"

If the file doesn't have spaces in its name, you can get 8 characters:

wc -c<$0


Finding Nash Equilibria

This is a very important concept when the KOTH involves a relatively simple set of decisions, involves only a few players (typically 2), and is deterministic.  A Nash equilibrium describes a "gridlock" position: if the two players have decided upon their two strategies, then the two players are effectively locked in those positions: either player changing their strategy simply creates additional vulnerabilities.

Examples of games where Nash equilibria are important are:

Rock-Paper-Scissors(-Lizard-Spock), in which an "unbeatable" strategy is random play
Morra, which has a "spectrum" of equilibria. Peter Taylor wrote a good example in his answer here.
Prisoner's Dilemma, a cooperative game notable for having an "everybody loses" gridlock

How to find an equilibrium

Finding an equilibrium actually is actually pretty simple for most simple games, and is often pretty intuitive.  A ton of detail about the various methods can be found on the internet.  The basic concept, which is normally applicable, is to create a list of possible strategies that the two players can use (the options provided by the game).  If one strategy is "dominated" by another, then that strategy can be removed from the list, and the process is repeated. By "domination," I mean that if strategy A always gives an equal-or-better result than strategy B, against all of the remaining opponent strategies, then strategy B can be removed from the list.

Example: Rock-Paper-Scissors

RPS has something called a "mixed" equilibrium, meaning that a distribution is involved.  Rather than playing the same move repeatedly (which will lead to quick defeat), the equilibrium is to play 1/3 rock, 1/3 paper, and 1/3 scissors in a random distribution.  If I play randomly, there is nothing my opponent can do to get an edge on me, period.  If my opponent chooses not to play randomly, then that only creates a vulnerability on his part.

Games with mixed equilibrium are probably the most common on PPCG, since they can take many forms (the only interesting game I can think of with a pure equilibrium is prisoner's dilemma).  I should note that the mixed equilibrium doesn't have to be uniformly random, simply something other than playing the same move every time.

Using this information

The Nash equilibrium of a game often represents the "baseline" from which you should try to operate.  In RPS, playing randomly guarantees a finishing spot around the middle of the pack.  In order to move to the top, you have to start identifying other player's weaknesses.

To do this, you should stick to the equilibrium when unsure of the opponent's weaknesses.  Once those weaknesses have been identified (you have detected that your opponent is not in equilibrium), then you need to gently shift out of equilibrium to take advantage of your opponent.  This action, in turn, creates weaknesses on your own part.  You must then detect when your opponent is changing his strategy, so that you can then stop the attack and resume random play.

Detecting variation from equilibrium

This is pretty difficult, and I am not an expert.  Variations can come in many forms:

Favoring some options above/below others for no reason, like an RPS player that plays rock twice as often as scissors, or one that avoids playing paper.  Some relatively simple statistics can detect this.
Basing a current move off past moves, in some predictable pattern.  This includes copy-cats, "beats what beats your last move" bots, or "cycling" bots.  This takes additional logic to detect, since the overall move distribution can be evenly-distributed, even though the moves aren't random.  You should attempt to take the record of moves and find correlations like "the move I made 2 turns ago and the move my opponent made now" and "the move he made 1 turn ago, and the move he made now", etc.
Bots whose move distribution is based off of yours.  The vulnerability in these bots is often not created (in a measurable quantity) until after you have yourself varied from a random distribution.  Generally, your own bot falls into this category.


Python 2, 194 191 186 bytes

g=map(list,[' '*200]*100)
for x,h,z,t,s in sorted(input(),key=lambda m:-m[2]):
 for i in range(h):g[-h+i][x+~i:x-~i]=['/']+[' *Y'[(i<h-s)-(i>=h-t)]]*2*i+['\\']
for l in g:print''.join(l)

Try it online!

Prints the whole 100x200 grid.


PHP, 241 bytes

<?=preg_replace(["#\b(President|Founder)\b#i","#\bMaster instructor\b#i","#\bTeacher\b#i","#\bBlack Belt\b#i","#\b(Studen|Color Bel)t\b#i","#\bMaster level\b#i"],[Gwanjang.$n=" nim",Sabeom.$n,Gyosa.$n,Dan,Geup,Godanja],"$argn, *side-kick*");

Try it online!


Retina, 87 86 85 bytes

Thanks to Dennis for saving 1 byte.

^.{0,79}$
$0
:`^
<ESC>c
(`/ | \\
__
/\|(?!\\)
//a
(?<!/)\|\\
\\
$
aaaaa
a
aaaa
(a+)+b|a
<empty>

<ESC> should be replaced by the actual control character (0x1B). <empty> represents an empty trailing line. You can then run the above code from a single file with the -s flag.

The code requires a terminal which supports ANSI escape codes. I can't suppress the line feed in Retina's output so I need to clear the entire console with <ESC>c each time. I've tested the code in bash using Mono to run Retina.

Explanation

^.{0,79}$
$0

We start by appending a space if the input contains fewer than 80 characters. This is so that a / at the right end does not have to be treated separately.

:`^
<ESC>c

Now we prepend <ESC>c to the string, which is the ANSI escape code for clearing the terminal. So every time the string is printed it will do so at the top of the terminal. The :` instructs Retina to print out the result of this substitution, i.e. the initial configuration.

(`/ | \\
__

(` begins a loop. Since there is no matching ), the loop is assumed to go until the last stage of the program. Each iteration will simulate one step of the dominoes falling and then "sleep" a bit. This first stage replaces / and \ next to a space into __. This automatically handles the / \ case correctly, because matches cannot overlap and are searched for from left to right. So the /<sp> would be matched and turned into __ such that the \ can't be matched, and we get the correct __\.

/\|(?!\\)
//a

This turns /| into // provided there's no \ next to it. We append an a such that this new / doesn't mess with the next stage (which shouldn't "know" about this change yet).

(?<!/)\|\\
\\

The opposite situation: turn |\ into \\ provided there's no / next to it. We don't need to put an a here, because we're done with this step of the simulation.

Now the sleeping part...

$
aaaaa

Appends 5 more as to the end of the code.

a
aaaa

Turns each a into 4 as, so we get 20 as at the end.

(a+)+b|a
<empty>

Now the fun part... we sleep for a bit with the help of catastrophic backtracking. There is an exponential amount of ways to split up a match of (a+)+ between repetitions of the group. Because the b causes the match to fail, the engine will backtrack and try every single one of those combinations before deciding that (a+)+b can't match. For the twenty as at the end that takes something like half a second.

At the same time, we allow the regex to match a single a, but only after doing the backtracking. When that matches, we replace it with an empty string, removing all the as we inserted for one reason or another from the string.

That leaves printing the string at the end of the loop iteration. Here it comes in handy that I haven't fixed the printing behaviour of loops in Retina yet. Currently, there is only one flag for each stage, which says "print" or "don't print". The default is "don't print" except for the last stage in the program, which defaults to "print". But the stage is looped, so that means it actually prints the current string on each iteration. Normally, that is really annoying, and you almost always need to include an additional empty stage at the end if you only want the final result, but here it lets me save four bytes.


Hexagony, 920 722 271 bytes

Six different types of fruit loops, you say? That is what Hexagony was made for.

){r''o{{y\p''b{{g''<.{</"&~"&~"&<_.>/{.\.....~..&.>}<.._...=.>\<=..}.|>'%<}|\.._\..>....\.}.><.|\{{*<.>,<.>/.\}/.>...\'/../==.|....|./".<_>){{<\....._>\'=.|.....>{>)<._\....<..\..=.._/}\~><.|.....>e''\.<.}\{{\|./<../e;*\.@=_.~><.>{}<><;.(~.__..>\._..>'"n{{<>{<...="<.>../

Okay, it wasn't. Oh god, what did I do to myself...

This code is now a hexagon of side length 10 (it started out at 19). It could probably be golfed some more, maybe even to size 9, but I think my job is done here... For reference, there are 175 actual commands in the source, many of which are potentially unnecessary mirrors (or were added to cancel out a command from a crossing path).

Despite the apparent linearity, the code is actually two-dimensional: Hexagony will rearrange it into a regular hexagon (which is also valid code, but all whitespace is optional in Hexagony). Here is the unfolded code in all its... well I don't want to say "beauty":

          ) { r ' ' o { { y \
         p ' ' b { { g ' ' < .
        { < / " & ~ " & ~ " & <
       _ . > / { . \ . . . . . ~
      . . & . > } < . . _ . . . =
     . > \ < = . . } . | > ' % < }
    | \ . . _ \ . . > . . . . \ . }
   . > < . | \ { { * < . > , < . > /
  . \ } / . > . . . \ ' / . . / = = .
 | . . . . | . / " . < _ > ) { { < \ .
  . . . . _ > \ ' = . | . . . . . > {
   > ) < . _ \ . . . . < . . \ . . =
    . . _ / } \ ~ > < . | . . . . .
     > e ' ' \ . < . } \ { { \ | .
      / < . . / e ; * \ . @ = _ .
       ~ > < . > { } < > < ; . (
        ~ . _ _ . . > \ . _ . .
         > ' " n { { < > { < .
          . . = " < . > . . /

Explanation

I won't even try and begin explaining all the convoluted execution paths in this golfed version, but the algorithm and overall control flow are identical to this ungolfed version which might be easier to study for the really curious after I've explained the algorithm:

                 ) { r ' ' o { { \ / ' ' p { . . .
                . . . . . . . . y . b . . . . . . .
               . . . . . . . . ' . . { . . . . . . .
              . . . . . . . . \ ' g { / . . . . . . .
             . . . . . . . . . . . . . . . . . . . . .
            . . . . . . . . . . . . . . . . . . . . . .
           . . . . . . . . > . . . . < . . . . . . . . .
          . . . . . . . . . . . . . . > . . ) < . . . . .
         . . . . . . . . . . / = { { < . . . . ( . . . . .
        . . . . . . . . . . . ; . . . > . . . . . . . . . <
       . . . . . . . . . . . . > < . / e ; * \ . . . . . . .
      . . . . . . . . . . . . @ . } . > { } < . . | . . . . .
     . . . . . / } \ . . . . . . . > < . . . > { < . . . . . .
    . . . . . . > < . . . . . . . . . . . . . . . | . . . . . .
   . . . . . . . . _ . . > . . \ \ " ' / . . . . . . . . . . . .
  . . . . . . \ { { \ . . . > < . . > . . . . \ . . . . . . . . .
 . < . . . . . . . * . . . { . > { } n = { { < . . . / { . \ . . |
  . > { { ) < . . ' . . . { . \ ' < . . . . . _ . . . > } < . . .
   | . . . . > , < . . . e . . . . . . . . . . . . . = . . } . .
    . . . . . . . > ' % < . . . . . . . . . . . . . & . . . | .
     . . . . _ . . } . . > } } = ~ & " ~ & " ~ & " < . . . . .
      . . . \ . . < . . . . . . . . . . . . . . . . } . . . .
       . \ . . . . . . . . . . . . . . . . . . . . . . . < .
        . . . . | . . . . . . . . . . . . . . . . . . = . .
         . . . . . . \ . . . . . . . . . . . . . . . . / .
          . . . . . . > . . . . . . . . . . . . . . . . <
           . . . . . . . . . . . . . . . . . . . . . . .
            _ . . . . . . . . . . . . . . . . . . . . .
             . . . . . . . . . . . . . . . . . . . . .
              . . . . . . . . . . . . . . . . . . . .
               . . . . . . . . . . . . . . . . . . .
                . . . . . . . . . . . . . . . . . .
                 . . . . . . . . . . . . . . . . .

Honestly, in the first paragraph I was only half joking. The fact that we're dealing with a cycle of six elements was actually a great help. The memory model of Hexagony is an infinite hexagonal grid where each edge of the grid contains a signed arbitrary-precision integer, initialised to zero.

Here is a diagram of the layout of the memory I've used in this program:

The long straight bit on the left is used as a 0-terminated string a of arbitrary size which is associated with the letter r. The dashed lines on the other letters represent the same kind of structure, each one rotated by 60 degrees. Initially, the memory pointer points at the edge labelled 1, facing north.

The first, linear bit of the code sets the inner "star" of edges to the letters roygbp as well as setting the initial edge to 1, such that we know where the cycle ends/begins (between p and r):

){r''o{{y''g{{b''p{

After this, we're back on the edge labelled 1.

Now the general idea of the algorithm is this:

For each letter in the cycle, keep reading letters from STDIN and, if they are different from the current letter, append them to the string associated with that letter.
When we read the letter we're currently looking for, we store an e in the edge labelled ?, because as long as the cycle is not complete, we have to assume that we'll have to eat this character as well. Afterwards, we'll move around the ring to the next character in the cycle.
There are two ways this process can be interrupted:

Either we've completed cycle. In this case, we make another quick round through the cycle, replacing all those es in the ? edges with ns, because now we want that cycle to remain on the necklace. Then we move on to printing code.
Or we hit EOF (which we recognise as a negative character code). In this case, we write a negative value into the ? edge of the current character (so that we can easily distinguish it from both e and n). Then we search for the 1 edge (to skip the remainder of a potentially incomplete cycle) before moving to printing code as well.

The printing code goes through the cycle again: for each character in the cycle it clears the stored string while printing an e for each character. Then it moves to the ? edge associated with the character. If it's negative, we simply terminate the program. If it's positive, we simply print it and move on to the next character. Once we complete the cycle we go back to step 2.

Another thing that might be interesting is how I've implemented the arbitrary-size strings (because it's the first time I've used unbounded memory in Hexagony).

Imagine we're at some point where we're still reading characters for r (so we can use the diagram as is) and a[0] and a1 have already been filled with characters (everything north-west of them is still zero). E.g. maybe we've just read the first two characters og of the input into those edges and are now reading a y.

The new character is read into the in edge. We use the ? edge to check whether this character is equal to r. (There's a nifty trick here: Hexagony can only distinguish between positive and non-positive easily, so checking for equality via subtraction is annoying and requires at least two branches. But all the letters are less than a factor of 2 from each other, so we can compare the values by taking the modulo, which will only give zero if they are equal.)

Because y is different from r, we move the (unlabelled) edge left of in and copy the y there. We now move further around the hexagon, copying the character one edge further each time, until we have the y on the edge opposite of in. But now there is already a character in a[0] which we don't want to overwrite. Instead, we "drag" the y around the next hexagon and check a1. But there's a character there as well, so we go another hexagon further out. Now a[2] is still zero, so we copy the y into it. The memory pointer now moves back along the string towards the inner ring. We know when we've reached the beginning of the string, because the (unlabelled) edges between the a[i] are all zero whereas ? is positive.

This will probably be a useful technique for writing non-trivial code in Hexagony in general.


05AB1E, 13 bytes
Input is a list of digits.
.•*Š"—Êo•sèJ™

Try it online! or Try all cases!
Commented:
.•*Š"—Êo•      # compressed alphabet string "nubtqphsoe"
         s     # swap to implicit input
          è    # index each digit into the string
           J   # join into a single string
            ™  # apply title case

See the step-by-step output here.

Lyxal has suggested another 13-byter with a nicer input format:
.•*Š"—Êo•ÅвJ™

Try it online!
This uses Åв, which converts the input integer into the custom base defined by the string.


Brachylog, 28 26 bytes
:K≜+ℕ~lṗ.+₁~×[İ,J]h:2^₍J≜∧

Try it online!
This is too slow for TIO for inputs bigger than 4.
Explanation
:K                             The list [Input, K]
  ≜                            Assign a value to K (0, then 1, then -1, then 2, etc.)
   +ℕ                          Input + K >= 0
     ~l .                      Output is a number of length (Input + K)
       ṗ.                      Output must be a prime number
         +₁                    Output + 1...
           ~×[İ,J]             ... = İ × J, İ being an integer...
                  h:2^₍J       ... and J = 2^İ
                         ≜∧    Check that it is possible to find a value for İ that satisfies
                                 all of those constraints. If not, go back to the beginning
                                 and try another value for K through backtracking.

We use a common trick in Brachylog for "find the closest X to Y": labeling a completely free variable (which we do when we use ≜ on the list [Input, K] will label it with this pattern: 0, 1, -1, 2, -2, 3, .... Therefore, when backtracking if the value Input + K doesn't work as the number of digits, the next choice we will try will be the next possible closest choice.


J, 16 bytes

Function 1, 5 bytes

p:^i.

Function 2, 6 bytes

+p:^i.

Function 3, 5 bytes

>:^i.

How it works

Function 1

p:^i.     Right argument: y

   i.     Compute (0 ... y-1).
p:        Compute P, the prime at index y (zero-indexed).
  ^       Return all powers P^e, where e belongs to (0 ... y-1).

Since P is prime and P > y, y cannot divide Pe.

Function 2

+p:^i.    Right argument: y

 p:^i.    As before.
+         Add y to all results.

If y divided Pe + y, it would also divide Pe + y - y = Pe.

Function 3

>:^i.     Right argument: y

   i.     Compute (0 ... y-1).
>:        Compute y+1.
  ^       Return all powers (y+1)^e, where e belongs to (0 ... y-1).

If y divided (y+1)e some prime factor Q of y would have to divide (y+1)e.

But then, Q would divide both y and y+1 and, therefore, y + 1 - y = 1.


Jelly, 8 bytes

BFṢḄæ«ÆẸ

Try it online!

Left inverse, 5 bytes

Bċ0ÆE

Try it online!

How it works

BFṢḄæ«ÆẸ  Main link. Argument: A (array)

B         Binary; convert each integer in A to base 2.
 F        Flatten; concatenate the resulting binary arrays.
  Ṣ       Sort the resulting bit array.
   Ḅ      Convert from base 2 to integer, yielding an integer x with as much set
          bits as there are set bits in A.
      ÆẸ  Unexponents; convert A = [a1, a2, ...] to y = (p1**a1 + p2**a2 + ...),
          where pn is the n-th prime number.
          By the fundamental theorem of arithmetic, the resulting integer is unique
          for each array A without trailing zeroes.
    æ«    Bitshift left; compute x * 2**y.


Ruby - 131 115 107 97 84 bytes

I'm still golfing it.

h,m,s=gets.split(/\w/).map &:to_i;$><<"#{(h+m/60+s/3600)%24}:#{(m+s/60)%60}:#{s%60}"

Thanks for @Doorknob for /\w/ inshead of /h|m|s/


JavaScript (ES6), 76 bytes
Expects the angles in radians. Returns either [x,y] or 0 if the lines are parallel or coincident.

(x,y,a,X,Y,A)=>a-A&&[(m=(t=Math.tan)(a))*(X-=(x-=m*y)+t(A)*Y,X/=m-t(A))+x,X]

Try it online!
Or 71 bytes if we can just return [Infinity,Infinity] for invalid inputs.


C, 2*70 2*60

Prints y for primes, nothing otherwise.
EDIT: Changed code to save 10 chars. Must be run without paramters (so m=1).

main(m,n){for(scanf("%d",&n);n%++m&&n>1;);n-m||puts("y");}/*
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/

The method for handling the transposition is quite generic, and can be applied to any program.
It's based on converting this:

abcd/*
\\\\*/

To this:

a\
b\
c\
d\
/*
*/

And both mean simply abcd.


Charcoal, 20 18 bytes

↘ＥＮ×*⊕ιＭ↗oＵＥ¬﹪η²⟲η

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

↘ＥＮ×*⊕ι

Draw a diagonal triangle of splats.

Ｍ↗o

Place the egg.

ＵＥ¬﹪η²

For even rotations, expand the splat horizontally to match the output requirement. This requirement doesn't match Charcoal's usual expectations. Try it online! (verbose) for how it looks without.

⟲η

Rotate the splat as required, using the following code for directions:

321
4o0
567

This 37 31-byte version avoids extraneous whitespace by only rotating in right angles:

¿﹪η²Ｇ↘←θ*«↘Ｅθ×*⊕ι↗»oＵＥ¹﹪η²⟲⊗÷η²

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


Charcoal, score 235 168

→ＷＳ⊞υιＦυＦ
«Ｐ↙ιＭ²←»Ｆ
Ｍ⊖⌈ＥυＬκ↙Ｆ
Ｆυ«Ｐ↖κ↗»Ｆ
Ｍ⊖⌈ＥυＬκ↖Ｆ
Ｆυ«Ｐ⪫κ ↘»

Try it online! Takes input as a newline-terminated list. Charcoal's problem here is that a newline is a command, so I can't just throw newlines in arbitrarily. Instead, I'm passing them as arguments to the For command, which loops over each character in the string, which here is just the one character, therefore not modifying the behaviour of the program (except to change the implicit loop variables). As such, these dummy For instructions are not included in the explanation. Explanation:

→

Another no-op, just to make the code exactly rectangular.

ＷＳ⊞υι

Input the list.

Ｆυ«Ｐ↙ιＭ²←»

Print the lower right diagonal side.

Ｍ⊖⌈ＥυＬκ↙

Move to the bottom.

Ｆυ«Ｐ↖κ↗»

Print the lower left diagonal side.

Ｍ⊖⌈ＥυＬκ↖

Move to the top left.

Ｆυ«Ｐ⪫κ ↘»

Print the top side.


JavaScript ES6, 94 92 72 70 66 64 bytes

Saved 6 bytes thanks to Neil!

n=>[...Array(a=Math.sqrt(8*n+1)-1>>1)].map((_,l)=>l<n-a*(a+1)/2)

I don't think this can be golfed more. At least with the equations.

Explanation

They are two main equations (n is input):

(Math.sqrt(8*n+1)-1)/2

This will give the total size the output array will need to be. In my program I used >>1 instead of (...)/2 these are the same as the first bit in binary has a value of 2. Shifting it will result in in floor(.../2)

n-a*(a+1)/2

This is the amount of trues there will be. a is the result of the previous expression.

This is what the syntax does:

[...Array(n)]

This code generates an array with range [0, n) in this answer n is the first equation.

.map((_,l)=>l<n) this will loop through the above range, l is the variable containing the current item in the range. If the item is less than the amount of trues they are (determined by second equation), then it will return true, else false.


APL (Dyalog Classic), 71 68 65 63 bytes

0{⍵≡⍕⍵:⍵⋄⍬≡⍵:'⍬'⋄1=≢⍵:⍺∇⊃⍵⋄3≥≢⍵:⍺⌽')(',⍣⍺∊1∇¨⍵⋄⍺∇¯3(↓,∘⊂1∇↑)⍵}⍎

Try it online!

The characters I chose for I/O are '(', ')', and '⍬'.

This solution is itself an APL train.

⍎ parses the input as if it's a nested array - a tree with empty numeric vectors (⍬) as leaves.

The dfn (i.e. lambda - { }) traverses the tree recursively and converts it to a properly parenthesised string. The left argument ⍺ controls whether parentheses should be added to the current level if necessary.

The dfn handles the following cases based on the right argument:

if it's already a string (⍵≡⍕⍵), return it
if it's ⍬, return the char '⍬'
if it's a singleton, just dig deeper (∇ is the symbol for a recursive call)
if its length is ≤3, recurse for each of the items and surround with () if necessary
otherwise, recurse for the 3-tail, prepend all but the 3-tail, and recurse again


Find the Missing Numbers in the Fibonacci Sequence Mod K

Haskell, 70 bytes

Some amount of bytes saved thanks to Esolanging Fruit

8 bytes saved thanks to Laikoni

a=1:scanl(+)1a
f x=[u|u<-[2..x-1],and[mod b x/=u|(_,b)<-zip[1..x^2]a]]

Try it online!


CJam, 51 bytes

Laeas$W%{1$f++}/:A;qN/{$aA&},{,~}$5<_0=,:L;{,L=},S*

CJam has no file I/O, so I opted to read the dictionary (converted to Unix format) from STDIN and read the string of letters as a command-line argument.

Test cases

$ for w in mhdexaspo iesretmng cmilensua floiufhyp frtuasmjg
> do cjam countdown.cjam $w < dictionary.txt
> echo
> done
hexapods mopheads
regiments
calumnies masculine
huffily puffily
frusta gamuts grafts jumars jurats

How it works

La        " Push T := [ '' ].                                                         ";
eas       " Push the command-line argument (R) as a string.                           ";
$W%       " Sort its letters, then reverse.                                           ";
{1$f++}/  " Iterate over the letters; prepend them to copies of the strings in T.     ";
:A;       " Save in A and discard. A contains all sorted substrings of R.             ";
qN/       " Read from STDIN and split at linefeeds.                                   ";
{$aA&},   " Filter; keep dictionary words D such that {sort(D)} ∩ A ≠ ∅.              ";
{,~}$     " Sort by negated word length.                                              ";
5<        " Keep only the first five words.                                           ";
_0=,:L;   " Save the length of the first in L.                                        ";
{,L=},    " Filter; keep dictionary words D such that len(D) = L.                     ";
 S*       " Separate by spaces.                                                       ";


JavaScript (ES6), 32 bytes
(_=screen)=>_.width+"x"+_.height

Outputs as function return. Add f= at the beginning and invoke like f(). Uses parameter-initializing to initialize the parameter _ to screen object. The rest is self-explanatory.

f=(_=screen)=>_.width+"x"+_.height
console.log(f())

Note: Passing an argument to this function will cause it to fail.

JavaScript (Previous Solution), 35 bytes

with(screen)alert(width+"x"+height)

Never thought I will one day use with! I don't think this can be golfed further.


Perl: 105 - 15 - 20 = 70

perl -MJSON -pE'sub f{$_[0]=~s#{{\s*((.*?(?R)?.*?)+)\s*}}#$h->{f($1)}#reg};BEGIN{$h=from_json shift};$_=f$_' 'JSON' <input

Usage: the JSON is given as a command line argument. The template source is passed in STDIN. Example:

$ perl ... '{"user_Joe":"Joseph, user #1234","username":"Joe","my n@m3":"Henry"}'
>Hello, {{user_{{username }}}}! It is { NICE } to meet you!
>My name is {{     my n@m3}}!

(where lines beginning with > are pasted/typed/piped in)

Restrictions:

can't do arithmetic.
keys cannot span multiple lines.
requires the JSON Perl module to be installed (non-standard).
requires a new-ish perl (tested on Perl5 v20, but should work on at least v16 or v14).

I am not sure about the scoring rules, so I excluded perl·, the quotes for the code, and included an extra space and two quotes needed to pass the JSON on the command line.

Explanation:

Perl regexes can be recursive, but substitutions can't. To overcome this, we first define a regex that matches keys that might contain keys again: {{\s* ((.*? (?R)? .*?)+) \s*}}. Here, (?R) recurses into the whole pattern. The key does not have to contain a template tag, so the recursion is optional. In that case, the pattern is a non-greedy “match anything”: .*?.*?. This will terminate given a double closing braces. Usually braces are metacharacters in regexes, e.g. a{10,20} (match 10 to 20 "a"s). Fortunately, the regex compiler recognizes that these braces are not used as quantifiers.

Once we have matched the (possibly recursive) tag contents, we pass it to the function f which again applies the substitution to this content. The result is then used as a key in a hash reference $h, which replaces the tag contents. This is done non-destructively /r and globally /g.

The $h hash reference is defined in the BEGIN phase to the json-decoded value of the first command line argument. Since the sub f definition and the BEGIN block are done before the main execution, the actual script is perl -pE'$_=f$_', which applies our substitution function f to each line.

Voilà, a template engine is born :)


Symbolic Differentiation of Composed Functions

Java 8, 224 214 bytes

Let the games begin!

interface B{static void main(String[]a){String o="";int v=2,z=a.length-1,i=z,k;for(;i>0;o+="x)"){if(a[--i].equals("cos")){o+="(sin ";v=(v+2)%4;}else o+="(cos ";for(k=i;++k<z;)o+=a[k]+" ";}System.out.print(v-1+o);}}

This could (theoretically) extend infinitely.

Output for sin cos sin sin cos sin cos sin sin sin cos sin sin cos sin cos cos cos sin x:

1(cos x)(sin sin x)(sin cos sin x)(sin cos cos sin x)(cos cos cos cos sin x)(sin sin cos cos cos sin x)(cos cos sin cos cos cos sin x)(cos sin cos sin cos cos cos sin x)(sin sin sin cos sin cos cos cos sin x)(cos cos sin sin cos sin cos cos cos sin x)(cos sin cos sin sin cos sin cos cos cos sin x)(cos sin sin cos sin sin cos sin cos cos cos sin x)(sin sin sin sin cos sin sin cos sin cos cos cos sin x)(cos cos sin sin sin cos sin sin cos sin cos cos cos sin x)(sin sin cos sin sin sin cos sin sin cos sin cos cos cos sin x)(cos cos sin cos sin sin sin cos sin sin cos sin cos cos cos sin x)(cos sin cos sin cos sin sin sin cos sin sin cos sin cos cos cos sin x)(sin sin sin cos sin cos sin sin sin cos sin sin cos sin cos cos cos sin x)(cos cos sin sin cos sin cos sin sin sin cos sin sin cos sin cos cos cos sin x)


Count rotary dial pulses in a phone number (including letters)

05AB1E, 19 18 17 15 bytes

AÁ0ªā6+žq÷9š‡þO

Try it online!

This is the first answer to use π. Why use π, you might ask? Well, the letters are associated with 22233344455566677778889999, in order. Notice how most digits repeat 3 times, but 7 repeats 4 times. You could say that each digit repeats (3+1/7) times, on average. I wonder if there’s any number that’s approximately 3+1/7 and takes fewer bytes than 22/7…

This only gives 4 7s, not 4 9s, so we still need to handle Z as a special case.

A               # alphabet (abcdefghijklmnopqrstuvwxyz)
 Á              # rotate right (zabcdefghijklmnopqrstuvwxy)
  0ª            # append 0 (zabcdefghijklmnopqrstuvwxy0)

ā6+             # range [7..33]
   žq÷          # divide by π (22233344455566677778889991010)
      9š        # prepend 9 (922233344455566677778889991010)

‡               # transliterate the implicit input with the two lists above
                # this replaces z → 9, a → 2, … y → 9, 0 → 10
 þ              # remove all non-digits
  O             # sum


Display 0 - 1000 - 0 each on a separate line

PHP, 38 bytes

for(;$i-=1|$x|=$i/1001;)echo~$i,"<p>";

Try it online!
A one-byte improvement by JoKing. The idea is that by decrementing $i instead of incrementing it, we can save on the minus in the 1|-$x construction by having $x become -1 instead of 1 as a signal. This is achieved by using $i/1001, which is 0 if $i>-1001 and -1 otherwise. This would break even if not for the fact we can now use ~$i instead of $i-1.
PHP, 39 bytes

for(;$i+=1|-$x|=$i>1e3;)echo$i-1,"<p>";

Try it online!
In collaboration with primo on the code.golf discord.
The idea is to have a signal variable $x that is zero until $i hits 1000 then is 1 afterwards. We use the bitwise construction 1|-$x which is a shorter version of $x ? -1 : 1 to select whether to go upwards or downwards.


Python (565 - 150 = 415)

Btw... it seems that we can't naively just decide the next tile by the its left and top tile. There's some combination of tiles that will fit each other.
This solution fills in left->right, top->down brute forces through all possible combinations and backtracks if a tile cannot fit in.

For more info about the 13 tile proof: An aperiodic set of 13 Wang tiles

Width and Height are specified by W and H

Red, Green, Blue, Yellow and Noir specified by R, G, B, Y and N

import Image,sys
W,H=map(int,sys.argv[1:])
R=99
G=R<<8
B=G<<8
Y=G+R
N=0
s="RGB";u=32;g=[[0,0]]*W*H;k=f=0
def t(c):i=Image.new(s,(2,2));k=i.load();q=16;k[1,0],k[1,1],k[0,1],k[0,0]=c;return i.resize([64]*2).rotate(45).crop((q,q,q+u,q+u))
while k<H*W:
 z=g[k][1];v=-1;j=k/W;i=k%W
 while z<13:
    l=map(eval,"GGGRRRYBGGYBGGBBRRGYYNNNNYBGBGBGRGRYRGGRRGGBBYYYYNNN"[z::13])
    if(j<1or g[(j-1)*W+i][0][2]==l[0])and(i<1or g[j*W+i-1][0][1]==l[3]):g[k]=[l,z+1];v=1;z=99
    z+=1
 g[k][1]*=(v>0);k+=v
m=Image.new(s,(W*u,H*u))
for e in g:m.paste(t(e[0]),(f%W*u,(f/W)*u));f+=1
m.show()

Output. Not the actual color scheme... cuz too glaring. This might make some interesting interior decor patterns...:


Haskell - 43 31

43 characters without anything fancy.
f 0=0
f 8=8
f 2=5
f 5=2
f 6=9
f 9=6
f _= -1

Got it down to 31 characters by making it a partial function.
f=([0,-1,5,-1,-1,2,9,-1,8,6]!!)


Count the lucky tickets within the given range

05AB1E, 8 (or 10?) 11 (or 13?) bytes
Ÿʒ₄n+¦S3ôOË

Try it online or verify some more test cases.
NOTE: In 05AB1E strings and integers are interchangeable, so the output numbers doesn't contain leading zeroes. This could however be fixed with 1 additional byte (12 bytes):
Ÿ₄n+€¦ʒS3ôOË

Try it online or verify some more test cases.
+3 bytes to bug-fix numbers with a length of 3 or less (range [000000, 000999]).
Explanation:

Ÿ          # Create an inclusive (on both sides) range from the two inputs
           #  i.e. 038920 and 038910 →
           #   [38910,38911,38912,38913,38914,38915,38916,38917,38918,38919,38920]
 ʒ         # Filter this list by:
  ₄n+      #  Add 1,000,000 to the number
     |     #  And remove the leading 1
           #   i.e. 38910 → 1038910 → '038910'
  S        #  Transform it to a list of digits
           #   i.e. '038910' → ['0','3','8','9','1','0']
   3ô      #  Split it into chunks of length 3
           #   i.e. ['0','3','8','9','1','0'] → [['0','3','8'],['9','1','0']]
     O     #  Sum the digits in both parts
           #   i.e. [['0','3','8'],['9','1','0']] → [11,10]
      Ë    #  Check if they are equal (if they are, they remain in the filtered list)
           #   i.e. [11,10] → 0

EDIT: Seems I (and most other answers) slightly misread the challenge and the amount of numbers is being asked instead of the numbers themselves within the range. In that case a trailing }g can be added (close the filter; and get the amount of numbers left in the filtered list), so it's 10 13 bytes instead:
Ÿʒ₄n+¦S3ôOË}g

Try it online or verify some more test cases.


Ruby, 181 163 153 146 characters
h=[0]*4e4
[0,-200,201,202,2,3].map{|i|h[i]=1}
gets.to_i.times{h=h.map{[g=1,200,201].map{|x|g+=h[x]+h[-x]};g>5-h.rotate![-1]||g<3?0:1}}
p h.count 1

This implementation follows a standard approach using an array h (dimensions 200 x 200 flattened), where each element is either 0 (no bee) or 1 (bee included). The array [0,-200,201,202,2,3] describes the initial positions of bees (relative to any initial cell).
Input and output as specified above, passes all test cases defined.
Edit 1: changed back to a wrapping solution instead of the "additional space"-version (which was shorter in an intermediate version but now is several characters longer).
Edit 2: removed variable b completely.
Edit 3: warning: this edit made the program horribly slow. I thus reduced the dimensions to 200 each which still is sufficient for up to 150 iterations. Instead of indexing the array by a variable we constantly rotate the array forward. Not really good design, but now we are considerably below the 150.


Rational / Float / Complex

I've read so many times that GolfScript has only integers that I started to believe it. Well, it's not true.

2-1? # Raise 2 to the power of -1. Result: 0.5
4-1? # Raise 4 to the power of -1. Result: 0.25
+    # Add. Result: 0.75

The output is

3/4

with the standard GolfScript interpreter and

0.75

on Web GolfScript.

Similar hacks allow to cast to Rational, Float or even Complex:

{-2.?./*}:rational
{2.-1??./*}:float
{-2.-1??./*}:complex


C, 108 bytes

-1 byte thanks to Logern
-3 bytes thanks to ceilingcat

f(M,n,i)double**M;{for(i=n*n;i--;)M[i/n][i%n]-=M[n][i%n]*M[i/n][n]/M[n][n];return M[n][n]>0&(!n||f(M,n-1));}

Try it online!

Performs Gaussian elimination and checks whether all diagonal elements are positive (Sylvester's criterion). Argument n is the size of the matrix minus one.


Jelly, 7 bytes

Ṭ=Ḃµ€ŒB

Try it online!

-1 byte thanks to Erik the Outgolfer

Explanation

Ṭ=Ḃµ€ŒB  Main link
    €    For each element in (implicit range of) the input:
Ṭ        List 1s and 0s with 1s in the indices in the left argument (generates `[0, 0, ..., 1]`)
 =Ḃ      Is this equal to `(z % 2)` where `z` is the range number? (Every other row is flipped)
     ŒB  Reflect each row


Alice, 28 bytes

/mY. zm~wZ.k;
\I;'!*?RR.OY@/

Try it online!

If the input length is odd, this puts the padding space at the end of the linearised program, which ends up being the first character of the output.

Leo wrote an Ordinal formatter in Alice a few days ago. After adding support for odd-length inputs and then removing some stuff that wasn't necessary for this challenge, we ended up at 28 bytes. I wanted to try a slightly different approach, which is this answer. Unfortunately, it just ended up tying 28 bytes, but at least this way I can post my own solution and let Leo post his original algorithm.

This does use Leo's really clever idea to split a string in half with ..Y;m;.!z?~.

Explanation

Let's assume that the input has even length (because we'll just pad it with a space if it doesn't). The pattern is a bit easier to see if we use 0123456789 as the code. The required output would be:

91735
08264

So the first line contains all odd positions of the input and the second line all the even inputs. Furthermore, if we reverse the odd positions, then the lines itself are both the first half (possibly longer) interleaved with the reverse of second half.

So the basic idea is:

Separate input into odd and even positions.
Pad the odd positions with a space if necessary.
Reverse the odd positions.
Then twice: halve the current string, reverse the second half, interleave both halves, print with trailing linefeed.

As for the code, this looks a lot like the kind of layout we're producing in this challenge, but it's subtly different: when the IP hits the / at the end of the code it gets reflected east, not south. Then, while in Cardinal mode, the IP will wrap around to the first column. The \ there re-enters Ordinal mode, so that the second half of the code doesn't go from right to left here, but from left to right as well. This is beneficial when working with the return address stack, because it doesn't store information about the IP's direction. This lets us save a few bytes because the IP will move in the same (horizontal) direction on both w and k.

The linearised code is this:

IY' *mRw..Y;m;.!z?~RZOk@

Let's go through it:

I       Read one line of input.
Y       Unzip. Separates the string into even and odd positions.
' *     Append a space to the odd half.
m       Truncate: discards characters from the longer of the two
        strings until they're the same length. So if the input
        length was even, appending a space will make the odd half
        longer and this discards the space again. Otherwise, the
        space just padded the odd half to the same length as the
        even half and this does nothing.
R       Reverse the odd half.
w       Push the current IP address to the return address stack.
        The purpose of this is to run the following section
        exactly twice.

          This first part splits the current line in half, based
          on an idea of Leo's:
  ..        Make two copies of the current half.
  Y         Unzip one of the copies. The actual strings are irrelevant
            but the important part is that the first string's length
            will be exactly half the original string's length (rounded up).
  ;         Discard the potentially shorter half.
  m         Truncate on the original string and its even half. This shortens
            the original string to the first half of its characters.
  ;         Discard the even half, because we only needed its length.
  .!        Store a copy of the first half on the tape.
  z         Drop. Use the first half to discard it from the original string.
            This gives us the the second (potentially shorter half).
  ?         Retrieve the first half from the tape.
  ~         Swap it so that the second half is on top.
          The string has now been split in half.
  R       Reverse the second half.
  Z       Zip. Interleave the two halves.
  O       Print the result with a trailing linefeed.

k       Pop an address from the return address stack and jump back there.
        The second time we reach this, the return address stack is empty,
        and this does nothing.
@       Terminate the program.


How much code would a codegolf golf if a codegolf could golf code?

Python 3, 70 67 bytes

"How much {0} would a {0}{1} {1} if a {0}{1} could {1} {0}?".format

Try it online!

I mean, if the shoe fits..

Thanks to manatwork for catching a typo

Thanks to Remco Haszing for the excellent -3 bytes idea

I am running off of the assumption that this would still be a valid submission (because man, it's too cool not to try). If OP could clarify whether this is acceptable (because I haven't written a function, per se), that would be appreciated.

Update: Blessing received, all is good :)

Previous version:

lambda a,b:f"How much {a} would a {a+b} {b} if a {a+b} could {b} {a}?"


Mathematica, 112 111 bytes
-5 byte thanks to Mark S. and LegionMammal978!
-22 bytes (and noticing a problem with the output) thanks to ngenisis!
Tr[1^Entity["AdministrativeDivision",#~StringDelete~" "]@"BorderingStates"]+Boole@StringMatchQ[#,"Il*"|"Mic*"]&

Of course, there's a Mathematica builtin for it. Includes D.C. in the count.


Is there are exactly one partition, given length of partition and maximum number?

Python 2, 38 bytes

lambda n,k,m:m>n-k<2or-1<k*m-n<2+2/m*k

Try it online!

Characterizes the cases where there's only one legal partition.

Consider the partitions of \$n\$ into exactly \$k\$ parts each between \$1\$ and \$m\$ inclusive. There's only two ways to for there to be only one such partition.

The number \$n\$ is close to as small as possible (\$n=k\$ or \$n=k+1)\$ or as large as possible (\$n=mk-1\$ or \$n=mk)\$ for such a partitions. This leave only enough "wiggle room" for only one partition in each case:

\$n=1+1+\cdots +1+1\$.
\$n=2+1+\cdots+1+1\$.
\$n=m+m+\cdots+m+(m-1)\$.
\$n=m+m+\cdots+m+m\$.

We allow only \$m=2\$ maximum, forcing a unique partition made of 1's and 2's. Such a partition requires \$k \leq n \leq 2k\$.

The challenge lets us assume that \$n>k\$, so we can omit the \$n=k\$ case and \$k \leq n\$ check, and, as feersum observed, can let us check \$n=k+1\$ as \$n<k+2\$.  The \$m=1\$ case makes it impossible to make a partition with \$n>k\$, so we make sure it's always rejected. This gives the condition

  \$n \in \{ k+1, mk-1, mk\}\$and \$ m>1\$, or \$n \leq 2k \$ and \$m=2\$


Ruby, 171

->w{s=[0]*8
w.chars.flat_map{|c|z=0..7
*m,i=z.map{|j|z.select{|k|s[k]!=z.map{|i|c.ord[i]}.rotate(j)[k]}<<j}.min_by &:size
m.map{|m|s[m]=1-s[m];"t #{7-m}"}+["p #{i}"]}*?\n}

A Ruby function that's only double the size of the reference implementation. :)

Try it online: http://ideone.com/ysYyFP

The program is pretty straighforward: it starts off with the 8 bits set to 0 and iterates through the characters. At each step, it takes the shortest route from the current state to a state that would allow printing the character. It returns a string in the specified format.

The initial (less golfed) version of the program is available here.


Better way to read multiple int in C than scanf

You can write a function instead of a program as your submission. In C you can omit int from function signatures:

f(w,x,y,z){}


05AB1E, 17 16 14 11 bytes

ā°`<Ÿʒ.L}pO

Explanation:

ā             Push inclusive range from 1 to the length of the input
 °            Raise 10 to the power of each element
  `           Push each element to the stack
   <          Decrement the topmost element
    Ÿ         Inclusive range
              For 13, this creates an array like [10 11 12 13 14 .. 98 99]
     ʒ.L}     Only keep elements with a levenshtein distance to the input of
              exactly one
         p    Check each element for primality
          O   Sum

Try it online! or up to 100.


CJam (22 bytes)

{):X),3m*{:+X=},Xdff/}

This is an anonymous block (function) which takes N on the stack and leaves an array of arrays of doubles on the stack. Online demo

Dissection

{         e# Define a block
  ):X     e# Let X=N+1 be the number of segments per edge
  ),3m*   e# Generate all triplets of integers in [0, X] (inclusive)
  {:+X=}, e# Filter to those triplets which sum to X
  Xdff/   e# Normalise
}


Minimise the count of prime factors through insertion

Husk, 16 bytes

§◄öLpr§·++⁰↑↓oΘŀ

Expects input as strings, try it online!

Explanation

§◄(öLpr§·++⁰↑↓)(Θŀ)  -- input A implicit, B as ⁰ (example "1234" and "32")
§ (           )(  )  -- apply A to the two functions and ..
  (ö          )      --   | "suppose we have an argument N" (eg. 2)
  (    §      )      --   | fork A and ..
  (         ↑ )      --     | take N: "12"
  (          ↓)      --     | drop N: "34"
  (     ·++⁰  )      --   | .. join the result by B: "123234"
  (   r       )      --   | read: 123234
  (  p        )      --   | prime factors: [2,3,19,23,47]
  ( L         )      --   | length: 5
  (öLpr§·++⁰↑↓)      --   : function taking N and returning number of factors
                            in the constructed number
               ( ŀ)  --   | range [1..length A]
               (Θ )  --   | prepend 0
               (Θŀ)  --   : [0,1,2,3,4]
 ◄                   -- .. using the generated function find the min over range


Jelly, 6 bytes

D!SµÐĿ
    ÐĿ  Repeat until the results are no longer unique. Collects all intermediate results.
D           Convert from integer to decimal (list of digits)
 !          Factorial (each digit)
  S         Sum

Try it online!

I don't see any other way to make it shorter other than to do as told.

Specs

Input: 132 (as command-line argument)
Output: [132, 9, 362880, 81369, 403927, 367953, 368772, 51128, 40444, 97, 367920, 368649, 404670, 5810, 40442, 75, 5160, 842, 40346, 775, 10200, 6, 720, 5043, 151, 122, 5, 120, 4, 24, 26, 722, 5044, 169, 363601, 1454]


Python, 67

a=lambda x:sum(i for i in range(1,x)if x%i<1)
b=lambda x:x==a(a(x))


Make An ASCII Poker Chip Stack Arrangement

JavaScript (ES6), 185 177 ... 171 bytes

f=(a,s='')=>(a=(a[0]?a:[...(m='25455')+m+m].map((m,i)=>(a-=(k=a/(v/=m)|0)*v,k*16+i),v=1E9).sort((a,b)=>b-a)).map(n=>n>15&&(s+='SVTILAMCOPYBGRW'[n&15],n-16)),s&&f(a)+`
`+s)

Formatted and commented

(a, s = '') => (                           // a = bankroll OR array of chip stacks
  a = (                                    // s = string of chip initials for this iteration
    a[0] ?                                 // if 'a' already is an array:
      a                                    // use it as-is
    :                                      // else, 'a' is the bankroll:
      [...(m = '25455') + m + m]           // for each 'm' in [ 2, 5, 4, 5, 5, ... ] (x3)
      .map((m, i) =>                       // v = current chip value = previous value / m
        (                                  // k = floor(a / v) = number of these chips
          a -= (k = a / (v /= m) | 0) * v, // update remaining bankroll: a = a - k * v
          k * 16 + i                       // saved in array: chip index in bits 0-3
        ),                                 // and number of chips in bits 4+
        v = 1E9                            // initial chip value = 1 billion
      )                                    // (1B / 2 -> 500M, 500M / 5 -> 100M, etc.)
      .sort((a, b) => b - a)               // sort the chip stacks
  )                                        //
  .map(n =>                                // for each chip stack:
    n > 15 &&                              // if there's at least one remaining chip of
    (                                      // this kind:
      s += 'SVTILAMCOPYBGRW'[n & 15],      // append its initial to the string
      n - 16                               // decrement the number of chips in this stack
    )                                      //
  ),                                       // process recursive call if there was at least
  s && f(a) + '\n' + s                     // one non-empty chip stack (the next lines are
)                                          // appended at the beginning of the final string)

Demo

let f=(a,s='')=>(a=(a[0]?a:[...(m='25455')+m+m].map((m,i)=>(a-=(k=a/(v/=m)|0)*v,k*16+i),v=1E9).sort((a,b)=>b-a)).map(n=>n>15&&(s+='SVTILAMCOPYBGRW'[n&15],n-16)),s&&f(a)+`
`+s)

function update() {
  document.getElementById('o').innerHTML = f(+document.getElementById('i').value);
}
update();
<input id="i" value="1342185143" oninput="update()">


JavaScript (ES6), 91 bytes
Takes input as (cost)(lands):

\$cost\$ is a list of characters in BGRUW order, prefixed with the generic part, even when it's \$0\$
\$lands\$ is a list of strings.

a=>g=([c,...r],n=0,s=e='')=>[...n+s].sort()+e==a|(c&&[e,e,...c].some((c,i)=>g(r,n+!i,s+c)))

Try it online!
Commented
a =>                        // main function taking the array a[] describing the cost
  g = (                     // g = recursive function taking:
    [c, ...r],              //   c = next land string; r[] = remaining land strings
    n = 0,                  //   n = generic mana, initialized to 0
    s = e = ''              //   s = generated cost string, initialized to e = empty string
  ) =>                      //
    [...n + s].sort() + e   // prepend n to s, split, sort and force coercion to a string
    == a | (                // if this is matching a[], the test is successful
      c &&                  // if c is defined:
      [                     //   try the following recursive calls:
        e,                  //     - increment n and append nothing to s
        e,                  //     - do nothing
        ...c                //     - leave n unchanged and append a character to s
      ].some((c, i) =>      //   for each c at position i in the above array:
        g(r, n + !i, s + c) //     process the recursive call
      )                     //   end of some()
    )                       // end of the recursive part