Python 2: 151 chars

N=2*input()
for i in range(2**N):
 L=[];c=1;exec"b=i%2;c+=2*b-1;L+=[[' ']*N];L[-1][b-c]='\/'[b];i=i/2*(c>0);"*N
 for x in(c==1)*zip(*L):print"".join(x)

#Output for n=3:

  /\
 /  \
/    \

 /\/\
/    \

   /\
/\/  \

 /\
/  \/\

/\/\/\

Wow, this is a mess.

The first idea is to use the numbers 0 to 2**N-1 to encode all sequences of N up-moves and down-moves in their bits. We read off these bits one by one by repeated %2 and /2, iterated in an exec loop.

We store the running mountain range sideways in a transposed list of strings L. Each time, we generate a new a row of spaces are replace one space in the new row with / or \ depending on whether an up-move or down-move happened.

The index of that space is c spaces from the end, where c is the running height. Doing it from the front would make the mountains upside down. We further shift it by b to align upward and downward moves , getting [b-c]. Starting c at 1 rather than 0 fixes an off-by-one error.

To eliminate cases where c dips below the start value 1, when this happens, we set i to 0, which causes all further moves to be downward, making c become more negative. Then, when we check whether c ended at 1, we also check whether c ever fell below it. We only print the mountain range if c is 1.

To print, we do zip(*L) to transpose the range from vertical to horizontal, and print each joined string. A lot of trouble in this answer came from Python treats strings as immutable, so we worked with them as lists of characters and only joined them into strings for printing.

Thanks to @flornquake for help and improvements.


Code golf: Solve a Knights and Knaves logic problem by parsing English

Python, 491 chars

Works by converting each line to a Python expression, and eveluating it.
The knave and knight are evaluated as 0 and 1. For the two people, we try both options.
For example, Joe: Steve is a knave becomes Joe==(Steve==knave). This way, if Joe is a knave, the result is true only if he's lying.
You get ugly errors when it's impossible or undecided. If impossible, r[0] is an index error, because r is empty. If undecidable, concatenating r[1:] to a list of strings causes trouble.

import sys
def p():
    a=s.pop(0)
    try:return{"both":"(%s*%s)","either":"(%s|%s)","neither":"(1-(%s|%s))"}[a.lower()]%(p(),p())
    except KeyError:r=s[2];del s[:4];return"(%s==%s)"%((a,m)[a=="I"],r)
x=[];w=[]
for l in sys.stdin:
    m,l=l.split(":");w+=[m]
    for s in l.split("."):
        s=s.split()
        while s:x+=["%s==%s"%(m,p())]
k=("knave","knight")
r=[a for a in[{w[0]:z,w[1]:1-z}for z in(0,1)]if all(eval(l,{k[0]:0,k[1]:1},a)for l in x)]
print"\n".join(x+" is the "+k[r[0][x]]+"."for x in w+r[1:])


all non-empty sublists partitionings of a list

66 bytes
p=lambda l:[q+[l[i:]]for i in range(len(l))for q in p(l[:i])]or[l]

If the last part is changed from [l] to [[]], then it can also be used with tuples or strings, in addition to lists.


Find the numbers coprime to their decimal digits

Plain English 853 787 738 594 550 538 532 bytes

Removed 66 bytes of white space.  Removed 49 bytes by using a more generic output type.  Removed 144 bytes by abbreviating variable names, and reusing the quotient and the remainder.  Removed 44 bytes by abbreviating an interface.  Shortened Destroy the number things. to Destroy the L.  Removed 6 bytes by changing "some" to "a", and "number" to "count".

Golfed code:

To create a L number things given a c count:
Put 0 in a i count.
Loop.
Add 1 to a n count.
If the i is at least the c, exit.
If the n is g,
append the n to the L;
add 1 to the i.
Repeat.
To decide if a n count is g:
If the n is at most 10, say no.
Put 1 in a m count.
Loop.
If the m is greater than the n, say yes.
Divide the n by the m giving a q quotient and a r remainder.
Divide the q by 10 giving the q and the r.
Get a gcd given the n and the r.
If the gcd is at least 2, say no.
Multiply the m by 10.
Repeat.

Ungolfed code:

Some special numbers are some number things.

To create some special numbers given a count:
  Put 0 in another count.
  Loop.
    Add 1 to a number.
    If the other count is at least the count, exit.
    If the number is coprime with its digits,
      Append the number to the special numbers;
      Add 1 to the other count.
  Repeat.

To decide if a number is coprime with its digits:
  If the number is at most 10, say no.
  Put 1 in another number.
  Loop.
    If the other number is greater than the number, say yes.
    Divide the number by the other number giving a quotient and a remainder.
    Divide the quotient by 10 giving another quotient and another remainder.
    Get a gcd given the number and the other remainder.
    If the gcd is greater than 1, say no.
    Multiply the other number by 10.
  Repeat.

"Some number things" are a doubly-linked list of numbers.
The calling code has the responsibility to Destroy the special numbers., so I have added the corresponding bytes.

The Plain English IDE is available at github.com/Folds/english.  The IDE runs on Windows.  It compiles to 32-bit x86 code.


Iterate over the neighborhood of a string

Haskell, 115 109 bytes

-6 thanks to Unrelated String

import Data.List
f=nub.(=<<)g.g
g=(=<<)h.(zip.inits<*>tails)
h(x,y)=[x++b++c|b<-["a","b",""],c<-[y,drop 1 y]]

Try it online!
Explanation:

f :: String -> [String]
f=nub    -- delete duplicates
 .(=<<)g -- apply g to every result (get all words with distance <= 2)
 .g      -- apply g once to the input (get all words with distance <= 1)

g :: String -> [String]
g=(=<<)h               -- apply h to every split and flatten the resulting list
 .(zip.inits<*>tails)  -- split the string at every possible position

{- |
h takes a pair of Strings (x,y the input split at some point) and returns all
combinations of x, one of a, b or nothing, and y with the first letter present
or removed
("he","llo") -> ["heallo","healo","hebllo","heblo","hello","helo"]
drop 1 is basically the same as tail with the difference that drop 1 [] returns
[] instead of throwing an error
-}
h :: (String,String) -> [String]
h(x,y)=[x++b++c|b<-["a","b",""],c<-[y,drop 1 y]]


Python 3, 57 bytes
lambda s:eval(s.upper().translate({70:'+[',87:']*'})[1:])

Turns a string like
f1w0f2w10

into a expression like
[1]*0+[2]*10

that it evaluated as code. This is done by turning the string uppercase, turning each f into +[ and each w into ]*, and removing the initial +. Thanks to Dennis for saving 7 bytes in Python 3 by using translate with a dictionary.


JavaScript (ES6),  130 128 126  125 bytes
Takes input as \$(m)(l)\$ where \$m\$ is a binary matrix describing the room layout (\$0\$ = wall, \$1\$ = empty) and \$l\$ is the list of distances.
Returns another binary matrix where each valid position is marked with \$1\$.

m=>l=>m.map((r,y)=>r.map((v,x)=>v&!!([...'3210321'].map(d=>(g=X=>(m[Y+=~-d%2]||0)[X+=(d-2)%2]?1+g(X):0)(x,Y=y))+g).match(l)))

Try it online! (with post-processed output for readability)
Commented
m => l =>                         // m[] = layout matrix; l[] = list of distances
  m.map((r, y) =>                 // for each row r[] at position y in m[]:
    r.map((v, x) =>               //   for each cell v at position x in r[];
      v &&                        //     yield 0 if v = 0
      !!(                         //     otherwise, test whether we can find l[] within a
        [...'3210321']            //     list containing twice the results of the sensors
        .map(d =>                 //       for each direction d:
          (g = X => (             //         g = recursive function taking X
              m[Y += ~-d % 2]     //         add dy[d] to Y
              || 0                //         use a dummy object if we're out of the board
            )[X += (d - 2) % 2] ? //         add dx[d] to X; if (m[Y] || 0)[X] is equal to 1:
              1 +                 //           add 1 to the final result
              g(X)                //           and do a recursive call
            :                     //         else:
              0                   //           yield 0 and stop recursion
          )(x, Y = y)             //         initial call to g with X = x and Y = y
        )                         //       end of map() over directions
        + g                       //       coerce the result to a comma-separated string,
                                  //       followed by harmless garbage
      ).match(l)                  //     test whether l[] can be found in this string
                                  //     (l[] is implicitly coerced to a string as well)
    )                             //   end of map() over r[]
  )                               // end of map() over m[]


CJam, 64 60 58 bytes

]ri:X{'|'}{I))*\I**XX*)Se[s}:L~:M.e>S'-LaI*~M}fI]zN*'}/'+*

Constructing each column at a time.

Try it online here


Java (JDK), 570 bytes

t->{return "Routes = "+Arrays.deepToString(Arrays.stream(r(t.get(0).get(0),t,t.get(0).get(0)).split("\\[")).filter(d->d.endsWith("]")).map(d->d.replaceAll("]", "")).map(d->d.split("(?=[A-Z])")).collect(Collectors.toList()).toArray());};String r(String s, List<List<String>>t, String b){List<String>o = t.stream().filter(e->e.get(0).equals(s)).map(e->e.get(1)).collect(Collectors.toList());if(s.matches("^S(?!(?:1)$)\\d+"))return s;if(o.size()>1){String x="";for(String n:o){x+="["+b+r(n,t,b+n)+"]";}return x;}if(o.size()==1)return s+r(o.get(0),t,b+o.get(0));return "]";}

As you may notice by my code I´m still learning a lot every day.
My answer is neighter pretty nor short and I honestly even hope this works for different testcases even though I tested a couple.
But I hope that this question gets the attention it deserves and there will be more answers I can learn from.

INPUT

String[][] STEP = { { "S1", "B3" },  ... ,{ "B14", "T2" }, { "B14", "T10" } };
List<List<String>> tupels = Arrays.stream(STEP).map(Arrays::asList).collect(Collectors.toList());
z(tupels);

I converted your given Input into an 2D-Java-Array String[][] and converted that into a List<List<String>>.

CODE

The first method calls a recursive method to get all routes and formats the output.

t->{
return "Routes ="+Arrays.deepToString(
  Arrays.stream(r(t.get(0).get(0),t,t.get(0).get(0)).split("\\["))
 .filter(d->d.endsWith("]")).map(d->d.replaceAll("]", ""))
 .map(d->d.split("(?=[A-Z])")).collect(Collectors.toList()).toArray());
};

The second method is the recursive method which gathers all the possible routes

String r(String s, List<List<String>>t, String b){
  List<String>o =t.stream().filter(e->e.get(0).equals(s)).map(e->e.get(1))
  .collect(Collectors.toList());
  if(s.matches("^S(?!(?:1)$)\\d+"))
    return s;
  if(o.size()>1){
    String x="";
    for(String n:o){
      x+="["+b+r(n,t,b+n)+"]";
    }
    return x;
  }
  if(o.size()==1)
    return s+r(o.get(0),t,b+o.get(0));
  return "]";
}

Try it online!


Recursively concatenated cumulative sums of [N] with M iterations

Haskell, 35 bytes

n!m=iterate((++)<*>scanl1(+))[n]!!m

Try it online!

Thanks to H.PWiz for -18 bytes


JavaScript (ES6), 319 313 bytes

f=
n=>{s=`<svg viewBox=${n*=-12},${n},${n*=-2},${n}><use href=#d transform=rotate(180) /><g id=d><use href=#s transform=rotate(90) /><path id=s fill=none stroke=#000 d=`
for(n/=24;n--;)for(j=0;j<=n;j++)s+=`M${n*5+j*7},${n*12-j*7}h7l5,5v7h-7l-5,-5z`+(j<n?`M${n*12},${n*5-j*10}h7l5,-5l-5,-5h-7l-5,5z`:``)
return s+`>`}
<input type=number min=1 oninput=o.innerHTML=f(this.value)><div id=o>

Output is an HTML5 SVG, which the snippet inserts into a DOM node so that you can see it. Output is rotated by 45° as allowed by the question. Edit: Saved 3 bytes thanks to @KevinCruijssen.


C, 74 70 bytes

Thanks to @Johan du Toit for saving 4 bytes!

i;f(x,y){for(i=y;i--;)printf("%*c\n",(int)round((i-y)/(-1.*y/x)),35);}

Try it online!


Mathematica, 15 bytes

Order@@Mean/@#&

Try it online!

Function which expects a list of two lists. Mean/@# takes the arithmetic mean of each list in the input, then those means are passed into Order, which returns -1 if the first list wins, 0 if there is a tie, and 1 if the second list wins.


JavaScript (ES6), 127 124 119 bytes

Saved 3 bytes thanks to nderscore

m=>(F=(x,y)=>m.map((r,Y)=>r.map((i,X)=>i?1/y?n+=x<X&y<=Y&(g=(a,b)=>(m[b+X-x]||0)[a-Y+y])(x,y)&g(X,Y):F(X,Y):0)))(n=0)|n

How?

This function iterates on all pairs of cells (x, y), (X, Y) of the input matrix m such that:

