Go to opposite corner of rectangle in all directions - Harder

Pyth, 46 45 44 bytes

eSKtMQjsM_mm?sJ,kd?q#J.umtWbbNeSKK\#\.\XhQeQ

Try it here.

Explanation:

move-count-printing:

  K     assign K to...
     Q  the input, a 2-length array...
   tM   with each element decremented
eS      take the max and output it (this is the number of moves)

main path-finding logic:

    mm                     hQeQ  map over x-values and y-values...
        J,kd                     assign J to [x,y]
      ?s                         if both x and y are NOT zero (sum is truthy)...
            ?q#J[...]              if [x,y] is present in [...] (see below)...
                     \#            ... put a # at this position in the output
                       \.          ... else, put a . at this position
                         \X      ... else, put the X here (at [0,0])
jsM_                             reverse and output in the proper format

the [...] part in the code above, which finds positions where #s go:

.u      eSKK  cumulative reduce on <number of moves> elements, starting at K,
                which is [max_x, max_y] as assigned at the beginning
  m    N      map over x and y...
   tWbb       decrement, only if the value is > 0


Compute number of matrices with appropriate sums

JavaScript (ES7), 163 bytes

f=([R,...x],s)=>1/R?[...Array(R**s.length)].reduce((k,_,n)=>(a=s.map((_,i)=>n/R**i%R|0)).some(c=>(p+=c<<++j)>R,p=j=0)?k:k+f(x,s.map((v,i)=>v-a[i])),0):!/-/.test(s)

Test cases

NB: I've removed the two most time-consuming test cases from this snippet, but they should pass as well.

f=([R,...x],s)=>1/R?[...Array(R**s.length)].reduce((k,_,n)=>(a=s.map((_,i)=>n/R**i%R|0)).some(c=>(p+=c<<++j)>R,p=j=0)?k:k+f(x,s.map((v,i)=>v-a[i])),0):!/-/.test(s)

console.log(f([1],[2]))            // 1
console.log(f([2],[1]))            // 2
console.log(f([4],[1,1]))          // 3
console.log(f([2,4],[1,1]   ))     // 5
console.log(f([3,5,7],[1,2]))      // 14
console.log(f([7,10],[1,1,1]))     // 15
console.log(f([7,8],[3,3,1]))      // 44
console.log(f([2,6,7,16],[1,3,2])) // 128
console.log(f([2,7,16],[3,3,1,1])) // 175

Commented

f = (                               // f = recursive function taking:
  [R,                               //   - the input array r[] splitted into:
      ...x],                        //     R = next element / x = remaining elements
  s                                 //   - the input array s[]
) =>                                //
  1 / R ?                           // if R is defined:
    [...Array(R**s.length)]         //   for each n in [0, ..., R**s.length - 1],
    .reduce((k, _, n) =>            //   using k as an accumulator:
      (a =                          //     build the next combination a[] of
        s.map((_, i) =>             //     N elements in [0, ..., R - 1]
          n / R**i % R | 0          //     where N is the length of s[]
        )                           //
      ).some(c =>                   //     for each element c in a[]:
        (p += c << ++j)             //       increment j; add c * (2**j) to p
        > R,                        //       exit with a truthy value if p > R
        p = j = 0                   //       start with p = j = 0
      ) ?                           //     end of some(); if truthy:
        k                           //       just return k unchanged
      :                             //     else:
        k +                         //       add to k the result of
        f(                          //       a recursive call to f() with:
          x,                        //         the remaining elements of r[]
          s.map((v, i) => v - a[i]) //         s[] updated by subtracting the values of a[]
        ),                          //       end of recursive call
      0                             //     initial value of the accumulator k
    )                               //   end of reduce()
  :                                 // else:
    !/-/.test(s)                    //   return true if there's no negative value in s[]


Jelly, 3 bytes