m[ x, y ] = m[ X, Y ] = 1
x < X
y ≤ Y

Each matching pair describes the coordinates of a potential edge of a square. The inequations guarantee that each edge is tested only once.

We use the vector [ dx, dy ] = [ X - x, Y - y ] rotated 90° clockwise to test the cells located at [ x - dy, y + dx ] and [ X - dy, Y + dx ]. If they both contain a 1, we've found a valid square.

Test cases

let f =

m=>(F=(x,y)=>m.map((r,Y)=>r.map((i,X)=>i?1/y?n+=x<X&y<=Y&(g=(a,b)=>(m[b+X-x]||0)[a-Y+y])(x,y)&g(X,Y):F(X,Y):0)))(n=0)|n

console.log(f([
  [0,0,0,1,0,0,0],
  [1,0,0,0,0,0,0],
  [0,0,0,0,0,0,0],
  [0,0,0,0,1,0,0],
  [0,1,0,0,0,0,0]
]));

console.log(f([
  [1,0,1,0,1],
  [0,0,0,0,0],
  [1,0,1,0,0],
  [0,0,0,0,0],
  [1,0,0,0,1]
]));

console.log(f([
  [1,1,1,1],
  [1,1,1,1],
  [1,1,1,1],
  [1,1,1,1]
]));


Python 2, 78 bytes

f=lambda n,l=[]:sum([f(n,l+[i+1])for i in range(n)if~-(i+1in l)],[l]*(n in l))

Try it online!
Python 3 lets us save some bytes with set unpacking.
Python 3, 74 bytes

f=lambda n,l=[]:sum([f(n,l+[i])for i in{*range(1,n+1)}-{*l}],[l]*(n in l))

Try it online!


Jelly, 7 6 bytes
Rb9ḌİS

Try it online!
-1 byte thanks to @Razetime
Takes input 1-indexed as an argument (footer on TIO converts to 0-indexed like in test cases)
Returns the nth partial sum
How it Works
Let's look at the denominators in base 10:
\$[1, 2, 3, 4, 5, 6, 7, 8, 10,11,12,13,...]\$ (base 10)
Since these consist of the nine base-9 digits, we can interpret them as  base 9 strings:
\$[1_9, 2_9, 3_9, 4_9, 5_9, 6_9, 7_9, 8_9, 10_9, 11_9, 12_9, 13_9, ...]\$
\$=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]\$ (base 10)
So all of the denominators can be generated as natural numbers, converted to base 9, then interpreted as base 10.
Rb9ḌİS - main link, taking n (1-indexed)
R       - convert to list [1..n]
 b9     - convert each natural number to base 9
   Ḍ   - interpret each base-9 string as base 10 (decimal)
    İ  - reciprocal
     S - sum


JavaScript (ES6), 18 bytes

f=n=>m=>m?f(m+n):n

Pass a falsy value to retrieve the sum. Zeros could be allowed for a cost of 2 bytes.

Try it online

Ungolfed:

f = function(n) {
    return function(m) {
        if (m) {
            return f(m+n);
        } else {
            return n;
        }
    }
}