x`X

Try it online!

Look 'ma, no Unicode!

Explanation:

x`X
 `  Make monad from dyad and use same left and right arguments
x   Repeat each element of the left argument (implicit) list its respective number of times in the right argument list
  X Random element


CJam, 34 31 bytes
8,q{~2*f{_@-_zF8b&,@@+8,=*}0-}/

Did this on my phone, so I'll have to put up an explanation later. Output is nonempty iff truthy.
Try it online | Test suite
Explanation
The new code shifts the layout a little:
2    3    4

1    .    5

0/8  7    6

Even numbers correspond to string positions and odd numbers correspond to crank positions.
Here's what happens:
8,           Create the range [0 1 .. 7] of possible starting positions
             We can leave the string positions [0 2 4 6] in since it doesn't matter
q{ ... }/    For each character in the input...
  ~2*          Evaluate as integer and double, mapping "1234" -> [2 4 6 8]
  f{ ... }     Map over our possible current crank positions with the string
               position as an extra parameter
    _@-          Calculate (string - crank), giving some number in [-7 ... 7]
    _z           Duplicate and absolute value
    F8b          Push 15 base 8, or [1 7]
    &,           Setwise intersection and get length. If (string - crank) was in
                 [-7 -1 1 7] then the move was valid and this evaluates to 1, otherwise 0
    @@+          Calculate ((string - crank) + string)
    8,=          Take modulo 8, giving the new crank position. x%y in Java matches the
                 sign of x, so we need to do ,= (range + index) to get a number in [0 .. 7]
    *            Multiply the new crank position by our previous 0 or 1
  0-           Remove all 0s, which correspond to invalid positions

The stack is then automatically printed at the end. Any possible ending positions will be in the output, e.g. for the input 1 the output is 31, which means the crank can end facing either left or up.
If only CJam had filter with extra parameter...

Edit: Temporarily rolling back while I convince myself that this 29-byte works:
8,q{~2*f{_@-_7b1#@@+8,=|}W-}/


Powershell, 71 68 65 Bytes

Similar to https://codegolf.stackexchange.com/a/101357/59735

Saved 3 bytes by not being an idiot (left the ... on loading)

-3 thanks to VisualMelon

changed 750 -> 751 to make sure 750 is included.

0..100|%{cls;"loading $("|/-\"[$_%4]) $_ %";sleep -m(random 751)}

Explanation:

0..100|%{                                  #For range 0-100...
    cls                                    #Clear Display
    "loading $("|/-\"[$_%4]) $_ %"    #Display the current string
    sleep -m(random 750)                  #Sleep random ms up to 750
}

Updated gif


TI-Basic, 94 bytes
"
Repeat 99<length(Ans
Ans+"-
End
Ans→Str1
Repeat 0
getTime
ClrDraw
Ans{Ans(1)≠24,1,1
Text(0,0,Ans(1),sub(Str1,1,1+Ans(2
Text(6,0,Ans(1)+1,sub(Str1,1,61-Ans(2
End

Relatively straightforward. That's a string with one space at the beginning. The hours are right-aligned. This only works on TI-84+ calculators since the TI-83 does not have an internal clock.
Edit: Thanks @kundor for noticing that I didn't close the last loop. Fixed now (+2 bytes).
Edit #2: First hour should be zero, not twenty-four. Corrected at a cost of +14 bytes.


Retina, 57 49 bytes

.+
$*
(^1|1\1)+$
1
(^1|1\1)+(1(?(2)\2))+$
2
11+
3

Try it online! Based on my answer to Three triangular numbers. Change the third line to ^(^1|1\1)*$ to support zero input. Edit: Saved 8 (but probably should be more) bytes thanks to @MartinEnder.


JavaScript (ES6), 81 80 bytes
Takes input in currying syntax (modify)(modifier).

s=>g=([c,...a],d=i=0,x=s[k=parseInt(c,36),i+=c?d&&(k-d+26)%26:1])=>x?x+g(a,k):''

Try it online!
Commented
s =>                       // outer function, taking the string s to modify
  g = (                    // recursive inner function g(), taking:
    [c, ...a],             //   c = current modifier character; a[] = remaining characters
    d = i = 0,             //   d = code of previous modifier character; i = pointer in s
    x = s[                 //   x = i-th character of s
      k = parseInt(c, 36), //     k = code of the current modifier character in [10..35]
      i += c ?             //     update i; if c is defined:
        d &&               //       if d = 0, let i unchanged
        (k - d + 26) % 26  //       otherwise, add the difference between k and d (mod 26)
      :                    //     else:
        1                  //       just pick the next character by adding 1
    ]                      //   end of character lookup in s
  ) =>                     //
    x ?                    // if x is defined:
      x + g(a, k)          //   append x and do a recursive call to g()
    :                      // else:
      ''                   //   stop recursion


Does the sum of 2 numbers in the list equal the desired sum?

Brachylog, 3 bytes

⊇Ċ+

Try it online!

⊇Ċ+   input as STDIN, output as ARG1
      (prove that:)
⊇     the input is a superset of
 Ċ       a list of two elements
  +         which sums up to the output


HTML + CSS + JavaScript, 39 + 141 + 20 = 200 bytes

Outputs visually to the webpage. To allow this to work with special elements like , all letters in the input are replaced.

p.innerHTML=prompt().replace(/\w/g,'a')
#p,#p *{display:flex;padding:0 0 1rem;align-items:flex-end;font-size:0}#p :before,#p :after{content:'/';font-size:1rem}#p :after{content:'\\'

HTML + CSS + JavaScript, 10 + 103 + 20 = 133 bytes

Solution that works if there is no content within tags.

p.innerHTML=prompt()
#p,#p *{display:flex;padding:0 0 1em;align-items:flex-end}#p :before{content:'/'}#p :after{content:'\\'


Collection from a sequence that constitute a perfect square

05AB1E, 10 bytes
Ý¨n6*æʒOÅ²

Try it online!
How?

Ý¨n6*æʒOÅ² || Full program. I'll call the input N.

Ý          || 0-based inclusive range. Push [0, N] ∩ ℤ.
 ¨         || Remove the last element.
  n        || Square (element-wise).
   6*      || Multiply by 6.
     æ     || Powerset.
      ʒ    || Filter-keep those which satisfy the following:
       O   ||---| Their sum...
        Å² ||---| ... Is a perfect square?


Vim, 8 bytes

o <Esc><C-V>{r*J

Takes input in the readahead buffer, so if input is 15, you would type that and then the code above. This is a silly rule, but seems to be allowed. If you got input in a register like "a, you'd just stick @a in front (10). If you got it from the start file, you'd prepend D@" instead (11).

Relies on abuse of :set autoindent, which is default in vimgolf.com rules and default in Vim 8 (and everyone uses it anyway).

o <Esc>: With its number argument, if your text starts with whitespace, and you have :set autoindent, Vim glitches out and creates a cascade of indent.
<C-V>{r*: Turn all those spaces into *s. I'm using block visual so that, even if your lousy indent settings silently group your spaces into tabs, you'll still get the right number of *s.
J: Starting with o unfortunately left a blank line at the top. This removes it.


C++, 564 bytes

#include <iostream>
#include <algorithm>
#include <ctime>
#include <cstdlib>
#include <vector>
using namespace std;int main(){int n,p,s=0,y,i=0,b;cin>>n>>b;if(n<5)n=5;vector<int>m(n*n,1);srand(time(0));if(b)for(int&c:m)c=rand()<RAND_MAX/6;for(;i<n*n;i++)cout<<m[i]<<(-~i%n?"":"\n");while(find(m.begin(),m.end(),1)!=m.end()){cin>>p>>y;p+=y*n;if(p<0||p>=n*n)continue;m[p]=!m[p];if(p%n)m[p-1]=!m[p-1];if(p%n+1<n)m[p+1]=!m[p+1];if(p>=n)m[p-n]=!m[p-n];if(p+n<n*n)m[p+n]=!m[p+n];for(i=0;i<n*n;i++)cout<<m[i]<<(-~i%n?"":"\n");s++;}cout<<"Solved in "<<s<<" steps."<<endl;}

In setup phase, the user should input the grid size first. Then if the grid should starts with all of the lights on, the user should input 0; otherwise 1.

In play phase, the user should input the 0-based coordinates of the cell to toggle until all lights off.

Original code:

#include <iostream>
#include <algorithm>
#include <ctime>
#include <cstdlib>
#include <vector>
using namespace std;
int main() {
    int n, p, s = 0, y, i = 0, b;
    cin >> n >> b;
    if(n < 5) n = 5;
    vector<int> m(n * n, 1);
    srand(time(0));
    if (b) for (int& c : m) c = rand() < RAND_MAX / 6;
    for (; i < n * n; i++) cout << m[i] << (-~i % n ? "" : "\n");
    while (find(m.begin(), m.end(), 1) != m.end()) {
        cin >> p >> y;
        p += y * n;
        if (p < 0 || p >= n * n) continue;
        m[p] = !m[p];
        if (p % n) m[p - 1] = !m[p - 1];
        if (p % n + 1 < n) m[p + 1] = !m[p + 1];
        if (p >= n) m[p - n] = !m[p - n];
        if (p + n < n * n) m[p + n] = !m[p + n];
        for (i = 0; i < n * n; i++) cout << m[i] << (-~i % n ? "" : "\n");
        s++;
    }
    cout << "Solved in " << s << " steps." << endl;
}


Python 3, 400 393 390 bytes

L=len
S,*K=' ┴┼│123456789'
def T(x):
 try:return[str(x+0)]
 except:
  z=[*map(T,x)];q=max(map(L,z))
  for p in z:p+=[S*L(p[0])]*(q-L(p))
  b=[S.join(a)for a in zip(*z)];t=b[0];l=L(t);s=0;e=L(z);r=[S]*l
  if e<2:return['│'.center(l),*b]
  for i in range(l):
   if t[i]in K:s+=1;r[i]='┬┌┐'[(s<e)-(s>1)]
   elif 0<s<e:r[i]='─'
  c=l//2;r[c]=K[r[c]=='┬'];return[''.join(r),*b]

Returns a list of strings from top to bottom.

EDIT 1: Trimmed 7 bytes by avoiding duplication of ┴┼ (net save of 2 bytes), cutting out 0 from the one string, changing how drawing characters are selected from ┬┌┐ (use < instead of ==), and replacing a L(z) I missed with e

EDIT 2: -2 bytes thanks to ovs and -1 byte thanks to Kevin Cruijssen

Try it online!

Ungolfed

def layer(item):
    if isinstance(item, int):
        return [str(item)]
    else:
        subs = [layer(sub) for sub in item]
        longest = max(map(len, subs))
        for sub in subs:
            sub += [' ' * len(sub[0])] * (longest - len(sub))
        below = [' '.join(l) for l in zip(*subs)]
        top = below[0]
        l = len(top)
        if len(subs) == 1:
            return ['│'.center(l), *below]
        seen = 0
        expected = len(subs)
        builder = [' '] * l
        for i in range(l):
            c = top[i]
            if c in '┴┼│123456789':
                seen += 1
                if seen == 1:
                    builder[i] = '┌'
                elif seen == expected:
                    builder[i] = '┐'
                else:
                    builder[i] = '┬'
            elif 0 < seen < expected:
                builder[i] = '─'
        center = l // 2
        if builder[center] == '┬':
            builder[center] = '┼'
        else:
            builder[center] = '┴'
        return [''.join(builder), *below]

Builds a tree from the leaves up, one layer at a time.


Indices of elements in an array in order from smallest to largest

Haskell, 41 bytes

f l|z<-zip l[0..]=[sum[1|q<-z,p>=q]|p<-z]

Try it online!

Haskell doesn't have build-in sorting, so we have to roll up our sleeves. We pair each element with its index with z<-zip l[0..], then for each pair counts the number of pairs that are smaller or equal. This first compares the values, then tiebreaks by their index.


Wolfram Language (Mathematica), 33 bytes

Uses Binomial and outputs ,really fast, fractions

Tr@Binomial[#,Prime@Range@#]/2^#&

Try it online!

The original code according to my formula was

Tr@Binomial[#,Prime@Range@PrimePi@#]/2^#&

but, as @attinat commented, instead of searching all Primes < n  we can
search the first n primes because every prime > n returns zero binomial.
In this way we save 8 bytes

Here is also the graph of the first 1000 cases which looks pretty cool


Find the program that prints this integer sequence (Robbers' thread)

MATL, 5 bytes, Luis Mendo
H5-*|

This code calculates abs((2-5)*input) which is just a(n)=3*n for positive numbers, which is http://oeis.org/A008585


The most pointless shell command you can concoct, based upon a often used shell command

Mine is the inverse of "print the kernel arguments you booted with on Linux":

cat /proc/cmdline
# turns into...
fgrep -x -f <(awk -F\= 'BEGIN { RS = " "} ; {print $1"="}' </proc/cmdline)\
-v <(curl 'https://www.kernel.org/doc/Documentation/kernel-parameters.txt'
2>/dev/null | awk '/\t+[a-z._]+=/ {print $1}' | tee test2) | tr '\n' ' ' &&
echo


Jelly, 9 bytes

ÆE²Sḍ2µ#Ṫ

Reads from STDIN and uses 1-based indexing. Try it online!

How it works

ÆE²Sḍ2µ#Ṫ  Main link. No arguments. Implicit argument: 0

      µ#   Read an integer n from STDIN and execute the chain to the left for
           k = 0, 1, 2, ... until n of them return a truthy value.
           Return the array of matches.
ÆE           Compute the exponents of k's prime factorization.
  ²          Square each exponent.
   S         Compute the sum of all squares.
    ḍ2       Test if 2 is divisible by the result (true iff  the sum is 1 or 2).
        Ṫ  Tail; extract the last (n-th) matching value of k.


JavaScript (ES6) 345

Not sure about the numbers, but here is my attempt.

Test running the snippet below in an EcmaScript compliant browser.

why=n=>(n<1?n=Math.random()*840|0:0,s="suggested,insisted on,did,fool,satisfy,please,stupid,smart,bald,tall,rich,Don't ask!,How should I know?,Stop asking!,Stewie,Peter,Homer,programmer,system manager,You".split`,`,n%7?(p=s[n%7+13],n&1?(p>'a'?'The ':'')+p+` ${s['2011'[-~n/2%4]]} it!`:`To ${s['5344'[n%8/2]]} the ${s[n/2%5+6]} ${p}!`):s[11+n%3])

for(o='',i=0;++i<1e3;)o+=i+':'+why(i)+'\n';O.innerHTML=o

function test() { R.innerHTML=why(+I.value) }

// Less golfed

WHY=n=>(
  n=n<1?Math.random()*999|0:n,
  s=["suggested", "insisted on", "did", "fool", "satisfy", "please",
     "stupid", "smart", "bald", "tall", "rich",
     "Don't ask!", "How should I know?", "Stop asking!",
     "Stewie", "Peter", "Homer", "programmer", "system manager", "You"],
  n%7
    ? ( p=s[n%7+13],
        n&1
        ? (p>'a'?'The ':'')+p+` ${s['2011'[-~n/2%4]]} it!`
        : `To ${s['5344'[n%8/2]]} the ${s[n/2%5+6]} ${p}!`)
    : s[11+n%3]
)
#O { height:300px; width:50%; overflow:auto }
#I { width:2em }
Why(<input id=I>)<button onclick=test()>-></button>


f(g(x)) decreases while g(f(x)) increases

Python, 68 characters
f=lambda x:(1-x%2*2)*(2*x*x+(x<0))
g=lambda x:(1-x%2*2)*(2*x*x+(x>0))

f maps negative numbers to odd numbers and positive numbers to even numbers, and even numbers to positive numbers and odd numbers to negative numbers, with the output magnitude increasing strictly with the input magnitude.
g does the same, except it maps negative numbers to even numbers and positive numbers to odd numbers.
f ∘ g maps negative → even → positive and positive → odd → negative.
g ∘ f maps negative → odd → negative and positive → even → positive.
Therefore f and g have the desired properties.


C++, score = 33.526203, all test cases in 2min34s
(of course, the score can be improved by running the program for more time; please do not do that to claim a victory or something)
That score is usually 11 won districts for the Republicans and from 9 to 11 for the Democrats.
In this revision, the score decreased significantly, because I found some really large bugs in the input parsing. My program also verifies its solution now.
//#define _GLIBCXX_DEBUG
#include <iostream>
#include <streambuf>
#include <iomanip>
#include <fstream>
#include <cstring>
#include <bitset>
#include <cassert>
#include <cstdio>
#include <vector>
#include <algorithm>
#include <cmath>
#include <climits>
#include <random>
#include <set>
#include <map>
#include <deque>
#include <string>

constexpr uint64_t rotl(uint64_t x, char k)
{
    return (x<<k) | (x>>(64-k)); //typo of the day: replace the >> with <<
}
uint64_t xs128()
{
    static uint64_t s_0 = 0, s_1 = 1;
    const uint64_t s0 = s_0;
    uint64_t s1 = s_1;
    uint64_t res = s0 + s1;
    s1 ^= s0;
    s_0 = rotl(s0, 24) ^ s1 ^ (s1 << 16);
    s_1 = rotl(s1, 37);
    return res >> 4;
}
std::vector<std::string> getCsvLine(std::istream& str)
{
    https://stackoverflow.com/a/1120224 - saved some time writing a parser...
    std::vector<std::string> result;
    std::string line; std::getline(str,line);
    std::stringstream lineStream(line);
    std::string cell;
    while(std::getline(lineStream,cell, ','))
        result.push_back(cell);
    return result;
}
struct county
{
    int good = 0;
    int sum = 0;
    std::vector<int> others;
    std::string name;
};
struct district
{
    int good = 0;
    int sum = 0;
    std::vector<int> others;
    void operator += (county& rhs)
    {
        good += rhs.good; sum += rhs.sum;
        for(int i = 0; i < others.size(); i++)
            others[i] += rhs.others[i];
    }
    void operator -= (county& rhs)
    {
        good -= rhs.good; sum -= rhs.sum;
        for(int i = 0; i < others.size(); i++)
            others[i] -= rhs.others[i];
    }
};
//seems like exactly 100 districts exist, below CHAR_MAX
std::vector<std::vector<char>> graph;
std::vector<char> curdistrict;
std::vector<county> counties;
std::vector<district> districts;
std::vector<char> marks;
bool pluralityCheck(const district& d)
{
    return d.good > *std::max_element(d.others.begin(), d.others.end());
}
int n, k, excluded;
double getFitness(std::vector<char>& dmap)
{
    std::vector<district> districts(k);
    for(district& d : districts)
        d.others.resize(counties[excluded==0?1:0].others.size());
    for(int i = 0; i < n; i++)
        if(i != excluded) districts[dmap[i]] += counties[i];
    double score = 0;
    int min = INT_MAX, max = INT_MIN;
    for(int i = 0; i < k; i++)
        score += pluralityCheck(districts[i]),
        min = std::min(min, districts[i].sum), max = std::max(max, districts[i].sum);
    score -= double(max) / min;
    return score;
}
void dfs(char v, char color)
{
    marks[v] = color;
    for(int to : graph[v])
        if(marks[to] != color && curdistrict[to] == curdistrict[v])
            dfs(to, color);
}
bool dfsFor(char at, char target, char color)
{
    marks[at] = color;
    if(at == target) return true;
    if(at == excluded) return false;
    bool ans = false;
    for(int to : graph[at])
        if(marks[to] != color && curdistrict[to] == curdistrict[at])
            ans |= dfsFor(to, target, color);
    return ans;
}
bool isCutpoint(int v)
{
    static int call = 0;
    char color = call + 1;
    call = (call + 1) % 255;
    if(color == 1) for(char& el : marks) el = 0; //reset every 256 calls
    marks[v] = color;
    int calls = 0;
    for(char to : graph[v])
    {
        if(curdistrict[to] != curdistrict[v]) continue;
        if(marks[to] == color) continue;
        calls++;
        if(calls == 2) break;
        dfs(to, color);
    }
    return calls != 1; //0 -> kills a district, >=2 -> a cutpoint -> splits a district
}
std::map<std::string, int> dnamemap;
double solve(int n, int k, int target, int excluded)
{
    ::n = n; ::k = k; ::excluded = excluded;
    marks = std::vector<char>(n);
    curdistrict = std::vector<char>(n, -1); graph = std::vector<std::vector<char>>(n);
    districts = std::vector<district>(k); counties = std::vector<county>(n);
    dnamemap = std::map<std::string, int>();
    std::ifstream data("NC_2016_presidential_election.csv");
    getCsvLine(data); //skip header
    for(int i = 0; i < n; i++)
    {
        std::vector<std::string> row = getCsvLine(data);
        dnamemap[row[0]] = i;
        counties[i].name = row[0];
        if(i == excluded) continue;
        for(int j = 1; j < row.size(); j++)
        {
            int v = std::stoi(row[j]);
            if(j - 1 == target)
                counties[i].good = v;
            else counties[i].others.push_back(v);
            counties[i].sum += v;
        }

    }
    data = std::ifstream("NC_county2.csv"); //no header
    //NC_county2.csv is obtained by cat NC_county_adjacency.csv | sort | tr -d '\r'
    //the default counties file caused not one but TWO horrible parsing bugs
    //they silently increased the score.
    //There were \r\n line endings instead of \n, and my program mishandled them.
    //and *the worst*. It seems to be in alphabetic order, but it actually simply isn't.
    for(int i = 0; i < n; i++)
    {
        std::vector<std::string> row = getCsvLine(data);
        if(i == excluded) continue;
        for(int j = 1; j < row.size(); j++)
        {
            if(row[j] == row[0]) continue;
            int to = dnamemap[row[j]];
            if(to == excluded) continue;
            graph[i].push_back(to);
        }
    }
    for(district& d : districts)
        d.others.resize(counties[excluded==0?1:0].others.size());
    int di = 0;
    for(int i = 0; di < k; i++) if(i != excluded) curdistrict[i] = di++;
    for(int it = n; it --> 0;)
        for(int i = 0; i < n; i++)
        {
            if(i == excluded || curdistrict[i] != -1) continue;
            for(int to : graph[i])
            {
                if(to == excluded || curdistrict[to] == -1) continue;
                curdistrict[i] = curdistrict[to];
                break;
            }
        }
    if(excluded >= 0) curdistrict[excluded] = -1;
    for(int i = 0; i < n; i++) printf("%d ", curdistrict[i]);
    printf("%d\n", excluded);
    for(int i = 0; i < n; i++) if(excluded != i) districts[curdistrict[i]] += counties[i];
    double temp = 3;
    int its = 2e7;
    std::vector<char> bestplacement = curdistrict;
    std::vector<district> bestdistricts = districts;
    int lastimprovement = 0;
    double bestscore = getFitness(curdistrict);
    int perblock = 2e4; //max number of iterations without improvement
    double delta = 1.01 * temp / its;
    double curscore = bestscore;
    double withoutimprovement = 0;
    for(int it = 0; it < its; it++)
    {
        temp -= delta;
        if(it % 1048576 == 0)
            printf("it=%d, cs=%lf       \r", it, curscore);
        int i = xs128() % n;
        while(i == excluded) i = xs128() % n;
        if(isCutpoint(i)) continue; //<- around 50% of program time
        std::vector<int> nearby;
        bool ok = false;
        for(int to : graph[i])
            if(curdistrict[to] != curdistrict[i] && curdistrict[to] != -1) ok = true;
        if(!ok) continue;
        int nd = -1;
        while(nd == curdistrict[i] || nd == -1)
            nd = curdistrict[graph[i][xs128() % graph[i].size()]];
        //calculate new min size, new max size etc.
        //can be done via std::set and other tree-based stuff, but it's much simpler to use a normal arrays (for k=13)
        //*might* use a segment tree to optimize later, but it's not spending a lot of time here
        char oldmaj1 = pluralityCheck(districts[curdistrict[i]]);
        char newmaj1 = pluralityCheck(districts[nd]);
        int maxs = INT_MIN, mins = INT_MAX;
        for(int i = 0; i < k; i++)
            maxs = std::max(maxs, districts[i].sum), mins = std::min(mins, districts[i].sum);
        double pen1 = double(maxs) / mins;
        districts[curdistrict[i]] -= counties[i];
        districts[nd] += counties[i];
        char oldmaj2 = pluralityCheck(districts[curdistrict[i]]);
        char newmaj2 = pluralityCheck(districts[nd]);
        maxs = INT_MIN, mins = INT_MAX;
        for(int i = 0; i < k; i++)
            maxs = std::max(maxs, districts[i].sum), mins = std::min(mins, districts[i].sum);
        double pen2 = double(maxs) / mins;
        double delta = pen1 - pen2 + (oldmaj2 + newmaj2 - oldmaj1 - newmaj1);
        if(delta <= 0 && (temp <= 0 || ldexpf(std::exp(delta / temp), 60) < xs128()))
        {
            districts[nd] -= counties[i], districts[curdistrict[i]] += counties[i];
        }
        else
        {
            curdistrict[i] = nd;
            curscore += delta;
            if(curscore > bestscore)
            {
                bestscore = curscore; lastimprovement = it;
                bestplacement = curdistrict; withoutimprovement = 0;
                bestdistricts = districts;
            }
        }
        if(curscore < bestscore) withoutimprovement += bestscore - curscore;
        if(it - lastimprovement > perblock || withoutimprovement > 3e4)
        {
            //restart at best score so far
            withoutimprovement = 0;
            lastimprovement = it;
            curdistrict = bestplacement;
            districts = bestdistricts;
            curscore = bestscore;
        }
    }
    for(int i = 0; i < n; i++)
        printf("%d ", curdistrict[i]);
    printf("\n");
    for(district& d : districts)
    {
        printf("%d total, maj=%d, %d good; rest:", d.sum, (int)pluralityCheck(d), d.good);
        for(int el : d.others) printf(" %d", el);
        printf("\n");
    }
    for(int i = 0; i < n; i++) //verify validness
    for(int j = i+1; j < n; j++)
    {
        if(i == excluded || j == excluded) continue;
        if(curdistrict[i] != curdistrict[j]) continue;
        for(char& el : marks) el = 0;
        bool good = dfsFor(i, j, 1);
        if(!good) printf("invalid: i=%d, j=%d, d=%d!\n", i, j, curdistrict[i]);
    }
    double score = getFitness(curdistrict);
    printf("%lf\n", score);
    return score;
}
int main()//int64_t argc, char*argv[])
{
    //randomly choose and recolor vertices
    //do not recolor a vertex if it is a cutpoint (more known as an articulation point or cut vertex) or alone
    //to check, DFS over same-colored vertices from it. If != 1 calls were done, it's alone or a cutpoint
    //initial state: all counties belong to district 0, but first 13 belong to district i (dumb but why bother)
    //for each district maintain the voters for both parties and total number
    //oh, and don't merely randomly recolor: use Simulated Annealing (TM) (it actually improves a lot!)
    setbuf(stdout, 0);
    int k = 13, n = 100;
    std::vector<int> toExclude { -1, 22, 28, 47, 50, 57, 61, 70, 82, 92, 97 }; //the final score computing
    //std::vector<int> toExclude { -1 };
    double score = 0;
    for(int el : toExclude)
    {
        double s = 0;
        s += solve(n, k, 0, el);
        s += solve(n, k, 1, el);
        if(el == -1) score += s;
        else score += s / 10;
    }
    printf("%lf\n", score);
}

Uses (attempts to use) simulated annealing to improve from a dumb assignment by making random changes if they do not ruin things (that is, destroy or split districts). Restarts from the best known assignment when either 20000 iterations passed without an improvement or the accumulated difference between the best score and the current score since the last improvement exceeds 30000.
Can be compiled with clang++ hax.cpp -Ofast -march=native -flto -no-pie -o a.out. Assumes files NC_2016_presidential_election.csv and NC_county2.csv are in the current directory, where NC_county2.csv is the NC_county_adjacency.csv, but with its lines actually sorted in alphabetical order, and with Unix (\n) line endings.
Quoting from the question, "you are encouraged to provide an illustration". I am definitely encouraged (I would really like to know whether or not the code has no bugs), but I have no idea how to create an illustration. I also have no idea how to export the output into a format readable by the linked website.
Assignment information on the normal map for the Democrats, then for the Republicans:

begin assignment for target=0, excluded=-1
Alamance,4
Alexander,8
Alleghany,8
Anson,12
Ashe,8
Avery,5
Beaufort,6
Bertie,6
Bladen,9
Brunswick,9
Buncombe,5
Burke,10
Cabarrus,8
Caldwell,8
Camden,7
Carteret,9
Caswell,0
Catawba,10
Chatham,12
Cherokee,10
Chowan,7
Clay,10
Cleveland,10
Columbus,2
Craven,9
Cumberland,2
Currituck,7
Dare,7
Davidson,12
Davie,8
Duplin,6
Durham,12
Edgecombe,6
Forsyth,3
Franklin,7
Gaston,10
Gates,7
Graham,10
Granville,0
Greene,6
Guilford,4
Halifax,7
Harnett,12
Haywood,10
Henderson,10
Hertford,7
Hoke,2
Hyde,7
Iredell,8
Jackson,10
Johnston,12
Jones,6
Lee,12
Lenoir,6
Lincoln,11
Macon,10
Madison,10
Martin,6
McDowell,5
Mecklenburg,11
Mitchell,5
Montgomery,12
Moore,12
Nash,7
New Hanover,9
Northampton,7
Onslow,9
Orange,0
Pamlico,9
Pasquotank,7
Pender,9
Perquimans,7
Person,0
Pitt,6
Polk,10
Randolph,4
Richmond,12
Robeson,2
Rockingham,0
Rowan,8
Rutherford,10
Sampson,9
Scotland,2
Stanly,8
Stokes,0
Surry,3
Swain,10
Transylvania,10
Tyrrell,7
Union,8
Vance,7
Wake,1
Warren,7
Washington,6
Watauga,5
Wayne,9
Wilkes,8
Wilson,6
Yadkin,8
Yancey,10
end assignment for target=0, excluded=-1
begin assignment for target=1, excluded=-1
Alamance,0
Alexander,1
Alleghany,11
Anson,7
Ashe,11
Avery,10
Beaufort,6
Bertie,6
Bladen,8
Brunswick,12
Buncombe,10
Burke,10
Cabarrus,7
Caldwell,11
Camden,9
Carteret,6
Caswell,0
Catawba,1
Chatham,2
Cherokee,4
Chowan,9
Clay,4
Cleveland,4
Columbus,12
Craven,9
Cumberland,8
Currituck,6
Dare,6
Davidson,0
Davie,7
Duplin,9
Durham,0
Edgecombe,9
Forsyth,1
Franklin,6
Gaston,4
Gates,9
Graham,10
Granville,6
Greene,6
Guilford,11
Halifax,6
Harnett,8
Haywood,10
Henderson,4
Hertford,9
Hoke,2
Hyde,6
Iredell,7
Jackson,4
Johnston,8
Jones,9
Lee,2
Lenoir,9
Lincoln,10
Macon,4
Madison,10
Martin,9
McDowell,10
Mecklenburg,5
Mitchell,10
Montgomery,2
Moore,2
Nash,9
New Hanover,12
Northampton,9
Onslow,12
Orange,2
Pamlico,9
Pasquotank,6
Pender,12
Perquimans,6
Person,0
Pitt,6
Polk,4
Randolph,0
Richmond,7
Robeson,8
Rockingham,0
Rowan,2
Rutherford,4
Sampson,12
Scotland,2
Stanly,2
Stokes,11
Surry,11
Swain,10
Transylvania,4
Tyrrell,6
Union,7
Vance,6
Wake,3
Warren,9
Washington,6
Watauga,11
Wayne,9
Wilkes,1
Wilson,9
Yadkin,1
Yancey,10
end assignment for target=1, excluded=-1


Find the first word starting with each letter

Retina, 28 bytes:

M!i`\b(\w)(?<!\b\1.+)\w*
¶
&#32

M! - Match each work and print all words separated by newlines.
i - Ignore case.
\b(\w) - Capture first letter of each word
(?<!\b\1.+) - After matching the letter, check if there wasn't a previous word starting with the same letter. \1.+ ensures at least two characters, so we are skipping the current word.
\w* - match the rest of the word.
The above matches only words - all other characters are removed.
¶\n  - Replace newlines with spaces.

Try it online!


Retina, 53 43 42 41 40 35 bytes

^[^x]+ |(\^1)?\w(?=1*x.(1+)| |$)
$2

For counting purposes each line goes in a separate file, but you can run the above as a single file by invoking Retina with the -s flag.

This expects the numbers in the input string to be given in unary and will yield output in the same format. E.g.

1 + 11x + -111x^11 + 11x^111 + -1x^11111
-->
11 + -111111x + 111111x^11 + -11111x^1111

instead of

1 + 2x + -3x^2 + 2x^3 + -1x^5
-->
2 + -6x + 6x^2 + -5x^4

Explanation

The code describes a single regex substitution, which is basically 4 substitutions compressed into one. Note that only one of the branches will fill group $2 so if any of the other three match, the match will simply be deleted from the string. So we can look at the four different cases separately:

^[^x]+<space>
<empty>

If it's possible to reach a space from the beginning of the string without encountering an x that means the first term is the constant term and we delete it. Due to the greediness of +, this will also match the plus and the second space after the constant term. If there is no constant term, this part will simply never match.

x(?= )
<empty>

This matches an x which is followed by a space, i.e. the x of the linear term (if it exists), and removes it. We can be sure that there's a space after it, because the degree of the polynomial is always at least 2.

1(?=1*x.(1+))
$1

This performs the multiplication of the coefficient by the exponent. This matches a single 1 in the coefficient and replaces it by the entire corresponding exponent via the lookahead.

(\^1)?1(?= |$)
<empty>

This reduces all remaining exponents by matching the trailing 1 (ensured by the lookahead). If it's possible to match ^11 (and a word boundary) we remove that instead, which takes care of displaying the linear term correctly.

For the compression, we notice that most of the conditions don't affect each other. (\^1)? won't match if the lookahead in the third case is true, so we can put those two together as

(\^1)?1(?=1*x.(1+)| |$)
$2

Now we already have the lookahead needed for the second case and the others can never be true when matching x, so we can simply generalise the 1 to a \w:

(\^1)?\w(?=1*x.(1+)| |$)
$2

The first case doesn't really have anything in common with the others, so we keep it separate.


Differences of MaxMin Divisor Pairs (DMDP)

JavaScript (ES7), 60 bytes

f=(n,i=1e4,j=i**.5|0)=>i?i%j?f(n,i,j-1):(i/j-j<n)+f(n,i-1):0

Probably exceeds your recursion limit, so you might prefer the iterative version for 70 bytes:

n=>[...Array(1e4)].map(g=(j=++i**.5|0)=>i%j?g(j-1):k+=i/j-j<n,i=k=0)|k


Python

This program opens the image specified on the command line and displays it.

import Image
import sys

with open(sys.argv[1]) as f:
    im = Image.open(f)
    im.show()

Works on linux, does not work on windows.

This is due to the way windows opens files. Binary mode must be specified for this to work properly on all operating systems.


Calculate \$ \lfloor n \log_2(n) \rfloor \$, exactly

Python 3, 25 bytes

lambda n:len(bin(n**n))-3

Try it online!
If the answer is \$x\$, then \$x+1 > n\log{n} \ge x\$ holds true, which means \$2^{x+1} > n^n \ge 2^x\$. So we can simply count the number of bits in the binary representation of \$n^n\$.


Tcl/Tk, 675 bytes

Well, I suppose I could crunch it more, but this is it for now...