Jelly, 14 bytes
ḊṖVr/ḟ×ɗċⱮØ($S

A monadic Link accepting a list of characters that yields the sum of the described range.
Try it online! Or see the test-suite.
How?
ḊṖVr/ḟ×ɗċⱮØ($S - Link: list of characters, R  e.g. "[5,8)"
Ḋ              - dequeue                           "5,8)"
 Ṗ             - pop                               "5,8"
  V            - evaluate as Jelly                 [5,8]
                 (call that X)
            $  - last two links as a monad - f(R):
          Ø(   -   list of characters = "()"       "()"
         Ɱ     -   map across these with:
        ċ      -     count ocuurences (in R)       [0,1]
                     (call that Y)
       ɗ       - last three links as a dyad - f(X,Y):
    /          -   reduce (X) with:
   r           -     inclusive range               [5,6,7,8]
      ×        -   (X) multiply (Y) (vectorises)   [0,8]
     ḟ         -   filter discard                  [5,6,7]
             S - sum                               18


><>, score 479 - 479 = 0
lllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllbfppllfepeeppppgglcepppbeppppppppppplfdppedpddpgglcdppbdpfcpecpggldcppllccpbcpplfbpebppldbppcbpggcbglefgpgbeglefgpgcbglefgpgggggedglefgpgccglefgpgfdglefgpgebglefgpgecglefgpggdcglefgpgceglefgpgeeglefgpgbcglefgpgfbglefgpgcdgfefgpbdgeefgpfegdefgpccgcefgpfdgbefgpdbgaefgpppddglefgpgbcglefgpgfcglefgpgdbglefgpgdcglefgpgecglefgpgddglefgpgdbglefgplffpbfgffgefgpcbgefgefgp

Try it online!
How it works
Very few useful instructions in ><> are letters.
However, we still have the l, pushing the length of the stack to the stack. As such, it's possible to (very verbosely) push arbitrary values to the stack. Thus, strings can be encoded in a similar fashion to brainfuck, using a to increase the length of the stack, and g or p to reduce it.
As per usual quine rules, g is not used to read the source code itself, instead maintaining registers at locations such asbb and bc and so on.
The string encoded is the prefix:
"r&:20&3-:&?.p48*-od0l2)?.;lllll"]"
Which after over 7,000 instructions outputs the original string in upper case.


Solve the 15 Puzzle (the tile-sliding puzzle)

PyPy, 195 moves, ~12 seconds computation

Computes optimal solutions using IDA* with a 'walking distance' heuristic augmented with linear conflicts. Here are the optimal solutions:

 5  1  7  3
 9  2 11  4
13  6 15  8
 0 10 14 12
Down, Down, Down, Left, Up, Up, Up, Left, Down, Down, Down, Left, Up, Up, Up

 2  5 13 12
 1  0  3 15
 9  7 14  6
10 11  8  4
Left, Down, Right, Up, Up, Left, Down, Down, Right, Up, Left, Left, Down, Right, Right, Right, Up, Up, Left, Left, Down, Left, Up, Up, Right, Down, Down, Left, Up, Up, Right, Right, Right, Down, Left, Up, Right, Down, Down, Left, Left, Down, Left, Up, Up, Right, Up, Left

 5  2  4  8
10  0  3 14
13  6 11 12
 1 15  9  7
Left, Up, Up, Right, Right, Down, Left, Up, Left, Left, Down, Down, Right, Right, Up, Left, Left, Down, Down, Right, Right, Up, Right, Up, Left, Left, Up, Right, Down, Down, Right, Down, Left, Left, Up, Up, Left, Up

11  4 12  2
 5 10  3 15
14  1  6  7
 0  9  8 13
Down, Left, Down, Right, Up, Left, Left, Left, Down, Down, Right, Right, Right, Up, Left, Left, Left, Down, Right, Right, Up, Left, Up, Up, Left, Down, Down, Right, Down, Right, Up, Up, Right, Up, Left, Left, Left, Down, Right, Right, Right, Up, Left, Down, Left, Down, Left, Up, Up

 5  8  7 11
 1  6 12  2
 9  0 13 10
14  3  4 15
Up, Right, Down, Left, Left, Down, Left, Up, Right, Up, Right, Down, Down, Right, Up, Up, Left, Left, Left, Down, Down, Down, Right, Right, Up, Right, Down, Left, Up, Left, Up, Left, Down, Right, Down, Left, Up, Right, Down, Right, Up, Up, Left, Left, Up

And the code:

import random

class IDAStar:
    def __init__(self, h, neighbours):
        """ Iterative-deepening A* search.

        h(n) is the heuristic that gives the cost between node n and the goal node. It must be admissable, meaning that h(n) MUST NEVER OVERSTIMATE the true cost. Underestimating is fine.

        neighbours(n) is an iterable giving a pair (cost, node, descr) for each node neighbouring n
        IN ASCENDING ORDER OF COST. descr is not used in the computation but can be used to
        efficiently store information about the path edges (e.g. up/left/right/down for grids).
        """

        self.h = h
        self.neighbours = neighbours
        self.FOUND = object()

    def solve(self, root, is_goal, max_cost=None):
        """ Returns the shortest path between the root and a given goal, as well as the total cost.
        If the cost exceeds a given max_cost, the function returns None. If you do not give a
        maximum cost the solver will never return for unsolvable instances."""

        self.is_goal = is_goal
        self.path = [root]
        self.is_in_path = {root}
        self.path_descrs = []
        self.nodes_evaluated = 0

        bound = self.h(root)

        while True:
            t = self._search(0, bound)
            if t is self.FOUND: return self.path, self.path_descrs, bound, self.nodes_evaluated
            if t is None: return None
            bound = t

    def _search(self, g, bound):
        self.nodes_evaluated += 1

        node = self.path[-1]
        f = g + self.h(node)
        if f > bound: return f
        if self.is_goal(node): return self.FOUND

        m = None # Lower bound on cost.
        for cost, n, descr in self.neighbours(node):
            if n in self.is_in_path: continue

            self.path.append(n)
            self.is_in_path.add(n)
            self.path_descrs.append(descr)
            t = self._search(g + cost, bound)

            if t == self.FOUND: return self.FOUND
            if m is None or (t is not None and t < m): m = t

            self.path.pop()
            self.path_descrs.pop()
            self.is_in_path.remove(n)

        return m

def slide_solved_state(n):
    return tuple(i % (n*n) for i in range(1, n*n+1))

def slide_randomize(p, neighbours):
    for _ in range(len(p) ** 2):
        _, p, _ = random.choice(list(neighbours(p)))
    return p

def slide_neighbours(n):
    movelist = []
    for gap in range(n*n):
        x, y = gap % n, gap // n
        moves = []
        if x > 0: moves.append(-1)    # Move the gap left.
        if x < n-1: moves.append(+1)  # Move the gap right.
        if y > 0: moves.append(-n)    # Move the gap up.
        if y < n-1: moves.append(+n)  # Move the gap down.
        movelist.append(moves)

    def neighbours(p):
        gap = p.index(0)
        l = list(p)

        for m in movelist[gap]:
            l[gap] = l[gap + m]
            l[gap + m] = 0
            yield (1, tuple(l), (l[gap], m))
            l[gap + m] = l[gap]
            l[gap] = 0

    return neighbours

def slide_print(p):
    n = int(round(len(p) ** 0.5))
    l = len(str(n*n))
    for i in range(0, len(p), n):
        print(" ".join("{:>{}}".format(x, l) for x in p[i:i+n]))

def encode_cfg(cfg, n):
    r = 0
    b = n.bit_length()
    for i in range(len(cfg)):
        r |= cfg[i] << (b*i)
    return r

def gen_wd_table(n):
    goal = [[0] * i + [n] + [0] * (n - 1 - i) for i in range(n)]
    goal[-1][-1] = n - 1
    goal = tuple(sum(goal, []))

    table = {}
    to_visit = [(goal, 0, n-1)]
    while to_visit:
        cfg, cost, e = to_visit.pop(0)
        enccfg = encode_cfg(cfg, n)
        if enccfg in table: continue
        table[enccfg] = cost

        for d in [-1, 1]:
            if 0 <= e + d < n:
                for c in range(n):
                    if cfg[n*(e+d) + c] > 0:
                        ncfg = list(cfg)
                        ncfg[n*(e+d) + c] -= 1
                        ncfg[n*e + c] += 1
                        to_visit.append((tuple(ncfg), cost + 1, e+d))

    return table

def slide_wd(n, goal):
    wd = gen_wd_table(n)
    goals = {i : goal.index(i) for i in goal}
    b = n.bit_length()

    def h(p):
        ht = 0 # Walking distance between rows.
        vt = 0 # Walking distance between columns.
        d = 0
        for i, c in enumerate(p):
            if c == 0: continue
            g = goals[c]
            xi, yi = i % n, i // n
            xg, yg = g % n, g // n
            ht += 1 << (b*(n*yi+yg))
            vt += 1 << (b*(n*xi+xg))

            if yg == yi:
                for k in range(i + 1, i - i%n + n): # Until end of row.
                    if p[k] and goals[p[k]] // n == yi and goals[p[k]] < g:
                        d += 2

            if xg == xi:
                for k in range(i + n, n * n, n): # Until end of column.
                    if p[k] and goals[p[k]] % n == xi and goals[p[k]] < g:
                        d += 2

        d += wd[ht] + wd[vt]

        return d
    return h

if __name__ == "__main__":
    solved_state = slide_solved_state(4)
    neighbours = slide_neighbours(4)
    is_goal = lambda p: p == solved_state

    tests = [
        (5,1,7,3,9,2,11,4,13,6,15,8,0,10,14,12),
        (2,5,13,12,1,0,3,15,9,7,14,6,10,11,8,4),
        (5,2,4,8,10,0,3,14,13,6,11,12,1,15,9,7),
        (11,4,12,2,5,10,3,15,14,1,6,7,0,9,8,13),
        (5,8,7,11,1,6,12,2,9,0,13,10,14,3,4,15),
    ]

    slide_solver = IDAStar(slide_wd(4, solved_state), neighbours)

    for p in tests:
        path, moves, cost, num_eval = slide_solver.solve(p, is_goal, 80)
        slide_print(p)
        print(", ".join({-1: "Left", 1: "Right", -4: "Up", 4: "Down"}[move[1]] for move in moves))
        print(cost, num_eval)


ES6, 83 bytes

a=>a.map(([x,y])=>r+=Math.atan2(y*b-x*c,y*c+x*b,b=x,c=y),b=c=r=0)&&r/Math.PI/2

Takes as input an array of pairs of points which are interpreted as complex numbers. Rather than converting each point into an angle, the points are divided by the previous point, which Math.atan2 then converts into an angle between -π and π, thus automatically determining which way the path is winding. The sum of the angles is then 2π times the winding number.

Since Math.atan2 doesn't care about the scale of its arguments I don't actually perform the full division z / w = (z * w*) / (w * w*) instead I just multiply each point by the complex conjugate of the previous point.

Edit: Saved 4 bytes thanks to @edc65.


05AB1E, 39 bytes
εNUε'aåi„aaë¯.øX<X>‚è˜y2£lSδåPài„Aaë„A_

Port of my Java answer.
Try it online or verify all test cases.
Explanation:

ε                     # Map over the rows of the (implicit) input-list:
 NU                   #  Store the outer-map index in variable `X`
   ε                  #  Map over the strings `y` of the current row:
    'aåi             '#   If the current string contains an "a":
        „aa           #    Push string "aa"
       ë              #   Else (it contains an "A" instead):
        ¯.ø           #    Surround the (implicit) input-list with two empty lists
                      #    (05AB1E has automatic wrap-around when indexing lists,
                      #     so this is to prevent that)
           X<X>‚      #    Push `X-1` and `X+1` and pair them together
                è     #    Index both into the list to get (potential) parent and child rows
                 ˜    #    Flatten it to a single list
        y             #    Push the current string we're mapping again
         2£           #    Only leave the first 2 characters (its id and the letter "A")
           l          #    Lowercase the "A" to "a"
            S         #    And convert it to a list of characters: [id, "A"]
             δå       #    Check in each string whether it contains the id and "A"
               P      #    Check for each whether it contained BOTH the id AND "A"
                ài    #    If a child/parent is found for which this is truthy:
                  „Aa #     Push string "Aa"
                 ë    #    Else:
                  „A_ #     Push string "A_"
                      # (after which the mapped result is output implicitly)


JavaScript, 40
(c,p)=>c.search(p.replace(/./g,"[^$&]"))

Using replace, this maps the plaintext input into a regular expression of form /[^H][^E][^L][^L][^O]/ (e.g., for plaintext input HELLO) and then uses search to test for the first index of the ciphertext substring that matches that regex. This regex means "a pattern where the first character is not H, the second character is not E, etc."
$& is a special sequence for replace output that substitutes in the value matched by the first replace argument (in this case, each single character matched by /./).


C, (14 + 15) = 29 byte source, 17,179,875,837 (16 GB) byte executable
Thanks to @viraptor for 6 bytes off.
Thanks to @hvd for 2 bytes off and executable size x4.
This defines the main function as a large array and initialises its first element.  This causes GCC to store the entire array in the resulting executable.
Because this array is bigger than 2GB, we need to provide the -mcmodel=medium flag to GCC.  The extra 15 bytes are included in the score, as per the rules.

main[-1u]={1};

Don't expect this code to do anything nice when run.
Compile with:
gcc -mcmodel=medium cbomb.c -o cbomb

It took me a while to get round to testing @hvd's suggestion - and to find a machine with enough juice to handle it. Eventually I found a old non-production RedHat 5.6 VM with 10GB RAM, 12GB swap, and /tmp set to a large local partition.  GCC version is 4.1.2.  Total compile time about 27 minutes.

Due to the CPU and RAM load, I recommend against doing this compile on any remotely production-related machine.


Python, 40 bytes

f=lambda n,k:k<2or~-n*n*f(n-1,k-1)/~-k/k

Try it online!

Uses the recurrence \$a_{n,1} = 1\$, \$a_{n,k} = \frac{n(n-1)}{k(k-1)}a_{n-1,k-1}\$.


Conjugate in the Spanish imperfect / Conjugue en el imperfecto de indicativo

Retina, 100 82 bytes

\B[^a]r$
I
r$
b
^vI$
veI
^sI$
er
$
a
$
 $_s $_ $_mos $_is $_n
T`l`L`.(?=[^I]amos )

Try it online. Unfortunately, due to the use of $_ it's not possible to modify the code to run all tests at once, so you'll have to copy in the individual verbs. I'm working on a new feature that will make this possible though.

Explanation

\B[^a]r$
I

We start by turning all endings which aren't ar into I, provided the input isn't the irregular verb ir. That takes care of the -er, -ir, -ír conjugations, messes up the irregular verbs ser and ver (but shortens them in the process), and leaves only ir and -ar with a trailing r.

r$
b

If the word still ends in r, we replace that with a b. We've now covered all standard conjugations as well as the irregular verb ir.

^vI$
veI

This fixes the irregular verb ver which has been turned into vI in the first stage.

^sI$
er

This fixes the irregular verb ser which has been turned into sI in the first stage. Now we've modified all possible stems correctly. All that's left to do is append all the possible endings, and then fix the accent for the first person plural in some cases.

$
a

First we append an a to the stem, because that's always part of all endings.

$
 $_s $_ $_mos $_is $_n

This makes use of the rarely seen $_ which inserts the entire string into the substitution (regardless of what was matched). This is actually very useful when duplicating strings, as are $` and $', which are also quite underappreciated.

Before this stage, we've got the first person singular in the string. We now append the other conjugations, by matching the end of the string with $ and building the other forms by appending the appropriate suffixes to the first person singular.

T`l`L`.(?=[^I]amos )

Finally, we fix the accent for the first person plural if applicable. This only needs to be done for a vowel, two characters in front of the -amos unless the character in between is I. So we match such a character and then use a transliteration stage to convert lower to upper case. This makes use of the new character classes l and L which I only added yesterday. They expand to a-z and A-Z respectively, so that new feature saves 4 bytes here.


Python 2, 47 bytes

lambda l:l.sort(key=len)or l[1::2][::-1]+l[::2]

Try it online!


Jelly, 20 bytes

2*ḃ€2‘ÄṪ⁼¥Ƈ⁸ṗfƝẸ$€ċ0

Try it online!


05AB1E, 12 10 bytes
µNNÑ€ÙSDÙQ

-2 bytes thanks to @Emigna.
1-indexed
Try it online or verify most test cases (last two test cases are omitted, since they time out).
Explanation:

µ           # Loop while the counter_variable is not equal to the (implicit) input yet:
 N          #  Push the 0-based index of the loop to the stack
  NÑ        #  Get the divisors of the 0-based index as well
            #   i.e. N=9566 → [1,2,4783,9566]
            #   i.e. N=9567 → [1,3,9,1063,3189,9567]
    €Ù      #  Uniquify the digits of each divisor
            #   → ["1","2","4783","956"]
            #   → ["1","3","9","1063","3189","9567"]
      S     #  Convert it to a flattened list of digits
            #   → ["1","2","4","7","8","3","9","5","6"]
            #   → ["1","3","9","1","0","6","3","3","1","8","9","9","5","6","7"]
       D    #  Duplicate this list
        Ù   #  Unique the digits
            #   → ["1","2","4","7","8","3","9","5","6"]
            #   → ["1","3","9","0","6","8","5","7"]
         Q  #  And check if it is still equal to the duplicated list
            #   → 1 (truthy)
            #   → 0 (falsey)
            #  And if it's truthy: implicitly increase the counter_variable by 1
            # (After the loop: implicitly output the top of the stack,
            #  which is the pushed index)


Ruby - 50 48 chars, plus -p command line parameter.

gsub(/(?<=\w)\w+(?=\w)/){[*$&.chars].shuffle*''}

Thanks @primo for -2 char.

Test

➜  codegolf git:(master) ruby -p 9261-cambridge-transposition.rb < 9261.in
Acdrcinog to a racreseher at Cagribmde Ursvetniiy, it dsoen't mttaer in waht odrer the leertts in a word are, the olny ionarpmtt tnhig is that the fsirt and last letetr be at the rghit pcale. The rset can be a taotl mses and you can slitl raed it wthiuot perlbom. Tihs is buaecse the hmuan mind does not raed ervey lteetr by ietlsf but the word as a wlhoe.


Dyalog APL, 27 characters
⊃⌽∨.∧⍨⍣≡1≥+/¨|∘.-⍨,(~×⍳∘⍴)⎕
⎕ evaluated input.  APL distinguishes between a matrix and a vector of vectors.  This program assumes that the input is a matrix.
(~×⍳∘⍴)A is a fork equivalent to (~A) × ⍳⍴A.  It's needed to avoid mentioning ⎕ twice or introducing a variable.
⍴A is the shape of A.  For a 4-by-7 matrix the shape is 4 7.
⍳ is the index generator.  ⍳4 is 1 2 3 4.  ⍳4 7 is the vectors (1 1)(1 2)...(4 7) arranged in a 4-by-7 matrix.
~A flips the bits of A.
× by multiplying ⍳⍴A by the flipped bits, we preserve the coordinates of all free cells and turn all walls into 0 0.
, ravels the matrix of coordinate pairs, i.e. linearizes it into a vector.  In this case the vector will consist of pairs.
∘.-⍨A or A∘.-A subtracts elements of A pairwise.  Note that here the elements of A are themselves pairs.
| absolute value
+/¨ sum each pair of absolute values.  This gives us the grid distances between every pair of cells in the maze, save for walls.
1≥ we are only intrested in neighbours at a distance no more than 1, this also excludes walls.  Now we have a graph's adjacency matrix.
∨.∧⍨⍣≡ Floyd--Warshall's transitive closure algorithm
(f⍣n)A (not used here) where n is an integer is the power operator.  It applies f to A n times: f f ... f A.
(f⍣g)A where g is a function, is the fixed point operator, a.k.a. "power limit".  It keeps on computing the series A, f A, f f A, ... until ((f⍣i)A) g ((f⍣(i+1))A) returns true for some i.  In this case we use match (≡) as g.
∨.∧⍨A or A∨.∧A is a step in Floyd's algorithm.  f.g is a generalisation of matrix multiplication (+.×), here we use conjunction (∧) and disjunction (∨) in place of + and ×.
⊃⌽  After ⍣≡ has applied the step enough times and reached a stable state, we must look up the top-right corner of the matrix to get the result, so we flip it (⌽) and take the first, top-left item (⊃).
Visualization of ⍣≡'s steps


176 bytes (plain TeX without e-TeX or pdfTeX)

\let\n\newcount\n~\n\j\n\k2~3\loop\ifnum~<1224{\let\x.\j3\loop\ifnum\j<~\k~\divide\k\j\multiply\k\j\ifnum\k=~\let\x!\fi\advance\j2\repeat\ifx\x., \the~\fi}\advance~2\repeat\end

Algorithm

The algorithm is quite simple. It outputs the first prime number 2 and goes from the next prime number 3 to the 200th prime number 1223.
Each number i is tested, if the odd number is divisible by 3 up to i-1 without even numbers (thanks Howard for the removal of the even numbers).

There is much room for optimizations of the run-time, e.g.:

The inner loop can be aborted, when the first divisor is found, see the comments.
The divisions only need to be done up to sqrt(i).

The result is a paragraph with comma separated numbers:

Ungolfed version

% assign some count registers with short names
\newcount\i
\newcount\j
\newcount\k
% Output first prime number 2
2%
% Start loop with second prime number 3
\i=3 %
\loop
\ifnum\i<1224 % 1223 is 200th prime number
  {% group with curly braces because of the nested \loop
    \let\x=. % \x is changed, if \i is not prime
    % Test for all 2 <= j < i: trunc(i/j)*j == i
    % If true, then j is divisor of i and i is not prime
    \j=3
    \loop
    \ifnum\j<\i
      \k=\i
      \divide\k by \j
      \multiply\k by \j
      \ifnum\k=\i
        \let\x=! % \i is not prime
        % Optimization to break the loop:
        %   \let\iterate\empty
        % Then also \x can be removed: If the loop is not aborted,
        % then \iterate will have the meaning \relax and the
        % test "\ifx\x." can be replaced by "\ifx\iterate\relax".
      \fi
      \advance\j by 2
    \repeat
    \ifx\x.
      , \the\i % output prime number
    \fi
  }%
  \advance\i by 2 % test next odd number
\repeat
\end % end of job

Variant: Output in protocol file, 195 bytes

\let\n\newcount\n~\n\j\n\k~2\def\w{\wlog{\the~}}\w~3\loop\ifnum~<1224{\let\x.\j3\loop\ifnum\j<~\k~\divide\k\j\multiply\k\j\ifnum\k=~\let\x!\fi\advance\j2\repeat\ifx\x.\w\fi}\advance~2\repeat\end

The result is written to the .log file:

This is TeX, Version 3.1415926 (TeX Live 2013) (format=tex 2013.5.21)  11 MAR 2014 18:33
**test
(./test.tex
~=\count26
\j=\count27
\k=\count28
2
3
5
7
11
13
17
19
23
29
31
37
41
43
47
53
59
61
67
71
73
79
83
89
97
101
103
107
109
113
127
131
137
139
149
151
157
163
167
173
179
181
191
193
197
199
211
223
227
229
233
239
241
251
257
263
269
271
277
281
283
293
307
311
313
317
331
337
347
349
353
359
367
373
379
383
389
397
401
409
419
421
431
433
439
443
449
457
461
463
467
479
487
491
499
503
509
521
523
541
547
557
563
569
571
577
587
593
599
601
607
613
617
619
631
641
643
647
653
659
661
673
677
683
691
701
709
719
727
733
739
743
751
757
761
769
773
787
797
809
811
821
823
827
829
839
853
857
859
863
877
881
883
887
907
911
919
929
937
941
947
953
967
971
977
983
991
997
1009
1013
1019
1021
1031
1033
1039
1049
1051
1061
1063
1069
1087
1091
1093
1097
1103
1109
1117
1123
1129
1151
1153
1163
1171
1181
1187
1193
1201
1213
1217
1223
 )
No pages of output.

Variant: Counting prime numbers, 197 bytes

The following variant also counts the prime numbers to get rid of the "hard-coded" 200th prime number. (I have added this variant at the end, because the question would also allow to hard-code all prime numbers.)

\let\a\advance\let\n\newcount\n\p\n~\n\j\n\k2\p1~3\loop\ifnum\p<200{\let\x.\j3\loop\ifnum\j<~\k~\divide\k\j\multiply\k\j\ifnum\k=~\let\x!\fi\a\j2\repeat\ifx\x., \the~\global\a\p1\fi}\a~2\repeat\end


Ruby

def method_missing(meth,*args)
  puts 'Banana'
  send(meth.next)
end

def also
  puts "Orange you glad I didn't say banana?"
end

ahem

Demo

Clears its throat, prints "Banana" 3070 times, and also puts "Orange you glad I didn't say banana?".

This uses Ruby's ridiculous just-in-time method definition functionality to define every method that lies alphabetically between the words 'ahem' and 'also' ("ahem", "ahen", "aheo", "ahep", "aheq", "aher", "ahes", "ahet", "aheu", "ahev"...) to first print Banana and then call the next in the list.


R, 85 84 76 74 bytes, 0.250s on TIO

f=function(n,k,m=nchar(gsub("[^5]","",n+1))-k)`if`(m<0,f(n+.1^m/50,k),n+1)

Try it online!
-1 byte thanks to Robert S.
-8 bytes thanks to Giuseppe.
The nchar(gsub(...)) part counts the number of 5s.
A simple recursive solution would be to increment by 1 until the answer is found, but this would not meet the time restriction. To meet the time restriction, this function makes use of the fact that if there are p missing 5s, we can increment by 2*10^(p-2) (represented as the golfier .1^m/50, with m=-p).
Note that when p=1, the increment becomes 0.2. This is OK, since after 5 steps we come back to an integer, and none of the decimal numbers encountered in the mean time have an extra 5. If instead we were to increment by 5*10^(p-2) or by 1*10^(p-2), then we would find f(24, 1)=24.5 instead of 25 for example.


Python 2, 646 bytes

G=range;w=raw_input;z=L,m,h=[0]*3
s=w();t=len(s);s+='!%s#'%w();u=len(s);I=z*u
def f(s,n):
 def r(o):
	b=[[]for _ in s];c=[]
	for x in B[:N]:b[s[x+o]]+=x,
	map(c.extend,b);B[:N]=c
 M=N=n--~n/3;t=n%3%2;B=G(n+t);del B[::3];r(2);u=m=p=r(1)>r(0);N-=n/3
 for x in B*1:v=s[x:x+3];m+=u<v;u=v;B[x/3+x%3/2*N]=m
 A=1/M*z or f(B+z,M)+z;B=[x*3for x in A if x<N];J=I[r(0):n];C=G(n)
 for k in C:b=A[t]/N;a=i,j=A[t]%N*3-~b,B[p];q=p<N<(s[i:i-~b],J[i/3+b+N-b*N])>(s[j+t/M:j-~b],J[j/3+b*N]);C[k]=x=a[q];I[x]=k;p+=q;t+=1-q
 return C
S=f(map(ord,s)+z*40,u)
for i in G(u):
 h-=h>0;j=S[I[i]-1]
 while s[i+h]==s[j+h]:h+=1
 if(i<t)==(t<j)<=h>m:m=h;L=min(i,j)
print-~L,L+m

Try it online
This uses the skew algorithm described in "Simple Linear Work Suffix Array Construction" by Kärkkäinen and Sanders. The C++ implementation included in that paper already feels a little "golfy", but there is still plenty of room for making it shorter. For example, we can recurse until arriving at an array of length one, instead of short circuiting as in the paper, without violating the O(n) requirement.
For the LCP part, I followed "Linear-Time Longest-Common-Prefix Computation in Suffix Arrays and Its Applications" by Kasai et al.
The program outputs 1 0 if the longest common substring is empty.
Here is some development code that includes an earlier version of the program that follows the C++ implementation a bit more closely, some slower approaches for comparison, and a simple test case generator:
from random import *

def brute(a,b):
    L=R=m=0

    for i in range(len(a)):
        for j in range(i+m+1,len(a)+1):
            if a[i:j] in b:
                m=j-i
                L,R=i,j

    return L+1,R

def suffix_array_slow(s):
    S=[]
    for i in range(len(s)):
        S+=[(s[i:],i)]
    S.sort()
    return [x[1] for x in S]

def slow1(a,b):
    # slow suffix array, slow lcp

    s=a+'!'+b
    S=suffix_array_slow(s)

    L=R=m=0

    for i in range(1,len(S)):
        x=S[i-1]
        y=S[i]
        p=s[x:]+'#'
        q=s[y:]+'$'
        h=0
        while p[h]==q[h]:
            h+=1
        if h>m and len(a)==sorted([x,y,len(a)])[1]:
            m=h
            L=min(x,y)
            R=L+h

    return L+1,R

def verify(a,b,L,R):
    if L<1 or R>len(a) or a[L-1:R] not in b:
        return 0
    LL,RR=brute(a,b)
    return R-L==RR-LL

def rand_string():
    if randint(0,1):
        n=randint(0,8)
    else:
        n=randint(0,24)
    a='zyxwvutsrq'[:randint(1,10)]
    s=''
    for _ in range(n):
        s+=choice(a)
    return s

def stress_test(f):
    numtrials=2000
    for trial in range(numtrials):
        a=rand_string()
        b=rand_string()
        L,R=f(a,b)
        if not verify(a,b,L,R):
            LL,RR=brute(a,b)
            print 'failed on',(a,b)
            print 'expected:',LL,RR
            print 'actual:',L,R
            return
    print 'ok'

def slow2(a,b):
    # slow suffix array, linear lcp

    s=a+'!'+b+'#'
    S=suffix_array_slow(s)

    I=S*1
    for i in range(len(S)):
        I[S[i]]=i

    L=R=m=h=0

    for i in range(len(S)):
        if I[i]:
            j=S[I[i]-1]
            while s[i+h]==s[j+h]:
                h+=1
            if h>m and len(a)==sorted([i,j,len(a)])[1]:
                m=h
                L=min(i,j)
                R=L+h
            h-=h>0

    return L+1,R

def suffix_array(s,K):
    # skew algorithm

    n=len(s)
    s+=[0]*3
    n0=(n+2)/3
    n1=(n+1)/3
    n2=n/3
    n02=n0+n2
    adj=n0-n1

    def radix_pass(a,o,n=n02):
        c=[0]*(K+3)
        for x in a[:n]:
            c[s[x+o]+1]+=1
        for i in range(K+3):
            c[i]+=c[i-1]
        for x in a[:n]:
            j=s[x+o]
            a[c[j]]=x
            c[j]+=1

    A=[x for x in range(n+adj) if x%3]+[0]*3

    radix_pass(A,2)
    radix_pass(A,1)
    radix_pass(A,0)

    B=[0]*n02
    t=m=0

    for x in A[:n02]:
        u=s[x:x+3]
        m+=t<u
        t=u
        B[x/3+x%3/2*n0]=m

    A[:n02]=1/n02*[0]or suffix_array(B,m)
    I=A*1
    for i in range(n02):
        I[A[i]]=i+1

    B=[3*x for x in A if x<n0]
    radix_pass(B,0,n0)

    R=[]

    p=0
    t=adj
    while t<n02:
        x=A[t]
        b=x>=n0
        i=(x-b*n0)*3-~b
        j=B[p]
        if p==n0 or ((s[i:i+2],I[A[t]-n0+1])<(s[j:j+2],I[j/3+n0]) if b else (s[i],I[A[t]+n0])<(s[j],I[j/3])):R+=i,;t+=1
        else:R+=j,;p+=1

    return R+B[p:n0]

def solve(a,b):
    # linear

    s=a+'!'+b+'#'
    S=suffix_array(map(ord,s),128)

    I=S*1
    for i in range(len(S)):
        I[S[i]]=i

    L=R=m=h=0

    for i in range(len(S)):
        if I[i]:
            j=S[I[i]-1]
            while s[i+h]==s[j+h]:
                h+=1
            if h>m and len(a)==sorted([i,j,len(a)])[1]:
                m=h
                L=min(i,j)
                R=L+h
            h-=h>0

    return L+1,R

stress_test(solve)


Determine if a number is prime without using arithmetic

PHP, 117 characters

This one is based on regular expressions. If a string containing $n characters can be split into chunks of equal length, then $n must be composite.

(Assumes $n is a positive integer.)

function p($n){$u=true;$s=str_repeat('x',$n);return($s!='x'&&!preg_match('/^(xx{'.$u.',})\\'.$u.'{'.$u.',}$/U',$s));}

Output:

for ($i=1; $i<=100; $i++) if (p($i)) echo "$i ";

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97


Maximal saturated domino covering of a rectangle

Sagemath, 60 bytes
lambda m,n:m*n-len(graphs.GridGraph([m,n]).dominating_set())

Try it online!

From Saturated Domino Coverings by Buchanan et al:

Corollary 6.3: If \$B\$ is a rectangular \$m \times n\$ board, then \$d(B) = |B| - \gamma(G_{m,n})\$.

Where \$\gamma(\ldots)\$ is the domination number and \$G_{m,n}\$ is a grid graph. We also clearly have that if \$B\$ represents an \$m\times n\$ board then \$|B| = mn\$.


Haskell, 350 346 342 bytes

main=interact f;f s|s==l++r=l|s/=l,s/=r=[]|1<3=l++r;r=reverse l;l=q++shows q['-'];q="main=interact f;f s|s==l++r=l|s/=l,s/=r=[]|1<3=l++r;r=reverse l;l=q++shows q['-'];q="--"=q;]'-'[q swohs++q=l;l esrever=r;r++l=3<1|][=r=/s,l=/s|l=r++l==s|s f;f tcaretni=niam"=q;]'-'[q swohs++q=l;l esrever=r;r++l=3<1|][=r=/s,l=/s|l=r++l==s|s f;f tcaretni=niam

Prints its left half with itself as input: https://tio.run/##7ZAxCoUwEESvEmwsoohYxjlJSBEkYvhrJNnwbXJ3f8gd7H4zsMPsY5jD8scRPc9pfYAP2SW7ZbGrXXBhgKRMoMITaKiSoE2Z16X5KiG5r0vsBClClJKP62YRdT/2RkV0r0DHsUNUpp46Cr6vg6WMqGHhuL2iQqQkLOtcjK74iQeqUgjNRy3RyuTNJpeDR/D2fAX63/WdXX8
Prints itself with its left half as input: Try it online!
Prints itself with its right half as input: Try it online!
Prints nothing with anything else as input: Try it online!

Edit: -8 bytes thanks to Ørjan Johansen! Also changed to a version which does not need (<>).


CJam, 44 37 36 bytes

Thanks to Sp3000 for reminding me that I'm overcomplicating things and saving 7 bytes.

rci7%"3>0<2<1>"2/=6,slS%{W$~+}*fe=p;

Test it here.

Explanation

Some observations:

We always want to count the entire first card.
All splays will result in either a prefix or a suffix of the icons removed. ! removes all of them (which is either a prefix or a suffix of four characters), < removes the first three characters, > removes the last two characters, ^ removes the first character.

So all we need is a short way to map the splay mode to the correct truncation:

rci   e# Read the splay mode and convert to its character code.
7%    e# Take modulo 7. This maps "<!>^" to [4 5 6 3], respectively. Modulo 4 those are
      e# are all distinct (namely [0 1 2 3], respectively).
"3>0<2<1>"
      e# Push this string.
2/    e# Split it into chunks of 2, ["3>" "0<" "2<" "1>"]. Each chunk is CJam code which
      e# performs one of the truncations.
=     e# Select the correct snippet. This works, because array indexing is cyclic in CJam.
6,s   e# Push the string "012345".
lS%   e# Read the remainder of the input and split into space-separated tokens.
{     e# Now we're abusing the fold operation to apply our snippet to every card except
      e# the first, while also combining them all back into a single string.
  W%  e#   Copy the bottom of the stack (the truncation snippet).
  ~   e#   Evaluate it.
  +   e#   Append it the string we're building.
}*
fe=   e# For each character in "012345", count the occurrences in our new string.
p     e# Pretty-print the array.
;     e# Discard the truncation snippet which was still at the bottom of the stack.

We can notice that the truncation snippets actually have a lot of structure. Each splay mode maps to one number in [0 1 2 3] (specifically, in order "!^><"), and two of them have > and two have <. I was hoping to find two hashes which magically produce these parts separately, as that would save a bunch of bytes, but so far I wasn't able to find anything. I can map "!^><" to numbers of alternating parity with 31% (to select the correct character from "<>"), but I haven't found anything which neatly maps them [0 1 2 3] in that order. (Except the naive solution of "!^><"# which unfortunately doesn't save any bytes.)

Also note that it's actually a bit more flexible. ! can also be implemented as n> for any n > 3 (discarding everything as a prefix). Unfortunately, I haven't been able to find any simple function for such a map either.


PHP 666 611 593 588 580 Characters
Edit: Used even smaller url than previously from tinyurl.
Edit: Following comment on other answer I used int rather than boolean. Also needed to correct an error that became apparent but fixed now.
Here is my code
<?
$a=34727;$b=new DOMDocument();$b->loadHTMLFile("http://turl.no/t2u");$c=$b->saveHTML();$d=$e=1;$f='data-answerid="';$g=strpos($c,$f);$h=substr($c,0,$g);$c=substr($c,($g+15));while($d==1){$g=strpos($c,'"');$i=substr($c,0,$g);if($i==$a){$j=$h;$k=$e;}$g=strpos($c,'vote-count-post ">');$c=substr($c,($g+18));$g=strpos($c,'<');$l=substr($c,0,$g);$g=strpos($c,'data-answerid="');if($g){++$e;++$e;$h=substr($c,0,$g);$c=substr($c,($g+15));}else{$d=2;}}if($k==1){echo 'Top!';}else{$g=strpos($j,'>');$m=strpos($j,'
');$n=$m-$g-7;$o=substr($j,($g+7),$n);echo nl2br($o);}

I am sure this can be improved using DOMXPath and nodes. However am quite pleased with it. I could not decide what to do in the case of mine is the only answer but with -ve points so ignored. However another answer was posted so not a problem any more.
I also used tinyurl to shorten the url, saving lots of characters.
I hope you like it,
Paul.
PS This will not run in codepad so can't show a fiddle.
Edit: saved 5 more with the php tags being altered
You can see it working here on a domain I do not currently use (so am not just trying a sneaky link). This is not a permanent link though but is currently available.


JavaScript, 177 187 198 characters
function(d){c="";for(a=e=b=0;a<4*d.length/3;f=b>>2*(++a&3)&63,c+=String.fromCharCode(f+71-(f<26?6:f<52?0:f<62?75:f^63?90:87)))a&3^3&&(b=b<<8^d[e++]);for(;a++&3;)c+="=";return c}

For adding linebreaks, \r\n, after each 76th character, add 23 characters to the code:
function(d){c="";for(a=e=b=0;a<4*d.length/3;f=b>>2*(++a&3)&63,c+=String.fromCharCode(f+71-(f<26?6:f<52?0:f<62?75:f^63?90:87))+(75==(a-1)%76?"\r\n":""))a&3^3&&(b=b<<8^d[e++]);for(;a++&3;)c+="=";return c}

Demo code:

var encode = function(d,a,e,b,c,f){c="";for(a=e=b=0;a<4*d.length/3;f=b>>2*(++a&3)&63,c+=String.fromCharCode(f+71-(f<26?6:f<52?0:f<62?75:f^63?90:87))+(75==(a-1)%76?"\r\n":""))a&3^3&&(b=b<<8^d[e++]);for(;a++&3;)c+="=";return c};

//OP test case
console.log(encode([99, 97, 102, 195, 169])); // outputs "Y2Fmw6k=".

//Quote from Hobbes' Leviathan:
console.log(
 encode(
  ("Man is distinguished, not only by his reason, but by this singular passion from " +
   "other animals, which is a lust of the mind, that by a perseverance of delight " +
   "in the continued and indefatigable generation of knowledge, exceeds the short " +
   "vehemence of any carnal pleasure.")
  .split('').map(function(i){return i.charCodeAt(0)})
 )
);


CJam, 47 41 37 bytes

li4,1${__m*{_~<\:+*}%$2/z:^$2=+}*1><`

Try it online.

Example run

$ cjam <(echo 'li4,1${__m*{_~<\:+*}%$2/z:^$2=+}*1><`') <<< 26
[1 2 3 4 6 8 11 13 16 18 26 28 36 38 47 48 53 57 62 69 72 77 82 87 97 99]

How it works

This basic idea is the following:

Start with the array A := [ 0 U₁ U₂ ... Uₖ ].
Compute S, the array of all sums x + y such that x,y ∊ A and x < y.
Discard all non-unique sums from S. Since every Ulam number greater than 2 is both the sum of two smaller ones and the sum of zero and itself, this discards the Ulam numbers U₃, U₄, ... Uₖ.
The remaining array is [ U₁ U₂ Uₖ₊₁ ... ], so the next Ulam number is the third smallest element. Append it to A and go back to step 1.

li                                    " Read one integer (I) from STDIN.                  ";
  4,                                  " Push the array A = [ 0 1 2 3 ].                   ";
    1${                        }*     " Do the following I times:                         ";
       __m*                           " Push the Cartesian product A × A.                 ";
           {       }%                 " For each pair (x,y) in A × A:                     ";
            _~<\:+*                   " Compute (x + y) * (x < y).                        ";
                     $2               " Sort the resulting array.                         ";
                       /              " Split it into chunks of length 2.                 ";
                        z             " Transpose the resulting two-dimensional array.    ";
                         :^           " Compute the symmetric difference of its rows.     ";
                           $          " Sort the resulting array.                         ";
                            2=        " Extract its third element.                        ";
                              +       " Push it on the array A.                           ";
                                 1>   " Discard the first element of A (0).               ";
                                   <  " Discard all but the first I elements of A.        ";
                                    ` " Push a string representation of A.                ";


Haskell, 201 194 bytes

l=length
g[]n u=map(\_->"")n
g(b:c)[]u=(u++c):g c[]u
g(b:c)n@(o:p)u|b==o=g c p(u++[o])|1<2=((u++o:c):g c p(u++[o]))!((u++c):g c n u)
a!b|l a<l b=a|1<2=b
p[a,n]=g a n""
f=interact$unlines.p.lines

Longer than expected. Maybe I can golf it down a little bit ...

Usage example:

*Main> f                     -- call via f
Questions                    -- User input
Answers                      -- no newline after second line!
uestions                     -- Output starts here
Aestions
Anstions
Ansions
Answons
Answens
Answers

It's a brute force that decides between changing and deleting if the initial characters differ.


Vim with Ultisnips in C (gcc), 30 keystrokes

imaTabTabputs("Hello, World!");Esc:x

Explanation

To use the above you'll need the mentioned Plugin installed and g:UltiSnipsExpandTrigger and g:UltiSnipsJumpForwardTrigger bound to Tab, further you'll need this snippet in your g:UltiSnipsDir. This also makes the assumption that you opened a file which sets filetype=c:

ima: Change to Insert mode and enter ma
TabTab: Select and expand the main <snip>
puts("Hello, World!");: Insert the remaining characters
Esc: Change to Normal mode
:x: Write the file and exit

The resulting file looks like this:

int main(int argc, char *argv[])
{
  puts("Hello, World!");
  return 0;
}

Note: I couldn't just now find a complete vimrc but here's a StackOverflow post that mentions the relevant parts.


Python 3.4 - min: 21, max: 29, total: 25146, time: 20min
min: 30, max: 235, total: 41636, time: 4min
Update:

Use binary search to find space. The idea is borrowed from Orby's answer. One spot I optimized is that if you found 2 spaces in a range when searching for the first space, you can narrow the search range of the second space.
Save wrong guesses along with their result. Compare with them in following guesses. This can save a lot.
Reduce letter enumerate count to 12, thanks to update #2.

This mehod don't use randomness so the score will not change.
First it use guesses like the following to find the first and second spaces in the answer.
. ......................
.. .....................
... ....................
.... ...................
# more follows, until two spaces found.

Then, it count occurrence of each letter by guessing aaaaa..., bbbbb.......
After these it will cost about 40 steps. In fact, we don't need to try all the letters and we can try them in arbitary order. In most cases, trying about 20 letters is enough. Here I choose 21.
Now it know the length of the first word and the second word so it can filter out a list of candidates for these two words. Normally it will have about 100 candidates left for each.
Then it just enumerate the first and the second word. Once the first two words is enumerated, we can infer all valid third word since we know it's character counts.
To optimize for speed, I use the concurrent.futures to add multiprocessing to the program. So you need Python 3 to run it and I tested it with Python 3.4 on my Linux box. Also, you need to install numpy.
import sys
import functools
from collections import defaultdict
from concurrent.futures import ProcessPoolExecutor
import numpy as np

def debug(*args, **kwargs):
    return
    print(*args, **kwargs)

def compare(answer, guess):
    b = sum(1 for x, y in zip(guess, answer) if x == y)
    a = 0
    c = defaultdict(int)
    for x in answer:
        c[x] += 1

    for x in guess:
        if c.get(x, 0) > 0:
            a += 1
            c[x] -= 1
    return a, b

def checker_task(guesser):
    @functools.wraps(guesser)
    def task(case):
        i, answer = case
        return (i, answer, run_checker(answer, guesser))
    return task

def run_checker(answer, guesser):
    guess_count = 0
    guesser = guesser()
    guess = next(guesser)
    while True:
        guess_count += 1
        if answer == guess:
            break
        try:
            guess = guesser.send(compare(answer, guess))
        except StopIteration:
            raise Exception('Invalid guesser')
    try:
        guesser.send((-1, -1))
    except StopIteration:
        pass
    return guess_count

# Preprocessing
words = list(map(str.rstrip, open('dict.txt')))
words_with_len = defaultdict(list)
for word in words:
    words_with_len[len(word)].append(word)

M = 12
chars = 'eiasrntolcdupmghbyfvkwzxjq'[:M]
char_ord = {c: i for i, c in enumerate(chars)}

def get_fingerprint(word):
    counts = [0] * (M + 1)
    for c in word:
        counts[char_ord.get(c, M)] += 1
    return tuple(counts[:-1])

word_counts = {word: np.array(get_fingerprint(word)) for word in words}

# End of preprocessing

# @profile
@checker_task
def guesser1():
    # Find spaces using binary search
    max_word_len = max(map(len, words))
    max_len = max_word_len * 3 + 2
    # debug('max_len', max_len)
    s_l = [1, 3]
    s_r = [max_len - 3, max_len - 1]

    for i in range(2):
        while s_l[i] + 1 < s_r[i]:
            # debug(list(zip(s_l, s_r)))
            mid = (s_l[i] + s_r[i]) // 2
            guess = '.' * s_l[i] + ' ' * (mid - s_l[i])
            a, b = yield guess
            if b > 1 and i == 0:
                s_l[1] = max(s_l[1], s_l[0] + 2)
                s_r[1] = min(s_r[1], mid)
                s_r[0] = mid - 2
            elif b > 0:
                s_r[i] = mid
            else:
                s_l[i] = mid
        if i == 0:
            s_l[1] = max(s_l[1], s_l[0] + 2)

    spaces = s_l
    del s_l, s_r

    word_lens = [spaces[0], spaces[1] - spaces[0] - 1, None]
    debug('word_lens', word_lens)
    debug('spaces', spaces)
    char_counts = [0] * M
    for i, c in enumerate(chars):
        guess = c * max_len
        _, char_counts[i] = yield guess

    char_counts = np.array(char_counts)

    candidates = [words_with_len[word_lens[0]], words_with_len[word_lens[1]], words]
    for i, ws in enumerate(candidates):
        candidates[i] = [word for word in ws if np.alltrue(char_counts >= word_counts[word])]
    P = defaultdict(list)
    for word in candidates[2]:
        P[get_fingerprint(word)].append(word)
    debug('candidates', list(map(len, candidates)))

    wrong_guesses = []
    # @profile
    def search(i, counts, current):
        if i == 2:
            rests = tuple(char_counts - counts)
            for word in P[rests]:
                current[i] = word
                guess_new = ' '.join(current)
                for guess, t in wrong_guesses:
                    if t != compare(guess_new, guess):
                        break
                else:
                    yield current
            return
        for word in candidates[i]:
            counts += word_counts[word]
            if np.alltrue(char_counts >= counts):
                current[i] = word
                yield from search(i + 1, counts, current)
            counts -= word_counts[word]

    try_count = 0
    for result in search(0, np.array([0] * M), [None] * 3):
        guess = ' '.join(result)
        a, b = yield guess
        try_count += 1
        if a == -1:
            break
        wrong_guesses.append((guess, (a, b)))
    debug('try_count', try_count)

def test(test_file, checker_task):
    cases = list(enumerate(map(str.rstrip, open(test_file))))
    scores = [None] * len(cases)
    with ProcessPoolExecutor() as executor:
        for i, answer, score in executor.map(checker_task, cases):
            print('-' * 80)
            print('case', i)
            scores[i] = score
            print('{}: {}'.format(answer, score))
            sys.stdout.flush()
    print(scores)
    print('sum:{} max:{} min:{}'.format(sum(scores), max(scores), min(scores)))

if __name__ == '__main__':
    test(sys.argv[1], guesser1)


Bash + coreutils, 46

tr b-zB-Z ${a=typetjkitkpstokrtyputjkyb}${a^^}

Try it online!


J, 19 bytes
Takes input as six four. As the input range is limited, I just deleted characters while the output stayed the same. :-) Reads like "if there is no e in the input, or if there are no t and o in the input, … then we can spell another number."
e.e`to`for`si-.~&><

Try it online!
e.e`to`for`si-.~&><
                &>< boxing stuff
  e`to`for`si       for each e, to, for, si:
             -.~      delete from the input any character from the list
e.                  is the input still in the results, i.e. is there any
                      case were no character got deleted?


Python 2, 84 79 76 bytes

lambda*l:cmp(*map(lambda v:map(int,v.split('.')+[0]*len(`l`))[:len(`l`)],l))

Try it online!

Outputs -1,0,1 for <,=,>


Java

public class GamerDie {
    private final java.util.Random rnd;
    private final int sides;

    public GamerDie(int sides) {
        this.sides = sides;
        this.rnd = new java.util.Random();
    }

    public int throw() {
        return rnd.nextInt(sides) + 1;
    }
}

It's so simple that it's obviously not hiding anything: but java.util.Random is a straightforward linear congruential generator, and it uses a discard technique to ensure uniformity, so it guarantees that in any run of the largest multiple of size smaller than 2^48 samples it will distribute the numbers evenly, satisfying the requirement.


Are there any functional programming languages designed for code-golfing?

Husk

Husk is a pure functional golfing language created by me and Leo and inspired by Haskell.
It combines a rigid type system, type inference and extensive overloading.
Functions are first class values and can be manipulated as easily as other data.
Development of Husk is ongoing and many features are still missing, but you can try it out at TIO.
We also have a SE chatroom for the language.


Assembly for x86 Linux, 106 bytes

BITS 32
                org     0x2E620000
                db      0x7F, "ELF", 1, 1, 1, 0 ; e_ident
                dd      0, 0
                dw      2                       ; e_type
                dw      3                       ; e_machine
                dd      1                       ; e_version
                dd      _start                  ; e_entry
                dd      phdr - $$               ; e_phoff
                dd      0                       ; e_shoff
                dd      0                       ; e_flags
                dw      0x34                    ; e_ehsize
                dw      0x20                    ; e_phentsize
phdr:           dd      1                       ; e_phnum       ; p_type
                                                ; e_shentsize
                dd      0                       ; e_shnum       ; p_offset
                                                ; e_shstrndx
                dd      $$                                      ; p_vaddr
fname           equ     $ - 2
                db      'out', 0                                ; p_paddr
                dd      filesize                                ; p_filesz
                dd      filesize                                ; p_memsz
                dd      5                                       ; p_flags
                dd      0x1000                                  ; p_align
_start:         mov     al, 5                   ; 5 = open syscall
                mov     ebx, fname
                mov     cl, 65                  ; 65 = O_WRONLY | O_CREAT
                mov     dx, 666q
                int     0x80
                lea     edx, [byte ecx + filesize - 65]
                xchg    eax, ebx
                xchg    eax, ecx
                mov     cl, 0
                mov     al, 4                   ; 4 = write syscall
                int     0x80
                mov     al, 1                   ; 1 = exit syscall
                int     0x80
filesize        equ     $ - $$

This is for the nasm assembler. Build the binary with the command line: nasm -f bin -o a.out selfrep.asm && chmod +x a.out

Here's the same file as a hex dump: 7F 45 4C 46 01 01 01 00 00 00 00 00 00 00 00 00 02 00 03 00 01 00 00 00 4C 00 62 2E 2C 00 00 00 00 00 00 00 00 00 00 00 34 00 20 00 01 00 00 00 00 00 00 00 00 00 62 2E 6F 75 74 00 6A 00 00 00 6A 00 00 00 05 00 00 00 00 10 00 00 B0 05 BB 36 00 62 2E B1 41 66 BA B6 01 CD 80 8D 51 29 93 91 B1 00 B0 04 CD 80 B0 01 CD 80

As requested, the program copies itself to a separate file. (The program could have been significantly shorter if it had been allowed to just write to stdout and let the user redirect to a file.)

I avoided using any borderline tricks to reduce the size. This should be a fully conformant 32-bit ELF binary.

Edited to add: In the above version the created file is just a plain file, but it occurs to me that for a couple of bytes (and a tiny bend of the rules), you can create something a little more interesting. This version is only two bytes longer, at 108 bytes:

BITS 32
                org     0x00010000
                db      0x7F, "ELF", 1, 1, 1, 0 ; e_ident
                dd      0, 0
                dw      2                       ; e_type
                dw      3                       ; e_machine
                dd      1                       ; e_version
                dd      _start                  ; e_entry
                dd      phdr - $$               ; e_phoff
                dd      0                       ; e_shoff
                dd      0                       ; e_flags
                dw      0x34                    ; e_ehsize
                dw      0x20                    ; e_phentsize
phdr:           dd      1                       ; e_phnum       ; p_type
                                                ; e_shentsize
                dd      0                       ; e_shnum       ; p_offset
                                                ; e_shstrndx
                dd      $$                                      ; p_vaddr
fname:          db      'asr', 0                                ; p_paddr
                dd      filesize                                ; p_filesz
                dd      filesize                                ; p_memsz
                dd      7                                       ; p_flags
                dd      0x1000                                  ; p_align
_start:         mov     al, 5                   ; 5 = open syscall
                mov     ebx, fname
                inc     byte [ebx]
                mov     cl, 65                  ; 65 = O_WRONLY | O_CREAT
                mov     dx, 777q
                int     0x80
                lea     edx, [byte ecx + filesize - 65]
                xchg    eax, ebx
                xchg    eax, ecx
                mov     cl, 0
                mov     al, 4                   ; 4 = write syscall
                int     0x80
                mov     al, 1                   ; 1 = exit syscall
                int     0x80
filesize        equ     $ - $$

Name this version asr, for "a self-replicator": nasm -f bin -o asr asr.asm && chmod +x asr

Hex dump version for the nasm-impaired:
7F 45 4C 46 01 01 01 00 00 00 00 00 00 00 00 00 02 00 03 00 01 00 00 00 4C 00 01 00 2C 00 00 00 00 00 00 00 00 00 00 00 34 00 20 00 01 00 00 00 00 00 00 00 00 00 01 00 61 73 72 00 6C 00 00 00 6C 00 00 00 07 00 00 00 00 10 00 00 B0 05 BB 38 00 01 00 FE 03 B1 41 66 BA FF 01 CD 80 8D 51 2B 93 91 B1 00 B0 04 CD 80 B0 01 CD 80

When you run it, it creates an almost-identical file named bsr, but one that is itself executable. Running it will create another binary file named csr. And so on.

(Note that annoying things start to happen after zsr. I considered making a version that would cascade the name change to atr and so on, but I think most people will get bored well before then, so it probably isn't worth all the extra bytes.)


APL (Dyalog Unicode), 11 bytes

{⍵/⍨8>≢∪⍵}¨

Takes input as a list of strings.

Explanation:

{⍵/⍨8>≢∪⍵}¨
{       ⍵}¨ for each word
       ∪    take unique letters
    8>≢     length less than 8 as a boolean (0 or 1)
 ⍵/⍨        repeat word that many times

Try it online!


Javascript (561)

This can probably be reduced significantly, but here goes:

i=i.split("\n");d=new Date(i[0]);t=d.getDate();z=t%10;t+=z==1?"st":z==2?"nd":z==3?"rd":"th";m=['January','February','March','April','May','June','July','August','September','October','November','December'][d.getMonth()];y=d.getFullYear();a=d.getHours();b=d.getMinutes();c=d.getSeconds();l=a&&b&&c?" at "+a+":"+b+":"+c:"";g=d>new Date()?"will die":"died";n=i[1].split(" ");n[1]?n[0][n[0].length-1]==","?n=i[1]:n=n[1]+", "+n[0]:n[0];s=i[2]=="Male"?"He":i[2]=="Female"?"She":n;document.write(n+" "+g+" on the "+t+" of "+m+", "+y+l+".<br>"+s+" "+g+" of "+i[3]+".");

Sample I/O:

2 September 1973
J.R.R. Tolkien
Male
pneumonia

  Tolkien, J.R.R. died on the 2nd of September, 1973.
  He died of pneumonia.

January 19, 2038 03:14:08 GMT
Everyone
Unknown
Y2K38

  Everyone will die on the 18th of January, 2038 at 21:14:8.
  Everyone will die of Y2K38.

Try it out on JsFiddle.


Bash, 70 67 50 46 43 16 bytes

`</*/*/*/B*/c*y`

Outputs: <battery 0-100>: command not found

Reads the file /sys/class/power_supply/BAT1/capacity.

Tested using Ubuntu 18.04 on a LENOVO ideapad 500.

Takes a while (since it searches the entire filesystem) - but it saves a byte!

Old answer:

echo Remaining battery is `</*/*/*/B*/c*y`%


General tips for representing large numbers

Look out for special numbers

Some languages have built-in functions for squares, exponentiation with base 2, n-th prime, factorial, or other procedures that can generate large numbers. Check if you number happens to fall into any of those categories.

And if it doesn't, it may happen that a larger number that does will fit for your purposes and can be used instead.


Jelly, 13 bytes
ṗJ$Ẏy@ƒ⁼⁵ɗƇẈṂ

Try it online!
Full program taking a list of pairs L (e.g. ['AB', 'BC', 'CD', 'DZ', 'XY', 'YZ']) as the first argument, the source as the second and the target as the third.
How it works
Brute-force approach.
ṗJ$Ẏy@ƒ⁼⁵ɗƇẈṂ - Main link. Takes L on the left and S on the right
  $           - Group the previous 2 links into a monad f(L):
 J            -   Yield the indices of L; [1, 2, 3, ..., len(L)]
ṗ             -   Get the n'th Cartesian power of L for each n in this range
   Ẏ          - Flatten into a list of lists
         ɗƇ   - Keep those for which the following is true:
      ƒ       -   Reduce the list by the following, starting with S:
    y@        -     Translate, according to the pair mapping
       ⁼⁵     - Does the final result equal T?
           ẈṂ - Get the length of the shortest element


Python 3, 51 48 bytes

 -3 bytes thanks to Mr. Xcoder!

lambda b:sum(n*max(0,len(bin(n))-4.1)for n in b)

Try it online!


Python 2, 131 120 115 114 121 118 bytes

o=1;W=[]
for g in map(len,input().split('/o\\')):W+=[' '*(g-o)];o=max(o-g,0)+2
for q in' /o\ ','_/ \_':print q.join(W)

Try it online!

4 bytes thx to movatica; 10 bytes lost for bug fix.


05AB1E, 6 bytes

D¢DD¢Q

Try it online! or validate more test cases.

Outputs 1 if each item appears a unique number of times, 0 otherwise.

D           # duplicate the input
 ¢          # count occurences of each item in the input
  DD        # triplicate the list of occurence counts
    ¢       # count occurences of each occurence count in the list of occurence counts
     Q      # check whether this is equal to the list of occurence counts

Without the source restriction, this could be 4 bytes: ¢Ð¢Q.


CoffeeScript to JavaScript, 2 bytes

a;

Try it

a is compiled into a;. You may try it here.
; is compiled into nothing. You may try it here.

Without ban "programs where all the commands compile into themselves", js2js would be a much better choice, IMO.


Can the dog reach the neighbour's house?

PHP 781 chars
I know this can be smaller but I am sorry that I am confused. If I take your first two examples (answers no and yes), if diagonal moves are not allowed, answers should be no and no, surely. If diagonal moves are allowed, answers should be yes and yes. Have I misunderstood?
I also took beside to be the criteria of 'reached' as the dog can then wee on the building - however changing that to on top of can easily be done changing the pass counter which currently equals leash length.
Anyway, this allows for diagonal movement, non diagonal would be smaller than this.
<?php
$a.='7
............
...11..222..
...11..222..
...11.......
.x.11.......
...........';$b='No';$c=array();$d=array();function check_2($e,$f){if(($c[$e+1][$f-1]=='2')OR($c[$e+1][$f]=='2')OR($c[$e+1][$f+1]=='2')OR($c[$e][$f-1]=='2')OR($c[$e][$f]=='2')OR($c[$e][$f+1]=='2')OR($c[$e-1][$f-1]=='2')OR($c[$e-1][$f]=='2')OR($c[$e-1][$f+1]=='2')){return TRUE;;}else{return FALSE;}}str_replace("\n\r","\n",$a);$g=explode("\n",$a);$h=$g[0];unset($g[0]);$i=count($g);$j=0;foreach($g as $k){$l=str_split($k);$m=count($l)+1;unset($l[$m]);$c[$j]=$l;++$j;}$d=$c;for($n=0;$n<=$h;++$n){for($e=0;$e<$i;++$e){for($f=0;$f<$m;++$f){if($c[$e][$f]=='2'){$b='Yes';}if($c[$e][$f]=='x'){for($o=-1;$o<2;++$o){for($p=-1;$p<2;++$p){if($c[$e+$o][$f+$p]=='.'){$d[$e+$o][$f+$p]='x';}}}}}}$c=$d;}echo $b;?>

I am pretty sure I can make this smaller but with the confusion not sure which way to go.
Anyway this is my first flood fill so I am sure it can be done more efficiently. Most of the work was getting the input into a variable and a multi dimensional array.
The input it contained in the first variable $a. You can see it here on codepad.
I hope you like it. As a relative newbie and since this is the only answer I suppose I am officially winning here at the moment. Although I cannot imagine this will last long if someone else enters :-)


PostScript, 346 315 bytes

Code (compressed version):

5 5 scale<</C {setrgbcolor}/R{1 0 0 C}/B{0 0 1 C}/W{1 setgray}/o{closepath fill}/c{0 360 arc o}/f{rectfill}/t{translate}/p{currentpoint}/s{gsave p t 4{0 -11 lineto p t -144 rotate}repeat o grestore}>>begin R 0 0 74 48 f B 75 0 5 48 f W 37 24 13 c B 37 24 12 c W 37 24 t 3{-.1 -.5 moveto s 120 rotate}repeat showpage

Code (uncompressed version):

5 5 scale                 % over-all scale

% define some short-named procedures for later use
<<
  /C {setrgbcolor}
  /R {1 0 0 C}            % set red color
  /B {0 0 1 C}            % set blue color
  /W {1 setgray}          % set white color
  /o {closepath fill}
  /c {0 360 arc o}        % draw circle
  /f {rectfill}
  /t {translate}
  /p {currentpoint}
  /s {                    % draw 5-pointed star
    gsave
    p t
    4 {
      0 -11 lineto          % one line of star
      p t
      -144 rotate           % rotate by 144°
    } repeat
    o                       % fill the star
    grestore
  }
>> begin

R 0 0 74 48 f             % draw big red rectangle
B 75 0 5 48 f             % draw blue rectangle
W 37 24 13 c              % draw white circle
B 37 24 12 c              % draw blue circle
W
37 24 t                   % translate to center of circle
3 {
  -.1 -.5 moveto          % move a little off the center
  s                       % draw white star
  120 rotate              % rotate by 120°
} repeat
showpage

Result:


(Σ*)² ⟲ Σ* (aka Round-Trip a String Pair)

I know this is extra credit, but your problem got me thinking a lot about this and what interested me the most was not just separate being the left inverse of combine, but having them be true inverses of each other. This ends up with us defining a bijection from String -> String x String. The path I took was as follows

Define a bijection from String -> N
Define a bijection from N -> N x N
Combine them to get the functions we need

String -> N
Let r be the size of the character set you're working with and give each character a unique value from 1 to r, say f(c) = n. Going from right to left and indexing starting from zero, create the number f(s[0])r^0 + f(s[1])r^1 + f(s[2])r^2 ... f(s[length(s)])r^(length(s)). The lowest number you can get this way is 1, so we let the empty string equal 0.
N -> N x N
Take n in any base you like. Separate even digits into one part of the tuple and the odd digits into the other to make a pair of numbers. E.g. 12345 -> (24, 135). To work your way back, combine the numbers in the opposite way, inserting extra zeros as necessary.
Putting it all together
Haskell

module Main where

import Data.Function ((&))
-- tio is saying this isn't correct for some reason so gotta define it manually
-- import Data.Functor ((<&>))

main :: IO ()
main = do
  putStrLn $ show $ separate "Hello, world!"
  putStrLn $ combine ("Hello, world!", "")
  putStrLn $ show $ separate $ combine ("Hello, world!", "")
  putStrLn $ combine $ separate "Hello, world!"

separate :: String -> (String, String)
separate str =
  str
  <&> toInt
  & fromNZ
  & split
  & tmap toNZ
  & tmap (map fromInt)

combine :: (String, String) -> String
combine strs =
  strs
  & tmap (map toInt)
  & tmap fromNZ
  & join
  & toNZ
  <&> fromInt

base :: Int
base = 95

toInt :: Char -> Int
toInt c = fromEnum c - 31

fromInt :: Int -> Char
fromInt i = toEnum $ i + 31

strip :: [Int] -> [Int]
strip is = case is of
  0 : i : tail -> strip $ i : tail
  _ -> is

split :: [Int] -> ([Int], [Int])
split =
  tmap strip . fst . foldr
    (\a ((acc1, acc0), i) ->
      (if mod i 2 == 0 then
        (acc1, a : acc0)
      else
        (a : acc1, acc0)
      , i + 1
      )
    )
    (([], []), 0)

join :: ([Int], [Int]) -> [Int]
join (l1, l2)= strip $ reverse $ go [] (reverse l1, reverse l2)
  where
    go :: [Int] -> ([Int], [Int]) -> [Int]
    go acc (l1', l2') = case (l1', l2') of
      (head1 : tail1, head2 : tail2) -> head2 : head1 : go acc (tail1, tail2)
      ([], head : tail) -> head : 0 : go acc ([], tail)
      (head : tail, []) -> 0 : head : go acc (tail, [])
      ([], []) ->  acc

tmap :: (a -> b) -> (a, a) -> (b, b)
tmap f (a1, a2) = (f a1, f a2)

fromNZ :: [Int] -> [Int]
fromNZ is =
  if is == [] then [0]
  else let
    (result, finalCarry) =
      foldr
        (\i' (acc, carry) ->
          let
            i =
              if carry then i' + 1
              else i'
          in
            if i >= base then (i - base : acc, True)
            else (i : acc, False)
        )
        ([], False)
        is
  in
    if finalCarry then 1 : result
    else result

toNZ :: [Int] -> [Int]
toNZ is =
  if is == [0] then []
  else let
    (result, finalUncarry) =
      foldr
        (\i' (acc, uncarry) ->
          let
            i =
              if uncarry then i' - 1
              else i'
          in
            if i <= 0 then (i + base : acc, True)
            else (i : acc, False)
        )
        ([], False)
        is
  in
    if finalUncarry then
      case result of
        a : tail ->
          if a == base then tail
          else result
        _ -> result
    else result

m <&> f = f <$> m
infixl 1 <&>

Try it online!


Husk, 4 bytes
¤=Ö←

Try it online! (header runs function on all test cases)
¤       # combin: applies one function to two values and combines the results
 =      # combining function: are they equal?
  Ö←    # function to apply: sort on first element
        # values (implicit): inputs


Wolfram Language (Mathematica), 37 36 bytes

Tr[Csc[i=Pi/#2]^2Sin[2i#]-Cot@i#]/4&

Try it online!

Takes input in the order l, n.

Uses the same approach as in the reference and many other implementations.

Mathematica's trigonometric and arithmetic functions will automatically vectorize, and Tr returns the sum of the elements of a one-dimensional list.

\$\csc\$ and \$\cot\$ are relatively uncommon; \$\csc x=\frac1{\sin x}\$, and \$\cot x=\frac1{\tan x}\$.


Post-mortem update:

Perl 130 bytes

Combining techniques from dan1111's excellent solution with my own, I was able to squeeze one more byte:

@b=qw(Score: 0 correct | 0 wrong);$b[$#x=eval^<>?4:1]++while print"$b[@x]!
@b

"x/./,$_=(0|rand 11).chr(41^2+rand 3).~~rand 11,'='

There's a few things that might not be immediately obvious. If @x is an array, then $#x (the largest index of @x) will be one smaller than the length of @x. In this way, I can use $#x to point to the appropriate counting variable, and the length of @x to the corresponding message in a single assignment, without having to +1. The score string is repeating by /./, which will return 1 if an only if $_ is non-empty.

Perl 131 bytes

Here's my Perl attempt, which is more or less a direct translation of my PHP solution below.

@r=correct,${_^($n=eval^<>?z:r)}++while@z=wrong,print"@$n!
Score: $- @r | $% @z

"x@r,$_=(0|rand 11).chr(41^2+rand 3).~~rand 11,'='

$- and $% are used for counting variables as they default to 0, alleviating the need for a printf, and at the same time allowing me to combine the print statements into one. The score string is not printed the first iteration because @r has not yet been defined, and therefore x@r (repeat by the length of the array @r) repeats the string zero times, resulting in an empty string.

Once again using chr(41^2+rand 3) to generate +*-, as well as a bitwise xor _^ to switch between r→- and z→%. I would have liked to use a type glob for *n=eval^<>?z:r, saving a byte @$n→@n, but unfortunately typed as a string this comes back as either *main::r or *main::z, which isn't very useful.

</bandwagon>

PHP 157 (155) bytes

Just to get a smattering of languages:

<?for($X=$Y=+$x=correct;$y=wrong;)echo$q=rand(0,10).chr(rand(2,4)^41).rand(0,10),'=',eval("\${_&\$n=$q^fgets(STDIN)?y:x}++;"),$$n,"!
Score: $X $x | $Y $y

";

The initial $X=$Y=+ is necessary, because undefined variables print as an empty string, instead of 0. Unfortunate, but still shorter than using a printf. One thing to notice is the 'magic formula' chr(rand(2,4)^41). 2^41 = 43 (+), 3^41 = 42 (*) and 4^41 = 45 (-). chr(rand(3,5)^46) would also work, but in a different order.

This can be made 2 bytes shorter by using a few binary characters:

<?for($‡=$†=+$x=correct;$y=wrong;)echo$q=rand(0,10).chr(rand(2,4)^41).rand(0,10),~Â,eval("\${~\$n=$q^fgets(STDIN)?y:x}++;"),$$n,"!
Score: $‡ $x | $† $y

";

where †, ‡ and Â are characters 134, 135 and 194 respectively.


R, 19 chars

polyroot(scan(n=3))

or more strictly following the I/O requirements in 58 chars:

r=polyroot(rev(scan(sep=",")));cat("r1=",r[1],"\nr2=",r[2])

edit: reversed coefficients


Python 2, 123 bytes

a,b,c=map(int,input().split('-'))
for a,b,c in[[b,c,'big'],[b,a,'little'],[a,b,'middle']]:print(c+'-endian')*(a<13)*(b<32),

Try it online!

Python 2, less input parsing, 123 bytes

d=input()
for a,b,c in[[3,6,'big'],[3,0,'little'],[0,3,'middle']]:print(c+'-endian')*(int(d[a:a+2])<13)*(int(d[b:b+2])<32),

Try it online!


Build a numerical library without using any primitive data type

Haskell

Haskell is pretty good at defining obvious things from scratch.
Almost all definitions are simple translations of math axioms.
Doesn't support negative numbers, behaves badly on errors (e.g. 1-2 or 1/0).

data MyNum = Zero | S MyNum

toNative :: MyNum -> Integer
toNative Zero = 0
toNative (S n) = (toNative n) + 1
fromNative :: Integer -> MyNum
fromNative 0 = Zero
fromNative n = S $ fromNative $ n-1

-- numIfGE a b c = c if a>=b else 0
numIfGE _ Zero n = n
numIfGE Zero _ n = Zero
numIfGE (S a) (S b) n = numIfGE a b n

instance Num MyNum where
    a + Zero = a
    a + (S b) = S (a + b)

    a - Zero = a
    (S a) - (S b) = a - b

    a * Zero = Zero
    a * (S b) = a + (a*b)

a `divi` b = numIfGE a b (S $ (a - b) `divi` b)
a `modu` b = a - ((a `divi` b) * b)


Python 2 / 3, 52 bytes

lambda l:sum(l[:1]+[x*int(1-(1/2)*4)for x in l[1:]])

int(1-(1/2)*4) returns 1 in Python 2 because 1/2 evaluates first to 0, and then 0 * 4 = 0.

int(1-(1/2)*4) returns -1 in Python 3 because 1/2 evaluates first to 0.5, and then int(0.5 * 4) = int(2.0) = 2.


Python 2, 200 197 193 140 bytes

f=lambda n,D,S={0}:sum([f(n-x,D,S|{x+y for y in S})for x in D],[])if n>0else[S]*-~n
g=lambda*a:(f(*a)and reduce(set.__and__,f(*a))or{0})-{0}

(Thanks to @Nabb for tips)
Here's a poorly golfed solution for now to get things started. Call with g(16, [1, 5, 10, 25]) — output is a set with the relevant denominations.
The approach is straightforward, and is broken down into two steps:

f looks at all ways of reaching n with denominations D (e.g. [1, 5, 10]), and for each one it works out all amounts that can be made with these denominations (e.g. set([0, 1, 5, 6, 10, 11, 15, 16])).
g calculates the intersections of the results of f, then removes 0 for the final answer.

The program solves cases 1-5 and 7 fine, stack overflows on 6 and takes forever on 8.
If there is no solution (e.g. g(7, [2, 4, 6])), then the program returns an empty set. If an error is allowed to be thrown for such a case, then here is a shorter g:
g=lambda*a:reduce(set.__and__,f(*a))-{0}


Convex, 5 bytes

'_%.\

Try it online!

Convex is a CJam-based language, and this answer is almost the same as my CJam answer, except for l~ which is unneeded here, since Convex does automatic argument evaluation at the start of the program.

Explanation:

'_%.\ e# Full program only
'_    e# Push '_'
  %   e# Split and remove empty chunks
   .\ e# Vectorize by Swap


Mathematica, 140 139 105 bytes

Total[DiagonalMatrix@@@{{#},{1-Sign[Differences@#^2],1}}]&@(x/.Solve[#~CharacteristicPolynomial~x==0,x])&

I just found the builtin DiagonalMatrix which allows for an easy way to place the 0s and 1s along the superdiagonal.

Usage


Single Digit Representations of Natural Numbers

Python 3, 210 bytes · 100 + 59045 digits = 80045

def f(n,d):
 m={d:d},
 while{n}-{*m[0]}:m={z:(p[x],o,q[y])for p,q in zip(m,m[::-1])for x in p for y in q for z,o in zip([x+y,x-y,x*y,y<9and x**y,x%y<1and x//y,int(f"{x}{y}")],"+-*^/|")if z>0},*m
 return m[0][n]

Try it online!

Scoring

Scoring goes much faster using this modified version that solves 1 through 1000 all at once:

def f_gen(d):
 m={d:d},
 while 1:yield from m[0].items();m={z:(p[x],o,q[y])for p,q in zip(m,m[::-1])for x in p for y in q for z,o in zip([x+y,x-y,x*y,y<9and x**y,x%y<1and x//y,int(f"{x}{y}")],"+-*^/|")if z>0},*m

def size(expr):
    return 1 if isinstance(expr, int) else size(expr[0]) + size(expr[2])

score = 0
for d in range(1, 10):
    s = set(range(1, 1001))
    for n, expr in f_gen(d):
        if n in s:
            s -= {n}
            score += size(expr)
            print(n, expr)
            if not s:
                break
print(score)


05AB1E, 3 bytes

Code

LíO

Uses the 05AB1E encoding. Try it online!

Explanation

L       # Range
 í      # Reverse
  O     # Sum


Jelly, 6 bytes

œc2IFP

œc2 gets all combinations without replacement of length 2. I computes the difference list of each of those pairs, yielding a list like [[1], [2], [3], ..., [1]]. We Flatten and take the Product.

Try it here!


Brachylog, 8 bytes
{|∧ℕ₁}ᵐ≠

Try it online!
Explanation
{    }ᵐ     Map on the Input:
              Input = Output…
 |            …or…
  ∧ℕ₁         …Output is in [1,+inf)
       ≠    All elements of the output must be different
            (Implicit labeling)


Sample win/loss data generator based on certain criteria


The Note of Destiny - place a note on a staff

Ruby – 271 267 252 249 234 229 220 214 characters

I literally just learned Ruby for this. So there is certainly room for improvement in golfing it down. Or doing anything really. But I needed a language with mutable strings. :)

def f(n)s=[0]*20
s.fill{|i|i%2>0?i<3||i>11?" ---":?-*5:" "*5}
s[l=(3-n[(p="H_L".index n[0])?1:0].ord)%7+7*(p||1)][1,2]=("#b"[n[-1]]||s[l][1])+?O
s[l+3-2*o=l>7?3:1,3].map{|t|t[o]=?|}
puts s[[3,l].min..[11,l].max]end

Somewhat ungolfed:

def f(note)
  staff=[]
  0.step(20) {|i| staff[i] = " "*5}
  1.step(19,2) {|i| staff[i] = " ---"}
  3.step(11,2) {|i| staff[i] = "-"*5}
  level = 7
  if !(pos="HL".index note[i=0]).nil?
    level = 14*pos
    i += 1
  end
  level += (73-note[i].ord)%7
  staff[level][2] = "O"
  mark = note[-1]
  if !"#b".index(mark).nil?
    staff[level][1] = mark
  end
  offset = (level > 7) ? 3 : 1
  staff[level-2*offset+3,3].map {|line| line[offset] = "|"}
  first = [3,level].min
  last = [11,level].max
  puts s[first..last]
end

I can cut it by another 2 characters down to 212 characters if leading blank lines are allowed. This solution doesn't fill the lines that aren't printed anyway:

def f(n)s=[]
[3,l=(3-n[(p="H_L".index n[0])?1:0].ord)%7+7*(p||1)].min.step(l>11?l:11){|i|s[i]=i%2>0?i<3||i>11?" ---":?-*5:" "*5}
s[l][1,2]=("#b"[n[-1]]||s[l][1])+?O
s[l+3-2*o=l>7?3:1,3].map{|t|t[o]=?|}
puts s
end

Are lambda's fair game? Then I can get 210 characters with the first approach

f=->n{s=[0]*20
s.fill{|i|i%2>0?i<3||i>11?" ---":?-*5:" "*5}
s[l=(3-n[(p="H_L".index n[0])?1:0].ord)%7+7*(p||1)][1,2]=("#b"[n[-1]]||s[l][1])+?O
s[l+3-2*o=l>7?3:1,3].map{|t|t[o]=?|}
puts s[[3,l].min..[11,l].max]}

Or 207 characters with additional blank lines:

f=->n{s=[]
[3,l=(3-n[(p="H_L".index n[0])?1:0].ord)%7+7*(p||1)].min.step(l>11?l:11){|i|s[i]=i%2>0?i<3||i>11?" ---":?-*5:" "*5}
s[l][1,2]=("#b"[n[-1]]||s[l][1])+?O
s[l+3-2*o=l>7?3:1,3].map{|t|t[o]=?|}
puts s}

Of course, now you'd need to do f.call("HGb").


Labyrinth, 76 bytes

 `:_64/"32}
,`    (3  :=-{
"`{"; _v2$  ;`3
"`".:@ ; ".5(`3.
<       "" `^`;>

Another collab with @MartinBüttner and on the more insane side of the Labyrinth spectrum – for the first time we have all four of ^>v< in the one program. Try it online!

Explanation

The general algorithm, which runs in a loop, is as follows:

 1.   Read a char
 2.   If EOF:
 3.     Move all digits from auxiliary stack to main
 4.     Output all digits on main stack
 5.     Halt
      Otherwise:
 6.     If char is a letter (c >= 64):
 7.       If random turns left:
 8.         Output char XOR 32
          Otherwise:
 9.         Output char
        Otherwise:
10.       Shift char to auxiliary stack
11.       If char is space (c-32 == 0):
12.         Pull char back from auxiliary stack
13.         Output underscore
          Otherwise:
14.         Continue loop

To keep the explanation compact, here's roughly how each part of the program corresponds to the pseudocode above:

Here are the interesting parts.

Getting randomness in Labyrinth

There's only one way to get randomness in Labyrinth, and it's when the IP tries to go forwards but 1) there's neither a path forwards nor backwards and 2) there's paths available left and right. In this case, the IP randomly chooses between the left and right routes.

This is only possible using the^>v< operators, which pop n and shift the row/column n away by 1. For example, the program (Try it online!)

" 1
""v!@
  2
   !@

outputs either 1 or 2 randomly, since the v shifts the column with offset 0 (i.e. the column the IP is on) by 1, yielding

"
""1!@
  v
  2!@

The IP is facing rightward and tries to go forwards (top of stack is zero) but can't. It also can't move backwards, so it randomly chooses between left or right.

Golf tricks

The program starts from the first char in reading order, which you'll notice is actually step 6. However, popping from an empty Labyrinth stack yields 0, so steps 10 and 14 occur, shifting a zero to the auxiliary stack, which is effectively a no-op.
The main stack is effectively empty after every iteration, which allows us to golf the code layout by using > and < on the implicit zeroes at the bottom. The > wraps the bottom row around so that the IP moves from the bottom right to the bottom left, and the < shifts the row back. The IP then happily moves up the left column to continue the loop.
Digits in Labyrinth pop n and push 10*n + <digit>. In addition, chars are taken modulo 256 before being output. Putting these two together lets us output 95 (underscore) by doing `33 to  32 (space), which works because -3233 % 256 = 95. Even though there are other ways to turn 32 into 95 (;95 being the easiest), working with a negative number here allows us to compact the code a bit with left turns.


Use a genetic algorithm to recreate a string

APL (98)

L←⍴T←⎕UCS'Hello World!'⋄F←{+/2*⍨⍵-T}⋄0{0=F ⍵:⍺,⎕UCS⍵⋄(⍺+1)∇{(F⍵)≤F⊢C←⍵+(2-?3)×(⍳L)=?⍴⍵:⍵⋄C}⍵}L?255

Can be shortened, at the expense of easy configurability and of result, I'll do so when this one is beaten.

Output:

5940 Hello World!

(or another number between ~4000-~9000).

Credit for the algorithm: http://www.electricmonk.nl/log/2011/09/28/evolutionary-algorithm-evolving-hello-world/

Explanation:

L←⍴T←⎕UCS'Hello World!': The target is the ASCII values (⎕UCS) of 'Hello World'. (You can change the string.) L is its length.
F←{+/2*⍨⍵-T}: F measures the 'distance' between a candidate and a target. This is the sum of the squares of the difference between each character.
0{0=F ⍵:⍺,⎕UCS⍵⋄(⍺+1)∇...⍵}L?255: Starting with a random string (L?255), if the distance between the target and the candidate is 0 (i.e. we have it) (0=F ⍵:), then output the generation and the string (⍺,⎕UCS⍵). Otherwise, mutate the candidate and proceed to the next generation.
(F⍵)≤F⊢C←⍵+(2-?3)×(⍳L)=?⍴⍵:⍵⋄C: Generate a new candidate by selecting a random position and mutating it by one. If the distance to the target is less than the old candidate, return the new candidate, otherwise keep the old candidate.


JavaScript, 474 bytes
k=((e,r)=>{for(o=[],e=[...e],r=[...r],w=r.reduce((r,h,n)=>!(r[n]=e.map((e,r)=>h==e?r:"").filter(Number))||r,[]),[z]=w,h=[],x=0;x<w.reduce((e,r)=>e*=r.length||e,1);x++)z.forEach((e,r)=>{for(g=[z[r]],j=1;j<w.length;j++)for(n=w[j],y=0;y<n.length;y++)if(g.slice(-1)[0]<n[y]&&!h.some(e=>e.toString()==[...g,n[y]].toString())){g.push(n[y]);break}h.push(g)});return h.filter(e=>e.length==w.length).forEach(r=>{d=[...e],r.forEach(e=>d[e]=d[e].toUpperCase()),o.push(d.join(""))}),o})

Live example:

k=((e,r)=>{for(o=[],e=[...e],r=[...r],w=r.reduce((r,h,n)=>!(r[n]=e.map((e,r)=>h==e?r:"").filter(Number))||r,[]),[z]=w,h=[],x=0;x<w.reduce((e,r)=>e*=r.length||e,1);x++)z.forEach((e,r)=>{for(g=[z[r]],j=1;j<w.length;j++)for(n=w[j],y=0;y<n.length;y++)if(g.slice(-1)[0]<n[y]&&!h.some(e=>e.toString()==[...g,n[y]].toString())){g.push(n[y]);break}h.push(g)});return h.filter(e=>e.length==w.length).forEach(r=>{d=[...e],r.forEach(e=>d[e]=d[e].toUpperCase()),o.push(d.join(""))}),o})

console.log(k('this is a very long sentence with several words of no significance', 'henge'));

Explanation:
For each letter in the word, an array of indices is constructed corresponding to every position of that letter in the sentence.
Then inside a nest of 4 for loops, every possible path from the first array to the last array is computed, where each step is into an element with greater numeric value in the next array.
This produces an array of paths whose length is equal to the maximum possible paths, which is the product of multiplying the length of each letter indices array (this number gets big real quick as the length of the word increases).
Then all paths whose length is smaller than the word are excluded, since they failed to find a valid step between each array.
You can see the unminified logic at this stackoverflow answer.
I am confused by this line (even though it's my code), whose intent is to check the existing paths before adding a step to the current path to make sure its constructing a unique path:
if (!paths.some(p => p.toString() == [...path, arrays[j][y]].toString())) {
  path.push(arrays[j][y]);
  break;
}

It seems to me like this should erroneously prevent construction of multiple paths who share any beginning steps.  But it actually works as intended.  So I am stumped.