set a {y m d}
rename proc p
p r {n {s ""}} {foreach {v d} {10 X 5 V 1 I} {while {$n>=$v} {set s $s$d;incr n -$v}};string map {VIIII IX IIII IV} $s}
p y y {expr !($y%100?$y%4:$y%400)}
p i $a {expr {($m in {3 5 7 10})?15:13}}
p n $a {expr [i $y $m $d]-8}
p k $a {expr $m==2?29+($d>24&&[y $y]):$m<8?31+$m%2:32-$m%2}
p N {} {clock f [clock se] -f {%Y %N %e}}
p M m {lindex {IAN FEB MAR APR MAI IVN IVL AVG SEP OCT NOV DEC IAN} $m-1}
p d $a {foreach f {n i k} n {NON ID KAL} mo {0 0 1} {if {$d<=[$f $y $m $d]} break}
string map {{AD I } {} {AD II } {PR }} "AD [r [expr [$f $y $m $d]+1-$d]] $n [M [expr $m+$mo]]"}
p p $a {if {$d==1} {puts "KAL [M $m]"} {puts [d $y $m $d]}}
p {*}[N]

How it works

The first thing is to collect today's date as a list: year, month, day. Everything works over that. The first of the month is a simple special case; we handle that separately.

All remaining cases work like this:

Find the future reference day's date in (5,7,13,15,days-in-month)
Get the abbreviation corresponding to that reference (NON, ID, KAL)
For Kalends we increment the month by one
Assemble the date string as:
"AD <days-in-roman-numerals> <abbreviated-reference-day> <abbreviated-month-name>"
Apply a text replace to correct AD I and AD II.

The first step is done with a function lookup table for each of the Nones, Ides, and Kalends. Nones and Ides are straight-forward subtraction and lookup, respectively. Computing the Kalends is only a little more complicated (notice the trick with leap-February's day number.):

February → 28 days + (it's a leap year AND day > 24)
January..July → 30 days + (it's January, March, May or July)
August..December → 31 days - (it's September or November)

The days is a simple difference: (reference_day - todays_day + 1)

Computing the leap year is done with a somewhat unusual arrangement of the standard formula so that it could be crunched better (removing braces and parentheses from the expr command).

Converting decimal to Roman numerals is a simple table-driven approach, stripped to use only ones, fives, and tens since we don't need to print the year in Roman numerals (domain is [1,39]).

Almost everything else is application of lookup tables.

A note on Tcl and reducing bytes

The first two lines of the script eat bytes by simply being shorter than spelling out proc f {y m d} for all instances.

Single-letter proc names and variables, of course:

    r := decimal→roman(n)    i := ides(y,m,d)        M := month-abbreviation(month)
    y := is-leap(year)       n := nones(y,m,d)       d := date→roman(y,m,d) [d ≠ 1]
    N := today → (y,m,d)     k := kalends(y,m,d)     p := date→roman(y,m,d) [∀d]

Testing for dates other than today

Change the very last line from p {*}[N] to

p {*}$argv

and run the program with the date desired:

% tclsh roman.tcl 2016 2 25
AD VI KAL MAR

Enjoy!


Matlab, 112
The core idea is generating a list of possible next positions and then uniformly drawing one of them. If we are e.g. at position $l=1$ the possible steps would be [-1,0,1,2,3] Of course if we would chose -1 that would be invalid and we would have to stay at the same position. Thats why we replace the invalid positions with the current position, [1,0,1,2,3], and then randomly chose an element from this updated list.
The OP asked us tho draw the program, so here we go:

The transcription:
function c(n,s);
l=19;                             %initialize position
for k=1:n;
    disp([ones(1,l)*32,'.']);     %print the line
    z=(-2:2)+l;                   %get vector of possible next steps (for l=1 we get [-1,0,1,2,3])
    z(z<0)=l;                     %prune invalids: here we just replace the the invalid positions with the current position
    z(z>39)=l;                    %   this ensures the same behaivour as staying in the same spot when going outside of the range
    l=z(randi(5));                %draw random sample of those
    pause(s);
end


Using the smallest number of bytes of code, write a program that produces this image

C#, 849 793 771 bytes

using System;using System.Drawing;using System.IO;class P{static void Main(){dynamic x,y,i=new Bitmap(Bitmap.FromStream(new MemoryStream(Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAGAAAAA2BAMAAADKYYHhAAAAGFBMVEUAAABdAgSMAwb///+jBAfFgYLRgYOugIE5HrT9AAAA20lEQVR4AWKgHIwCQThAFmVECAsA2qsDk4qBGIzjD7qAn5ngvlvAJJ3AdyscTqAr3PqaQwMgVYATKvQPlED5kQaAng2QBVnoCywBVeFQqKu6im83gcP1GFgVqEMVqiIP25MIzRjlmgSPZNufK/Qj1wC+bSKk2w/gHkDUaFZrEXht+85jcDc6FAHcqgsqvX3fkCxfcFZiaK3xL8EckS0ArfVO8u31C4y+FAQBBgbLAOYE9v8HxgDAgiiPXgk6gPykz8ctOzPIgHl0f8mjB1aDGQuyxeDgx3KB37t6B3NXgUgfIi7ZAAAAAElFTkSuQmCC"),0,312))),d=new Bitmap(1920,1080),g=Graphics.FromImage(d);for(y=0;y<54;y++)for(x=0;x<96;x++)g.FillRectangle(new SolidBrush(i.GetPixel(x,y)),new Rectangle(x*20,y*20,20,20));d.Save("s.png");}}

Tested with the following code:

class P
{
    static void Main()
    {
        Bitmap a = new Bitmap(@"c:\projects\confidence_2019_golf.png");
        Bitmap b = new Bitmap(@"c:\projects\s.png");

        Console.WriteLine(a.Width + ", " + b.Width);
        Console.WriteLine(a.Height + ", " + b.Height);

        for (int y=0; y<a.Height; y++)
        {
            for (int x=0; x<a.Width; x++)
            {
                Color ca = a.GetPixel(x, y);
                Color cb = b.GetPixel(x, y);

                if (ca.R != cb.R || ca.G != cb.G || ca.B != cb.B)
                {
                    Console.WriteLine(x + ", " + y);
                    Console.WriteLine(ca.R + ", " + ca.G + ", " + ca.B);
                    Console.WriteLine(cb.R + ", " + cb.G + ", " + cb.B);
                }
            }
        }
    }
}

Ungolfed:

using System;
using System.Drawing;
using System.IO;
class P
{
    static void Main()
    {
        dynamic x = 0;
        dynamic y = 0;
        dynamic b = Convert.FromBase64String("iVBORw0KGgoAAAANSUhEUgAAAGAAAAA2BAMAAADKYYHhAAAAGFBMVEUAAABdAgSMAwb///+jBAfFgYLRgYOugIE5HrT9AAAA20lEQVR4AWKgHIwCQThAFmVECAsA2qsDk4qBGIzjD7qAn5ngvlvAJJ3AdyscTqAr3PqaQwMgVYATKvQPlED5kQaAng2QBVnoCywBVeFQqKu6im83gcP1GFgVqEMVqiIP25MIzRjlmgSPZNufK/Qj1wC+bSKk2w/gHkDUaFZrEXht+85jcDc6FAHcqgsqvX3fkCxfcFZiaK3xL8EckS0ArfVO8u31C4y+FAQBBgbLAOYE9v8HxgDAgiiPXgk6gPykz8ctOzPIgHl0f8mjB1aDGQuyxeDgx3KB37t6B3NXgUgfIi7ZAAAAAElFTkSuQmCC");
        dynamic i = new Bitmap(Bitmap.FromStream(new MemoryStream(b, 0, 312)));
        dynamic d = new Bitmap(1920, 1080);
        dynamic g = Graphics.FromImage(d);
        for (y = 0; y < 54; y++)
        {
            for (x = 0; x < 96; x++)
            {
                g.FillRectangle(new SolidBrush(i.GetPixel(x, y)), new Rectangle(x * 20, y * 20, 20, 20));
            }
        }
        d.Save(@"c:\projects\s.png");
    }
}


PHP 109 107 bytes

<?for($g=1e4;--$g;$l=$y/$g+abs($y=$x>1?1-1/$x:$x-1)*$l)$e=1+$e/$g*$x.=fgets(STDIN);echo"$e ",$x>0?$l:ERROR;

 is a fairly straight-forward calculation. I use a nested form of the sum of inverse factorials, which not only increases the convergence rate, but also allows for exponentiation at the same time:

 is slightly more complicated. All convergent series seem to work for  or , but not both (Newton's iteration does not have this limitation, but requires the calculation of  each step). This isn't really a problem, though, given the log identity:

This means that if, for example, the iteration you're using only works on  and , you can use the multiplicative inverse of  and negate the result. Because I was using a nested identity for , I also chose to use a nested identity for :

 where

Or equivalently, as demonstrated by Paul Walls' implementation:

I define the  case as  (which is necessarily negative), using the absolute value for the inner product, and then allowing a bare  value in the fraction to correct the sign.

Sample I/O:

$ echo 2 | php exp_ln.php
7.3890560989307 0.69314718055995

$ echo 0.25 | php exp_ln.php
1.2840254166877 -1.3862943611199

$ echo 2.718281828 | php exp_ln.php
15.154262234523 0.99999999983113

$ echo -0.1 | php exp_ln.php
0.90483741803596 ERROR

Perl 95 93 89 bytes

$e=1+$e/$?*($x.=<>),$l=$_/$?+$l*abs,$_=$x>1?1-1/$x:$x-1while--$?;print"$e ",$x>0?$l:ERROR

Nearly identical to the PHP solution above, with a slightly larger iteration (65535 down to 0).

Edits:

Both 2 byte improvements due to Paul Walls.
Four more bytes saved in Perl by (ab)using $?, which is stored internally as an unsigned short, and by using $_ to save parentheses in abs.


Haskell, 100 97 91 89 87 72 67 Bytes
Try It Online!
-3 bytes thanks to @flawr
-6 bytes thanks to @flawr again
-2 bytes thanks to @flawr yet again
-2 bytes thanks to an optimized set of parameters
-1 byte thanks to @flawrs yet another time
-14 bytes thanks to requirement to only having to output one factor
-5 bytes thanks to @AndersKaseorg
f n|let s x=mod(x*x+7)n;a#b|d<-gcd(b-a)n,d>1=d|c<-s b=s a#s c=5#s 5

This works for the first 5 test cases in unnoticable time.
This will probably time-out on the largest test case.
In general this will usually return one non-trivial factor in time proportional to the square root of the smallest factor.
It will not work on every input because it doesn't vary the polynomial and detection of the exceptional case is hard to do in 140 bytes.
It will also not output the full factorization, but rather a non-trivial factor and the division of the input by this factor.
It will also not sort the factors by size.
The method used is Pollard-Rho-Factoring with the standard starting value of 2 (with the standard x^2+1 polynomial applied once) and the non-standard polynomial constant factor of 7 (because 1 didn't work with 1679) for all further evaluations.
Full program (factor.hs):
import System.Environment(getArgs)

f n|let s x=mod(x*x+7)n;a#b|d<-gcd(b-a)n,d>1=d|c<-s b=s a#s c=5#s 5

main= do
      args <- getArgs
      print$f (read $ head args :: Integer)

Compile as $ ghc factor.hs (needs ghc installed).
Run as $ ./factor <number>.
Example run:
$ ./factor 187
11

Ungolfed code:
f n=g 5 (s 5)
   where s x=mod(x*x+7)n
         g a b = if d>1 then d else g(s a)(s(s b))
               where d=gcd(b-a)n

Computes the non-trivial factor by calling g with initial values. The polynomial is pre-applied on 2 here and re-applied on the result (5) so that the input to g (in a "where" clause) can always be readily used for the gcd-test. g (golfed version uses infix #) then tries to compute a non-trivial factor d (in the where clause in the un-golfed version, in-line in the golfed one) as the difference between the two inputs to g, if it succeeds returns said factor, else retries. Here it may generate n as the output if a==b and thus returns only a trivial factor, the proper approach to handle this would be to either vary the starting values upon this event or change the polynomial.


Python 2, 69 bytes

l,r,L,R=input()
d=r-l;k=1
while(R-L)*k%d:k+=1
print r-L>=k%2*d/k<=R-l

Try it online!


<>< (Fish) - 12 * 32 = 384

I was planning to go for a more elegant solution, but I somehow ended up with this, which is pretty brute-force:

c  0  g84*%\
c2*0  g84*%\
0  84*g84*%\
c  84*g84*%\
c2*84*g84*%\
0  88*g84*%\
c  88*g84*%\
?v         \
;>?v~~?vv
"L" o;  >
"S" o; >~?v
"T" o;    >
;  >~?v"L"o
;     >"J"o
?v         \
 >~?v~~?vv
"I"  o;  >
"J"  o; >
    \~~?vv
"T"  o;  >
"Z"  o; >
?v         \
 >?v"J"o;
   >?v"Z"o;
"L"o;>?!v
"J"o;   >?v
"T"o;     >
?v?v"I"o;  >
   >"L"o;
 >?v"T"o;
   >?v"O"o;
     >"S"o;

It's pretty simple, it checks the code in a 3x3 square for text and uses the results to see which tetrimino corresponds to the code's shape. I didn't take a lot of effort to golf it yet.

Try the code here (after using the snippet to shape it like a tetrimino)

Example of code in shape Z (v1) here


JavaScript (ES6), 346 310 299 298 297 296 283 bytes

f=(a,y=0,x=0)=>(a[y][x]?a[y][x]=='O'&&(a[y][x]='*',(g=w=>(w=a[y])&&w[x]&&(w[x]<'!'?g(w[x]='v',y++)||g(w[x++]='>',y--)||g(w[--x]='^',y--)||g(w[x--]='<',y++)||+(w[++x]=' '):w[x]=='O'&&!/ /.test(a)?w[x]='%':0))(y++)||g(y-=2)||g(y++,x++)||g(x-=2)||+(a[y][++x]='O'))||f(a,y,x+1):f(a,y+1))
<textarea id="tests">XXXXOOOOXXXX&#10;X          X&#10;X          X&#10;XXXXXXXXXXXX&#10;&#10;XOOOOOX&#10;X     X&#10;X     X&#10;X     XXXXXXXX&#10;X            X&#10;X            X&#10;XXXXXXXXXXXXXX&#10;&#10;XOOOOX&#10;X    X&#10;X    X&#10;X  XXX&#10;X    X&#10;X    X&#10;XXXXXX&#10;&#10;XXXXXXXXXXXXX&#10;O           X&#10;O    X      X&#10;O    X      X&#10;O           X&#10;XXXXXXXXXXXXX</textarea><br><button onclick="for(test of document.getElementById('tests').value.split('\n\n')){console.log(test);arr=test.split('\n').map(line=>line.split(''));f(arr);console.log(arr.map(line=>line.join('')).join('\n'))}">Run</button>

Quite hacky in some places, but I wanted to get the code out there. Input as a 2D character array, output by modifying said array.
Ungolfed version
This is the same exact algorithm, save for some truthy/falsy magic with +' ' being NaN being falsy (and some more), some golf variables and using ifs instead of ?:, || and &&.
f = (a, y = 0, x = 0) => {         // main function
  if (!a[y][x])                    // check for end of line
    return f(a, y + 1);            // end of line, recursively check next
  if (a[y][x] == 'O') {            // check for valid start position
    a[y][x] = '*';                 // set the start position
    function g() {                 // pathfinder function
      if (!a[y] || !a[y][x])       // check for out of bounds
        return 0;
      if (a[y][x] == ' ') {        // check for snow
        a[y][x] = 'v';             // set current cell to 'down'
        y++;                       // move position down
        if (g()) return 1;         // see if a valid route is found from there
        y--;                       // if not, reset position and try again
        a[y][x] = '>';             // repeat for other directions
        x++;
        if (g()) return 1;
        x--;
        a[y][x] = '^';
        y--;
        if (g()) return 1;
        y++;
        a[y][x] = '<';
        x++;
        if (g()) return 1;
        x++;
        a[y][x] = ' ';             // no route found, reset cell to snow
        return 0;
      }
      if (a[y][x] == 'O'           // check for valid exit
          && !/ /.test(a)) {       // and that no snow is left
        a[y][x] = '%';             // set the exit
        return 1;
      }
    }
    y++;                           // move a cell down from the start position
    if (g()) return 1;             // see if a valid route starts there
    y -= 2;                        // repeat for other directions
    if (g()) return 1;
    y++; x++;
    if (g()) return 1;
    x -= 2;
    if (g()) return 1;
    x++;
    a[y][x] = 'O';                 // no route found, continue on
  }
  return f(a, y, x + 1);           // check the next cell
}


Python, 661 chars

R=range
I=lambda x:[int(x[2*i:2*i+2],16)for i in R(16)]
k=I(raw_input())
c=I(raw_input())
P=[]
x=1
for i in R(512):P+=[x];x^=x*2^(x>>7)*0x11b
S=[255&(99^j^(j>>4)^(j>>5)^(j>>6)^(j>>7))for i in R(256)for j in[(P[255-P.index(i)]if i else 0)*257]]
for r in R(10):
 for i in R(4):k+=[k[-16]^S[k[-3-(i>2)*4]]]
 k[-4]^=[1,2,4,8,16,32,64,128,27,54][r]
 for i in R(12):k+=[k[-16]^k[-4]]
for r in R(11):
 c=[x^y for x,y in zip(k[160-16*r:],c)]
 if r>9:break
 for i in[0,4,8,12]*(r>0):c[i:i+4]=[x^y^z^w for j in R(4)for x,y,z,w in[[P[a+P.index(v)]if v else 0 for a,v in zip((2*[104,238,199,223])[3-j:],c[i:i+4])]]]
 c=(c*13)[::13];c=map(S.index,c)
print''.join(map(chr,c))

k is the key, c is the ciphertext.  I build P, the powers of 3 in the field, then S, the sbox.  Then k is extended with the key schedule.  Finally we do the AES decryption.  Mixcolumns is the hard phase, all the other phases are pretty straightforward.


Find a route between two Wikipedia articles

Python 373 -> 303

It reads the Wikipedia destination from input() (user input) and should be in the format of /wiki/dest. So, something like /wiki/Code_golf or /wiki/United_States. It also uses one space for the indents and http://enwp.org instead of Wikipedia's full URL to save bytes.

-50 because if it finds a broken URL it gets a new random URL.
-20 because it prints the title of each URL visited (could change title -> URL, but title is cleaner and actually makes my source larger).

It hangs every once and a while, and I can't figure out why. Perhaps because of Wikipedia rate limits?

I found the Boston Red Sox Wikipedia page in 9 minutes 20 seconds, and the United States page in under 10 seconds, so it shouldn't take too long to find Code Golf...

from mechanize import*;from lxml.html import*;from random import*;a=Browser();a.set_handle_robots(0);i='http://enwp.org/Special:Random';t=input();d={};k=a.open
def f(o):
 if o!=i:d[o]=o
 if o in d:f(i)
 try:v=fromstring(k(o).read()).xpath('//div[@id="content"]//a/@href')
 except:f(i)
 print a.title()
 if t in v:k(t);print 'f';exit()
 else:f(choice(v)) if v else f(i)
f(i)


Retina 0.8.2, 163 156 bytes

.+
$*_
(_+)¶(_+)
$2¶$1¶$1
r`__\G
$%`$&
¶
;
(?<=(_+);.*)(?<=;_+;\1*)_
¶$`_
m`^_+;
__
+`(>*)_(_+)(_+<?;)\2
$1_$.2$* $3¶$1>$2<;
T`>\_` \\`>+_
T`\\\_;<`V/_`.<|;

Try it online! Explanation:

.+
$*_

Convert the inputs to unary. This gives us W¶S.

(_+)¶(_+)
$2¶$1¶$1

Swap the inputs and duplicate the width. This gives us S¶W¶W.

r`__\G
$%`$&

Calculate the volume of the quarry. This gives us S¶W¶V.

¶
;

Join the inputs into one line. This gives us S;W;V.

(?<=(_+);.*)(?<=;_+;\1*)_
¶$`_

Calculate the amount of progress for each day on its own line. Each day has the format S;W;D, where D is 0 on the first line and increments by S each day until it reaches V.

m`^_+;
__

Delete S and increase W by 2 on each line. This gives us G;D for each day.

+`(>*)_(_+)(_+<?;)\2
$1_$.2$* $3¶$1>$2<;

While D is nonzero, dig either D or G-2 from the line (so the first and last characters are always left), moving the depth to the next line. Each line is indented with one more > than the previous. Newly dug lines also include a <.

T`>\_` \\`>+_

Turn the indent into spaces and the following _ into a \.

T`\\\_;<`V/_`.<|;

If a < is following a \ then turn it into a V, if it's following a _ then turn it into a /. Delete all the <s and ;s.


Jelly, 29 27 bytes

ÆEµØA“¡3ḅḲ+Ṿɼ¡ẏƙẊƘ’œ?xḊṚḢ}¡

Thanks to @JonathanAllan for golfing off 1 byte!

Try it online!

Background

“¡3ḅḲ+Ṿɼ¡ẏƙẊƘ’

is a numeric literal. The characters between the quotes are replaced with their 1-based indices in the Jelly code page, and the resulting array is interpreted as a base-250 number. This yields the integer c := 288824892868083015619552399.

How it works

ÆEµØA“¡3ḅḲ+Ṿɼ¡ẏƙẊƘ’œ?xḊṚḢ}¡  Main link. Argument: n

ÆE                           Yield the exponents of n's prime factorization, with.
                             zeroes. This yields an array A.
  µ                          Begin a new monadic chain with argument A.
   ØA                        Set the return value to “ABC...XYZ”.
     “¡3ḅḲ+Ṿɼ¡ẏƙẊƘ’œ?        Select the c-th permutation of the alphabet, yielding
                             s := “SPMFLQUIXNCWORAGZTEJHVDBKY”.
                      Ḋ      Dequeue; yield A without its first element, stripping
                             the exponent of 2.
                     x       Repeat the k-th letter of s r times, where r is the
                             exponent of the k-th odd prime number.
                          ¡  Combine the two links to the left into a quicklink:
                        Ḣ}     - Apply head to the right argument (A), yielding the
                                 exponent of 2. Since n is at most divisible by the
                                 first power of 2, this yields 1 for even numbers
                                 and 0 for odd ones. Call the link to the left that
                                 many times on the previous return value.
                       Ṛ       - Reverse the string to the left.


Haskell, 400 351 308 characters

import Data.List
import Text.Parsec
(&)=fmap
r=return
s=string
l f b=(>>=(&b).f)
x=(=<<).replicate
m=sort&chainl1(l x(concat&many1(l(flip x)n i))n)((s"+">>r(++))<|>(s"-">>r(\\)))
i=between(s"(")(s")")m<|>(:[])&(l(:)(many lower)upper)
n=option 1$read&many1 digit
main=getContents>>=parseTest(l(==)(s"=">>m)m)

This just might have all the golf squeezed out of it. I don't know if there is another 100 51 8 characters to be saved!

& echo 'C6H5COOH-O2=7CO2+3H2O' | runhaskell Chemical.hs
False

& echo '2Fe(CN)6+2SO2+2O2=Fe2(SO4)2+6C2N2' | runhaskell Chemical.hs
True

& echo '2SO2=2SO4-2O2' | runhaskell Chemical.hs
True

Here's the ungolf'd version, in case anyone want to follow along. It is a simple Parsec based parser:

import Control.Applicative ((<$>), (<*>))
import Data.List
import Text.Parsec
import Text.Parsec.String (Parser)

type Atom = String

{- golf'd as x -}
multiple :: Int -> [Atom] -> [Atom]
multiple n = concat . replicate n

{- golf'd as m -}
chemicals :: Parser [Atom]
chemicals = sort <$> chainl1 molecules op
  where
    op :: Eq a => Parser ([a] -> [a] -> [a])
    op = (char '+' >> return (++))
     <|> (char '-' >> return (\\))

    molecules :: Parser [Atom]
    molecules = multiple <$> number <*> terms

    terms :: Parser [Atom]
    terms = concat <$> many1 term

    term :: Parser [Atom]
    term = flip multiple <$> item <*> number

{- gofl'd as i -}
item :: Parser [Atom]
item = between (char '(') (char ')') chemicals
   <|> (:[]) <$> atom
  where
    atom :: Parser Atom
    atom = (:) <$> upper <*> many lower

{- gofl'd as n -}
number :: Parser Int
number = option 1 $ read <$> many1 digit

{- gofl'd as main -}
main :: IO ()
main = getContents >>= parseTest chemEquality
  where
    chemEquality :: Parser Bool
    chemEquality = (==) <$> chemicals <*> (char '=' >> chemicals)


Python 3 + inflect,  122  114 bytes

Saved 8 bytes thanks to Scrooble.

from inflect import*
f=lambda k,i=0:k!=4and f(len(engine().number_to_words(k,andword="").replace(" ","")),i+1)or i

This cannot be tested online because of the package it uses. Running the test suite gives:

4 -> 0
3 -> 2
6278 -> 6
1915580 -> 5


ASCII Arc Length: How long is a piece of string?

JavaScript (ES6), 158 bytes

-1 byte thanks to @VisualMelon

s=>s.split`
`.map(s=>(s=s.replace(/./g,(m,i)=>m>" "?i:""),n=s[0]>n?s.slice(-1):s[0]),n=p=0).reduce((t,v,i)=>(r=i&&t+(((p-v)**2+1)**.5*100+.5|0)/100,p=v,r),0)

Output is sometimes not exact  (0.999 instead of 1) due to floating-point imprecision, but rounding was done part-way through the steps in order to match the square root table.

Test Snippet

Note that trailing spaces on each line are ignored, so they can be omitted from the input.

f=
s=>s.split`
`.map(s=>(s=s.replace(/./g,(m,i)=>m>" "?i:""),n=s[0]>n?s.slice(-1):s[0]),n=p=0).reduce((t,v,i)=>(r=i&&t+(((p-v)**2+1)**.5*100+.5|0)/100,p=v,r),0)
<textarea id=I rows=15 cols=12></textarea><br>
<button onclick="O.value=f(I.value)">Run</button> <input id=O disabled>


Mathematica, 104 bytes

Extremely efficient

(t=i=1;While[t<#+1,If[!FreeQ[Subsets[(r=IntegerDigits)@Prime@i,{Length@r@i}],r@i],t++];i++];Prime[i-1])&

finds n=34 in under a minute


Are You the One? (Mastermind Derivative)

Python 2 (run faster if run using Pypy)

Believed to almost always guess the correct pairing in 10 rounds or lower

My algorithm is taken from my answer for mastermind as my hobby (see in Ideone). The idea is to find the guess which minimize the number of possibilities left in the worst case. My algorithm below just brute force it, but to save time, it just pick random guess if the number of possibilities left is larger than RANDOM_THRESHOLD. You can play around with this parameter to speed things up or to see better performance.

The algorithm is quite slow, on average 10s for one run if run using Pypy (if using normal CPython interpreter it's around 30s) so I can't test it on the whole permutations. But the performance is quite good, after around 30 tests I haven't seen any instance where it can't find the correct pairing in 10 rounds or lower.

Anyway, if this is used in real life show, it has plenty of time before the next round (one week?) so this algorithm can be used in real life =D

So I think it's safe to assume that on average this will find the correct pairings in 10 guesses or lower.

Try it yourself. I might improve the speed in the next few days (EDIT: it seems difficult to further improve, so I'll just leave the code as is. I tried only doing random pick, but even at size=7, it fails in 3 of the 5040 cases, so I decided to keep the cleverer method). You can run it as:

pypy are_you_the_one.py 10

Or, if you just want to see how it works, input smaller number (so that it runs faster)

To run a full test (warning: it'll take very long for size > 7), put a negative number.

Full test for size=7 (completed in 2m 32s):

...
(6, 5, 4, 1, 3, 2, 0): 5 guesses
(6, 5, 4, 2, 0, 1, 3): 5 guesses
(6, 5, 4, 2, 0, 3, 1): 4 guesses
(6, 5, 4, 2, 1, 0, 3): 5 guesses
(6, 5, 4, 2, 1, 3, 0): 6 guesses
(6, 5, 4, 2, 3, 0, 1): 6 guesses
(6, 5, 4, 2, 3, 1, 0): 6 guesses
(6, 5, 4, 3, 0, 1, 2): 6 guesses
(6, 5, 4, 3, 0, 2, 1): 3 guesses
(6, 5, 4, 3, 1, 0, 2): 7 guesses
(6, 5, 4, 3, 1, 2, 0): 7 guesses
(6, 5, 4, 3, 2, 0, 1): 4 guesses
(6, 5, 4, 3, 2, 1, 0): 7 guesses
Average count: 5.05
Max count    : 7
Min count    : 1
Num success  : 5040

If RANDOM_THRESHOLD and CLEVER_THRESHOLD are both set to a very high value (like 50000), it'll force the algorithm to find the optimal guess that minimizes the number of possibilities in the worst case. This is very slow, but very powerful. For example, running it on size=6 asserts that it can find the correct pairings in maximum 5 rounds.

Although the average is higher compared to using the approximation (which is 4.11 rounds on average), but it always succeeds, even more with one round left to spare. This further strengthen our hypothesis that when size=10, it should almost always find the correct pairings in 10 rounds or less.

The result (completed in 3m 9s):

(5, 4, 2, 1, 0, 3): 5 guesses
(5, 4, 2, 1, 3, 0): 5 guesses
(5, 4, 2, 3, 0, 1): 4 guesses
(5, 4, 2, 3, 1, 0): 4 guesses
(5, 4, 3, 0, 1, 2): 5 guesses
(5, 4, 3, 0, 2, 1): 5 guesses
(5, 4, 3, 1, 0, 2): 5 guesses
(5, 4, 3, 1, 2, 0): 5 guesses
(5, 4, 3, 2, 0, 1): 5 guesses
(5, 4, 3, 2, 1, 0): 5 guesses
Average count: 4.41
Max count    : 5
Min count    : 1
Num success  : 720

The code.

from itertools import permutations, combinations
import random, sys
from collections import Counter

INTERACTIVE = False
ORIG_PERMS = []
RANDOM_THRESHOLD = 100
CLEVER_THRESHOLD = 0

class Unbuffered():
    def __init__(self, stream):
        self.stream = stream

    def write(self, data):
        self.stream.write(data)
        self.stream.flush()

    def __getattr__(self, attr):
        self.stream.getattr(attr)
sys.stdout = Unbuffered(sys.stdout)

def init(size):
    global ORIG_PERMS
    ORIG_PERMS = list(permutations(range(size)))

def evaluate(solution, guess):
    if len(guess) == len(solution):
        cor = 0
        for sol, gss in zip(solution, guess):
            if sol == gss:
                cor += 1
        return cor
    else:
        return 1 if solution[guess[0]] == guess[1] else 0

def remove_perms(perms, evaluation, guess):
    return [perm for perm in perms if evaluate(perm, guess)==evaluation]

def guess_one(possible_perms, guessed_all, count):
    if count == 1:
        return (0,0)
    pairs = Counter()
    for perm in possible_perms:
        for pair in enumerate(perm):
            pairs[pair] += 1
    perm_cnt = len(possible_perms)
    return sorted(pairs.items(), key=lambda x: (abs(perm_cnt-x[1]) if x[1]<perm_cnt else perm_cnt,x[0]) )[0][0]

def guess_all(possible_perms, guessed_all, count):
    size = len(possible_perms[0])
    if count == 1:
        fact = 1
        for i in range(2, size):
            fact *= i
        if len(possible_perms) == fact:
            return tuple(range(size))
        else:
            return tuple([1,0]+range(2,size))
    if len(possible_perms) == 1:
        return possible_perms[0]
    if count < size and len(possible_perms) > RANDOM_THRESHOLD:
        return possible_perms[random.randint(0, len(possible_perms)-1)]
    elif count == size or len(possible_perms) > CLEVER_THRESHOLD:
        (_, next_guess) = min((max(((len(remove_perms(possible_perms, evaluation, next_guess)), next_guess) for evaluation in range(len(next_guess))), key=lambda x: x[0])
                               for next_guess in possible_perms if next_guess not in guessed_all), key=lambda x: x[0])
        return next_guess
    else:
        (_, next_guess) = min((max(((len(remove_perms(possible_perms, evaluation, next_guess)), next_guess) for evaluation in range(len(next_guess))), key=lambda x: x[0])
                               for next_guess in ORIG_PERMS if next_guess not in guessed_all), key=lambda x: x[0])
        return next_guess

def main(size=4):
    if size < 0:
        size = -size
        init(size)
        counts = []
        for solution in ORIG_PERMS:
            count = run_one(solution, False)
            counts.append(count)
            print '%s: %d guesses' % (solution, count)
        sum_count = float(sum(counts))
        print 'Average count: %.2f' % (sum_count/len(counts))
        print 'Max count    : %d' % max(counts)
        print 'Min count    : %d' % min(counts)
        print 'Num success  : %d' % sum(1 for count in counts if count <= size)
    else:
        init(size)
        solution = ORIG_PERMS[random.randint(0,len(ORIG_PERMS)-1)]
        run_one(solution, True)

def run_one(solution, should_print):
    if should_print:
        print solution
    size = len(solution)
    cur_guess = None
    possible_perms = list(ORIG_PERMS)
    count = 0
    guessed_one = []
    guessed_all = []
    while True:
        count += 1
        # Round A, guess one pair
        if should_print:
            print 'Round %dA' % count
        if should_print:
            print 'Num of possibilities: %d' % len(possible_perms)
        cur_guess = guess_one(possible_perms, guessed_all, count)
        if should_print:
            print 'Guess: %s' % str(cur_guess)
        if INTERACTIVE:
            evaluation = int(raw_input('Number of correct pairs: '))
        else:
            evaluation = evaluate(solution, cur_guess)
            if should_print:
                print 'Evaluation: %s' % str(evaluation)
        possible_perms = remove_perms(possible_perms, evaluation, cur_guess)

        # Round B, guess all pairs
        if should_print:
            print 'Round %dB' % count
            print 'Num of possibilities: %d' % len(possible_perms)
        cur_guess = guess_all(possible_perms, guessed_all, count)
        if should_print:
            print 'Guess: %s' % str(cur_guess)
        guessed_all.append(cur_guess)
        if INTERACTIVE:
            evaluation = int(raw_input('Number of correct pairs: '))
        else:
            evaluation = evaluate(solution, cur_guess)
            if should_print: print 'Evaluation: %s' % str(evaluation)
        if evaluation == size:
            if should_print:
                print 'Found %s in %d guesses' % (str(cur_guess), count)
            else:
                return count
            break
        possible_perms = remove_perms(possible_perms, evaluation, cur_guess)

if __name__=='__main__':
    size = 4
    if len(sys.argv) >= 2:
        size = int(sys.argv[1])
        if len(sys.argv) >= 3:
            INTERACTIVE = bool(int(sys.argv[2]))
    main(size)


JavaScript (ES6), 149 bytes
Takes input in currying syntax (w)(h)([a,b]).

w=>h=>g=(p,d=[1,-1],s=Array(w).fill` `)=>h--?`|${p=p.map((x,i)=>~(k=d[i],s[x]='/X\\'[x-p[i^1]?k+1:1],x+=k)&&x<w?x:x+(d[i]=-k)),s.join``}|
`+g(p,d):''

Try it online!
Commented
w => h =>                  // w = width, h = height
  g = (                    // g = recursive function taking:
    p,                     //   p[] = array holding the point coordinates
    d = [1, -1],           //   d[] = directions
    s = Array(w).fill` `   //   s = array of w spaces (we can't use a string because it's
  ) =>                     //       immutable in JS)
    h-- ?                  // if we haven't reached the last row yet:
      `|${                 //   append the left pipe
      p = p.map((x, i) =>  //   for each x at position i in p[]:
        ~(k = d[i],        //     k = direction for this point
          s[x] = '/X\\'[   //     insert either '/', 'X' or '\' at position x in s
            x - p[i ^ 1] ? //     if p[0] != p[1]:
              k + 1        //       use the direction
            :              //     else:
              1            //       force 'X'
          ], x += k        //     add k to x
        ) &&               //     if the result is not equal to -1
        x < w ?            //     and is less than w:
          x                //       use the current value of x
        :                  //     else:
          x + (d[i] = -k)  //       change the direction and restore the initial value of x
      ),                   //   end of map()
      s.join``}|\n` +      //   join and append s; append the right bar and a linefeed
      g(p, d)              //   followed by the result of a recursive call
    :                      // else:
      ''                   //   stop recursion


The real treasure was the numbers we made along the way

TI-BASIC (TI-84+ CE), \$238^3/14161 = 952.0\$

118-length("+×/ABCDEFGHIJK...

The 256 bytes in TI-BASIC break down thusly:

240 bytes are one-byte tokens that can be quoted
11 are the start of two-byte tokens
2 are unused
The remaining 3 are the ",→, and newline characters which break strings.

The string contains all 237 allowable bytes in the first category not already in 118-length(.

The program calculates 238 distinct integers, ranging from 118 down to -119. The score is therefore $$ \frac{238^3}{\sum_{n = -119}^{118} |n|} = 952.$$


Perl, 95

$m=1;$n=12||die$m;@ARGV=$0;$_=<>;$m*=$n--;s/\|/;\$m=$m;\$n=$n|/;open _,">$0";print _;exec$^X,$0

The program really has to be on a single line, and overwrites itself at each iteration.


Tuples by sequentially stepping through entries in list of lists

JavaScript (ES6), 59 bytes
Expects a list of lists of positive integers.

f=a=>[a.map(a=>a[0]),...a.some(a=>a[1]&&a.shift())?f(a):[]]

Try it online!
How?
At each iteration:

We output a new list consisting of the first element of each list.
We remove the first element of the first list containing at least 2 elements, and repeat the process. Or we stop the recursion if no such list exists.


Pyth, score 2 (8 bytes)

lefSIT.:

Try it here!

Code points [108, 101, 102, 83, 73, 84, 46, 58]. Another shorter solution, leSI#.: scores 3, but its code points are [108, 101, 83, 73, 35, 46, 58], which are very close to a score of 1, actually. Rearranging a bit may help Nevermind, the substrings built-in is .: which cannot be rearranged, so the lowest score must be 2 if the program makes use of it.

How?

lefSIT.:     Full program. Accepts either a list or a string from STDIN.
      .:     Substrings.
  f  T       Only keep those that are...
   SI        Sorting-Invariant.
le           Length of the last item.


JavaScript (ES6),  58  56 bytes
n=>`25AND 41OR X37OR`.replace(/\d+/g,m=>m>>n%6&1?'':'N')

Try it online!
How?
Given the input \$n\$, we compute \$n\bmod 6\$ to get an index into 3 small lookup bit masks.
It's worth noting that all operations are commutative, i.e. \$(X \operatorname{op} Y)=(Y \operatorname{op} X)\$ even when \$X=\lnot Y\$. So the collisions between 011 and 101 and between 010 and 100 are actually very welcome.
 n (decimal) | n mod 6 | NAND | NOR | XNOR
-------------+---------+------+-----+------
  011 or 101 |    5    |   0  |  1  |  1
  010 or 100 |    4    |   1  |  0  |  0
         111 |    3    |   1  |  1  |  0
         110 |    2    |   0  |  0  |  1
         001 |    1    |   0  |  0  |  0
         000 |    0    |   1  |  1  |  1
                           |     |     |
                           |     |     +--> 0b100101 = 37
                           |     +--------> 0b101001 = 41
                           +--------------> 0b011001 = 25

We look for the bit masks in the string "25AND 41OR X37OR" and replace them with either "N" or an empty string.


Converting a string to lower-case (without built-in to-lower functions!)

Python 2.7 - 30 (with terrible and unapologetic rule abuse)

raw_input().upper().swapcase()

As an anonymous edit pointed out, you can do it in 27 26 in Python 3:

input().upper().swapcase()

I'm flagrantly abusing the rules here, but...

  Important: you are NOT allowed to use a built-in function that converts the string (or just one character) to lowercase (such as ToLower() in .NET, strtolower() in PHP
  , ...)! You're allowed to use all other built-in functions, however.

This takes the strings and coverts it to upper case. Then in a very unrelated method call, it reverses the case of the string - so that any lower case letters become upper case letters... and swaps any upper case letters to lower case letters.


Shortest code to throw IllegalArgumentException in Java

These were all found by grepping the source code in the package java.lang.

All of them result in a "pure" IllegalArgumentException (i.e. not a subclass of it).

The ones marked * only work if you add " throws Exception" (18 characters) to your main declaration, as they throw a checked exception of some kind.

12 (30?) characters*

"".wait(-1);

This will result in:

java.lang.IllegalArgumentException: timeout value is negative

22 (40?) characters*

new Thread().join(-1);

22 characters

Character.toChars(-1);

30 characters

Character.UnicodeBlock.of(-1);


Find the shortest way to advance a counter to a certain number

Lua, 327763 steps (optimum, 276 bytes)
Golfed version:
a={[0]=""}t=tonumber for i=0,52 do A={}for k,v in pairs(a)do A[k]=v L=("%04d"):format(k)for i=1,4 do c=L:sub(i,i)d=L:gsub(c,(t(c)+1)%10)e=a[t(d)]A[d]=(not e or #e>#v)and v..c or e end b=k+1 if k<9999then e=a[b]A[b]=(not e or #e>#v)and v.."C"or e end end a=A endprint(a[(...)])

Improved version of the examples in question (only 1000 is improved):
0001:C
0093:CCCCCCCCCC12345678CCC
1000:0CCCCCCCCCCC2345678C23456789
     (0000>1111>1122>1199>1200>1000)
9999:012345678

Ungolfed version:
a = {[0]=""}
for i=0,52 do
    A = {}
    for k,v in pairs(a) do
        A[k] = v
        L=("%04d"):format(k)
        for i=1,4 do
           c=L:sub(i,i)
           d=L:gsub(c,(tonumber(c)+1)%10)
           e=a[tonumber(d)]
           A[d] = (not e or #e > #v) and v..c or e
        end
        b=k+1
        if k < 9999 then
            e=a[b]
            A[b] = (not e or #e > #v) and v.."C" or e
        end
    end
    a=A
end
print(a[93],a[1000],a[9999])


Canvas, 41 bytes

（Ａ┬｛［１｝０｝┐）
⁷Ｌ├Ｘ⁷ｌＹø；｛³×？³ｙ³－╵ｘ＼╋
⁸⤢↔╶╶⁸ｎ

Try it here!


JS, 1719/1694

Theory

Unfortunately, the rule set that you provide may not be a wise decision from a mathematical point of view. In fact, using a smaller subset of rules, you can find a solution for every number in the given interval

except for

for which there is no solution.

Reduced rule set

Consider the following subet of rules:

Use only the operators plus, minus and times.
You don't need to implement multiple occurrences of plus or minus in your expressions.
You don't need to implement neither division nor operator associativity (as their solution set is already covered by the first rule).

The reason why this works is that, as you discussed earlier with @Qwix, you allow boring answers, that is, expressions that end in the regular expression
( times one)+$. Allowing this, each number in the given interval will have a solution.

When you replied in one of your comments,

  @Qwix Yes; boring answers are acceptable, although that one doesn't
  work for 104, 105, 106, 107, 108, 109, 110, or 111. –

you were absolutely right: This does not work when you're trying to build your expression starting with the numbers themselves, i.e. one hundred four times one times one … or any other of those numbers.

If however, your expression starts with an expression whose evaluation equals one of the given numbers, you're out of luck. For example, note that 17 + 87 is indeed 104, so we could write 104 as:

104: seventeen plus eighty seven times one times one times one times one times one times one times one times one times one times one

To see that this subset works, save this file as num.js and make sure that SpiderMonkey, a JavaScript engine for command lines, is installed on your system.

The algorithm

Let us define the property K for positive integers as the state of the number having N letters and having a value of N.
Let us further define the property F for an expression as the state of its word conversion being 8k-times shorter than its evaluation with k ∈ ℕ. F stands for "fillable" and describes whether or not we can fill the word conversion of the expression with expressions of length 8 (i.e. " times one") such that the resulting expression might get the property N.

We then proceed as follows:

Convert the input number to words.
Check if the input number has property K.

If it does, return the words (4 is the only number with this property, unfortunately).
If it doesn't, proceed.

For all two-operand expressions (additions, subtractions and multiplications in this order) that result in the input number, check if their evaluation has property K.

If it does, return the words.
If it doesn't, check if the two-operand expression has property N.

If it does, fill the expression with " times one" and check if the evaluation of the resulting expression has property K.

If it does, return the words
If it doesn't, proceed

If it doesn't, proceed

Go drink a coffee

Practice

num.js (for SpiderMonkey / command lines)

function X(e,t){return e+": "+t}function P(e){var n,t;for(n=1;.5*e+(e%2===0?1:0)>n;++n){if(t=C.s(n)+" plus "+C.s(e-n),t.replace(/\s/g,"").length===e)return t;if(F(e,t)&&e>t.length)return G(e,t)}return!1}function M(e){var t,n;for(t=L;t>1;--t){if(0>t-e)return!1;if(n=C.s(t)+" minus "+C.s(t-e),n.replace(/\s/g,"").length===e)return n;if(F(e,n)&&e>n.length)return G(e,n)}return!1}function F(e,t){return(e-t.replace(/\s/g,"").length)%8===0}function G(r,t){var e,i=(r-t.replace(/\s/g,"").length)/8,n="";for(e=0;i>e;++e)n+=" times one";return t+n}function T(e){var t,n,r;if(F(e,C.s(e)))return G(e,C.s(e));for(t=1,n=1;t<Math.floor(Math.sqrt(e));++t){for(;e>tn;)++n;if(tn===e&&(r=C.s(t)+" times "+C.s(n),r.replace(/\s/g,"").length===e))return r}return!1}function Y(e){var n,r,t;return e===C.s(e).length?X(e,C.s(e)):(n=P(e))?X(e,n):(r=M(e))?X(e,r):(t=T(e),t?X(e,t):X(e,"impossible"))}var L=1e4,C=new function(){return this.o=["","one","two","three","four","five","six","seven","eight","nine"],this.t=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"],this.T=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],this.s=function(e){return e?this.m(e):"zero"},this.m=function(e){return e>=1e6?this.m(Math.floor(e/1e6))+" million"+(e%1e6!==0?" "+this.Z(e%1e6):""):this.Z(e)},this.Z=function(e){return e>=1e3?this.h(Math.floor(e/1e3))+" thousand"+(e%1e3!==0?" "+this.h(e%1e3):""):this.h(e)},this.h=function(e){return e>99?this.o[Math.floor(e/100)]+" hundred"+(e%100!==0?" "+this.U(e%100):""):this.U(e)},this.U=function(e){return 10>e?this.o[e]:e>=10&&20>e?this.T[e-10]:this.t[Math.floor(e/10)]+(e%10!==0?" "+this.o[e%10]:"")},this};print(Y(0|arguments[0]))

num.js (for browsers)

The given code from above can't work for browsers due to its last command, which grabs the command line arguments in order to make a nice command out of the given script.

In order to run the JavaScript code directly from within your browser, select this piece of the above code:

function X(e,t){return e+": "+t}function P(e){var n,t;for(n=1;.5*e+(e%2===0?1:0)>n;++n){if(t=C.s(n)+" plus "+C.s(e-n),t.replace(/\s/g,"").length===e)return t;if(F(e,t)&&e>t.length)return G(e,t)}return!1}function M(e){var t,n;for(t=L;t>1;--t){if(0>t-e)return!1;if(n=C.s(t)+" minus "+C.s(t-e),n.replace(/\s/g,"").length===e)return n;if(F(e,n)&&e>n.length)return G(e,n)}return!1}function F(e,t){return(e-t.replace(/\s/g,"").length)%8===0}function G(r,t){var e,i=(r-t.replace(/\s/g,"").length)/8,n="";for(e=0;i>e;++e)n+=" times one";return t+n}function T(e){var t,n,r;if(F(e,C.s(e)))return G(e,C.s(e));for(t=1,n=1;t<Math.floor(Math.sqrt(e));++t){for(;e>tn;)++n;if(tn===e&&(r=C.s(t)+" times "+C.s(n),r.replace(/\s/g,"").length===e))return r}return!1}function Y(e){var n,r,t;return e===C.s(e).length?X(e,C.s(e)):(n=P(e))?X(e,n):(r=M(e))?X(e,r):(t=T(e),t?X(e,t):X(e,"impossible"))}var L=1e4,C=new function(){return this.o=["","one","two","three","four","five","six","seven","eight","nine"],this.t=["","","twenty","thirty","forty","fifty","sixty","seventy","eighty","ninety"],this.T=["ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen"],this.s=function(e){return e?this.m(e):"zero"},this.m=function(e){return e>=1e6?this.m(Math.floor(e/1e6))+" million"+(e%1e6!==0?" "+this.Z(e%1e6):""):this.Z(e)},this.Z=function(e){return e>=1e3?this.h(Math.floor(e/1e3))+" thousand"+(e%1e3!==0?" "+this.h(e%1e3):""):this.h(e)},this.h=function(e){return e>99?this.o[Math.floor(e/100)]+" hundred"+(e%100!==0?" "+this.U(e%100):""):this.U(e)},this.U=function(e){return 10>e?this.o[e]:e>=10&&20>e?this.T[e-10]:this.t[Math.floor(e/10)]+(e%10!==0?" "+this.o[e%10]:"")},this}

Now, paste it into your browser's JavaScript console, so you can produce the same results from within your browser with, for example:

Y(1234);

Examples (command line)

chiru@chiru ~ $ js num.js 28
28: fourteen plus fourteen times one
chiru@chiru ~ $ js num.js 7
7: impossible
chiru@chiru ~ $ js num.js 42
42: nine thousand sixty minus nine thousand eighteen

And in order to see the trick with which you can make each number work, just have a look at the boring answer for js num.js 1337:
1337: ten plus one thousand three hundred twenty seven times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one times one

The provided codes generates valid solutions for the given interval (and probably even above, you'd only have to raise the value of the variable L).

Statistics

I was interested in "how boring" the expressions were (or: how much the substring times one was used per expression within this algorithm), as this part was responsible for finding a solution for every number within the given interval. See for yourselves:

x: n-th expression (min. 0, max. 10,000)

y: number of occurences of substring " times one" within expression (min. 0, max. 1245)

Conclusions:

The expressions tend to get more and more boring in a linear manner.
Over 99% of solutions are boring.


Evaluating Parentheses and Brackets as Integers

CJam, 23

q"])(""1]:*0]:+["4/ers~

With BIG credits to Dennis! Try it online

Explanation:

The program converts the input to a CJam expression then evaluates it.
[…] becomes […1]:* (append 1 and multiply)
(…) becomes […0]:+ (append 0 and add)

q              read input
"])("          characters we want to replace
"1]:*0]:+["    replacement strings, concatenated
4/             split into strings of length 4: ["1]:*" "0]:+" "["]
er             replace (transliterate) the 3 characters with the 3 strings
s              convert the result (mixed characters and strings) to string
~              evaluate


GolfScript, 116 bytes

Since the scoring is in bytes, I figure that means we can use all bytes in the solution.  Going outside the printable ASCII set allows a somewhat shorter solution than Peter Taylor's, at the cost of making the code harder to display here.  Without the unprintable data, my code looks like this:

'57 BYTES OF BINARY DATA HERE'256base 26base 6/{;9.?rand}${6rand=65+.81='  u '2/=}%8/n*

It's pretty similar to Peter Taylor's solution, and I admit to shamelessly borrowing bits of it (such as the .81='  u '2/= trick), although I think I managed to shorten his shuffle slightly, even after spending an extra char byte for better randomness.

The binary string in the beginning of the script contains unprintable characters, and so cannot be directly pasted here.  Instead, I'll provide the script as a hex dump:

0000000: 2701 8302 7c56 97d5 ec9c 52e3 462e 44d7  '...|V....R.F.D.
0000010: a8d2 81c9 6115 fc80 4da4 6cd3 b06f a6d8  ....a...M.l..o..
0000020: 4e7e 2029 12a9 f331 0b83 3481 de36 81e2  N~ )...1..4..6..
0000030: 41b4 534d dee8 13f7 ccfd 2732 3536 6261  A.SM......'256ba
0000040: 7365 2032 3662 6173 6520 362f 7b3b 392e  se 26base 6/{;9.
0000050: 3f72 616e 647d 247b 3672 616e 643d 3635  ?rand}${6rand=65
0000060: 2b2e 3831 3d27 2020 7520 2732 2f3d 7d25  +.81='  u '2/=}%
0000070: 382f 6e2a                                8/n*

On Linux, or any system with the xxd utility installed, this hex dump can be turned back into a working 116-byte GolfScript program by passing it through xxd -r.

Edit: Replaced 999rand with 9.?rand for much better randomness.  The shuffle should now be about as close to perfect as the underlying RNG allows.


Level-headed Trader

This bot tries to make his quantities as equal as possible

command.txt

python leveller.py

leveller.py

import sys

def current_goods():
    print "G"
    return parse_goods(readline())

def parse_goods(good_string):
    return dict([(a, int(b))
                 for a, b in [product.split("-")
                              for product in good_string.split(",")]])

def get_minimum(goods):
    cur_min = 200
    min_good = "X"
    for good, amount in goods.items():
        if amount < cur_min:
            min_good = good
            cur_min = amount
    return min_good

def get_maximum(goods):
    cur_max = -1
    max_good = "X"
    for good, amount in goods.items():
        if amount > cur_max:
            max_good = good
            cur_max = amount
    return max_good

def add_goods(x, y):
    return {k: int(x.get(k, 0)) + int(y.get(k, 0)) for k in set(x) | set(y)}

def readline():
    line = sys.stdin.readline().strip()
    if line == 'Q' or not line:
        exit()
    return line

def output_goods(goods):
    print ",".join([good+"-"+str(amount) for good, amount in goods.items()])

def output_good(good, amount):
    print good+"-"+str(amount)

def current_turn_is(turn):
    print "T"
    return readline() == turn

turns = MARKET, PRODUCE, TRADING, SKIPPED = "M", "P", "T", "S"
market_options = PURCHASE, SELL = "P", "S"
items = APRICOTS, BOARS, CANARIES, DAFFODILS, EARWIGS, NOTHING = "A", "B", "C", "D", "E", "X"

productivity = parse_goods(readline())
while True:
    product_to_produce = get_minimum(current_goods())
    print product_to_produce
    while current_turn_is(MARKET):
        print SELL
        if readline() != SKIPPED:
            maximum = get_maximum(current_goods())
            goods = {"A": 1, "B": 1, "C": 1, "D": 1, "E": 1}
            del goods[maximum]
            output_good(maximum, 1)
            output_goods(goods)


Find all number pairs that sum to 121212

C++

#include<iostream>
using namespace std;
#include<algorithm>

int main()
{
    long long N,F,S;
    char str[11]="1023456789";
    while (1) {
        sscanf(str,"%lld",&N);
        F=N/100000;S=N%100000;
        if (F>60000)
           break;
        if (F+S==121212)
           printf("%lld %lld\n",F,S);
        next_permutation(str,str+10);
    }
}

http://www.ideone.com/Lr84g


Jelly, 27 bytes

,UŒDḢ$S$€,Ṛ$j€SW€jSẋ¥€2$j"$

Try it online!


GraphicsMagick/ImageMagick

Ordered Dither:

magick B2DBy.jpg -gamma .45455 -ordered-dither [all] 4x4 ordered4x4g45.pbm

Before complaining about my using an "established algorithm" please read the ChangeLog for GraphicsMagick and ImageMagick for April 2003 where you'll see that I implemented the algorithm in those applications.  Also, the combination of "-gamma .45455" with "-ordered-dither" is new.

The "-gamma .45455" takes care of the image being too light.  The "all" parameter is only needed with GraphicsMagick.

There's banding because there are only 17 graylevels in a 4x4 ordered-dither image.
The appearance of banding can be reduced by using an 8x8 ordered-dither which has 65 levels.

Here are the original image, the 4x4 and 8x8 ordered dithered output and the random-threshold output:

I prefer the ordered-dither version, but am including the random-threshold version for completeness.

magick B2DBy.jpg -gamma .6 -random-threshold 10x90% random-threshold.pbm

The "10x90%" means to render below 10 percent intensity pixels as pure black and above 90 percent as pure white, to avoid having a few lonely specks in those areas.

It's probably worth noting that both are as memory-efficient as they can possibly be.  Neither does any diffusion, so they work one pixel at a time, even when writing ordered-dither blocks, and don't need to know anything about the neighboring pixels.  ImageMagick and GraphicsMagick process a row at a time, but it's not necessary for these methods.  The ordered-dither conversions take less than .04 second real time on my old x86_64 computer.


Find the smallest illegal (probable) prime


Piet (honorary answer)

Snakes its way downwards, running out the right through blue and re-entering through green. Prints out "Fruit flies like a banana."

I used PietCreator to make this, but you can try it out here. Remaking Piet programs is a pain, so I started out at 35x35 and continued that way, meaning that I used a lot more codels than I needed.

Actual size versions


Distance between two points in n-dimensional space

MATL, 2 bytes
ZP

Try it online!
The ZP function (corresponding to MATLAB's pdist2) computes all pairwise distances between two sets of points, using Euclidean distance by default. Each set of points is a matrix, and each point is a row. In this case it produces a single result, which is the distance between the two points.


JavaScript (ES6), 116 bytes

f=(a,p=i=0)=>1/a[p]?f(a,p+p+1,a.splice(p,0,0)):[...Array(p)].map(_=>i&++i?~~a[i-1]:a.reduce((p,e,j)=>p^=++j&i&&e,0))

If the padding is unnecessary, then for 97 bytes:

f=(a,p=i=0)=>1/a[p]?f(a,p+p+1,a.splice(p,0,0)):a.map(e=>i&++i?e:a.reduce((p,e,j)=>p^=++j&i&&e,0))


Use parameter untupling
Parameter untupling allows you to write functions accepting a single tuple as input as if they were functions accepting 2 parameters. Basically, you can replace these
list.map{case(a,b)=>a+b}
//and
list.map{case(a,b)=>Seq(a,b)}
//or
list.map(t=>t._1+t._2)
//and
list.map(t=>Seq(t._1,t._2))

with this, which is both shorter and more beautiful.
list.map(_+_)
//and
list.map(Seq(_,_))


MATL, 17 16 bytes
9:qWIe1Y6Z+i)BPf

The array is 1-based, that is, contains numbers from 1 to 9.
Try it online! Or verify all test cases.
Explanation
Consider input 2 as an example.
9:q  % Push [0 1 2 ... 8]
     % STACK: [0 1 2 ... 8]
W    % Rise to 2, element-wise
     % STACK: [1 2 4 ... 256]
Ie   % Reshape as 3-row matrix (column-major order)
     % STACK: [1   8  64;
               2  16 128;
               4  32 256]
1Y6  % Push [0 1 0; 1 0 1; 0 1 0]
     % STACK: [1   8  64;
               2  16 128;
               4  32 256],
              [0   1   0;
               1   0   1;
               0   1   0]
Z+   % Convolution, maintaining size
     % STACK: [10  81 136;
               21 170 336;
               34 276 160]
i    % Take input, n
     % STACK: [10  81 136;
               21 170 336;
               34 276 160],
               2
 )   % Get n-th entry (1-based; column-major order)
     % STACK: 21
B    % Convert to binary
     % STACK: [1 0 1 0 1]
P    % Flip
     % STACK: [1 0 1 0 1]
f    % Find: gives indices of nonzeros. Implicitly display
     % STACK: [1 3 5]


Pyth, 25 23 bytes

pdJef!-T<G7+k.:@Grz0)lJ

2 bytes saved thanks to @Jakube.

Demonstration. Test harness.

Explanation:

rz0: The input, in lowercase.
@Grz0: Strip any non-alphabetic characters.
.:@Grz0): Generate all substrings.
+k.:@Grz0): Add in the empty string.
f ... +k.:@Grz0): Filter over these strings.
-T<G7: Filter each string for non musical characters.
!-T<G7: Negate the result. This is True if and only if the string was musical.
f!-T<G7+k.:@Grz0): Filter out the musical strings.
ef!-T<G7+k.:@Grz0): Take the last such string. .: orders substrings by size, so this is also the longest musical substring.
Jef!-T<G7+k.:@Grz0): Assign the result to J.
pdJ: Print J, with d, space, as the ending character.
lJ: Then, print the length of J.


Pyth, 12 bytes

ls.-M.prR0.z

Test suite

The operation in question is equivalent to Pyth's bagwise subtraction operator, .-, applied in both directions. You could call it bagwise xor, I suppose.

The solution is:

.z: get input as list of 2 strings.

rR0: convert both to lowercase.

.p: Form all permutations, i.e. normal and reversed.

.-M: Map the .- operation over each ordering.

s: Concatenate the results.

l: Print the length.


Number of solutions to a binary weight equation

MATL, 15 bytes

t4*:tB!s&=Rs-=s

Try it online! Or verify all test cases.

This makes use of the following result:

Claim

\$a(n) \le 3n/4\$ for \$n \geq 3\$.

Here is a graphical illustration. The bound is quite loose, but it is sufficient to establish that only a finite number of values of \$k\$ need to be tested for a given \$n\$ (more on that in “How the code works”).

Proof

The sequence \$a(n)\$ (A263017) is the amount of numbers in the set \$\{1,2,\ldots,n\}\$ that have the same binary weight as \$n\$. The binary expansion of \$n\$ has \$b \leq \log_2 n + 1\$ digits, with a leading 1. Let \$w\$ be the binary weight of \$n\$. Clearly \$w \in \{0,\ldots,b\}\$.

The number of unique permutations of the binary expansion of \$n\$, not necessarily with a leading 1, is \${b\choose w}\$. \$a(n)\$ will be at most equal to this value. It can be less, because some of the permutations may produce a number exceeding \$n\$. Thus,

$$
a(n) \leq {b\choose w}.
$$

For \$b\$ even, the bound

$$
{2m \choose m} \leq \frac{4^m}{\sqrt{3m+1}} \text{ for all } m \geq 1
$$

and the fact that \${b\choose w} \leq {b\choose b/2}\$ imply that

$$
{b \choose w} \leq \frac{2^b}{\sqrt{\frac{3b+2}{2}}}.
$$

For \$b\$ not necessarily even, the bound holds with \$b\$ replaced by \$b+1\$:

$$
{b \choose w} \leq \frac{2^{b+1}}{\sqrt{\frac{3b+5}{2}}}.
$$

Since \$b \leq \log_2 n + 1\$,

$$
a(n) \leq {b\choose w} \leq \frac{2^{b+1}}{\sqrt{\frac{3b+5}{2}}} \leq \frac{4n}{\sqrt{ 3/2 \cdot \log_2 n + 4}}.
$$

This is less than \$3n/4\$ for \$n \geq 80478\$, because

$$
\sqrt{3/2 \cdot \log_2 80478 + 4}\ = 5.3333348 > 16/3.
$$

For \$n = 3, \ldots, 80477 \$, direct computation of \$a(n)\$ shows that \$a(n) \leq 3n/4\$. Therefore \$a(n) \leq 3n/4\$ for \$n \geq 3\$.

How the code works

The above result implies that

$$
k-a(k) \geq k / 4.
$$

for all \$k \geq 3\$. Thus, given \$n\$, to compute the number of positive integers \$k\$ that satisfy

$$
k-a(k)\ = n
$$

it suffices to test the latter equality for \$k = 1, \ldots, 4n\$.

Consider input 1 as an example.

t4*  % Implicit input: n. Duplicate. Multiply by 4
     % STACK: 1, 4
:    % Range. Gives [1 2 ... 4*n]. This is the vector of k values
     % STACK: 1, [1 2 3 4]
tB   % Duplicate. Binary expansion. Gives a binary matrix, where each row
     % corresponds to a value of k
     % STACK: 1, [1 2 3 4], [0 0 1;
                             0 1 0;
                             0 1 1;
                             1 0 0]
!s   % Tranpose. Sum of each column. This gives the binary weights
     % STACK: 1, [1 2 3 4], [1 1 2 1]
&=   % Matrix of pair-wise equality comparisons
     % STACK: 1, [1 2 3 4], [1 1 0 1;
                             1 1 0 1;
                             0 0 1 0;
                             1 1 0 1]
R    % Upper triangular part. This sets elements below the diagonal to 0
     % STACK: 1, [1 2 3 4], [1 1 0 1;
                             0 1 0 1;
                             0 0 1 0;
                             0 0 0 1]
s    % Sum of each column. For each column k, this gives the amount of
     % number up to k with the same weight as k; that is, a(k). Note that
     % the condition "up to k" corresponds to having taken the upper
     % triangular part of the matrix
     % STACK: 1, [1 2 3 4], [1 2 1 3]
-    % Subtract, element-wise. This gives k-a(k)
     % STACK: 1, [0 0 2 1]
=    % Equality comparison, element-wise. This compares n with each
     % value k-a(k)
     % STACK: [0 0 0 1]
s    % Sum. Implicit display
     % STACK: 1


Is there a language that supports Turing machines?

It should be acceptable to post answers in pure turing machine code. I have seen people do this before.
Examples:
https://codegolf.stackexchange.com/a/200380/95627
Simple cat program
If anyone knows more about this, you can edit.