Retina, 209 107 99 97 92 bytes

.(?=(.+)(?<=(?=<((\|+|(?<-5>\|(?=\1())?)+)[^|]+)+$(?(5)!)).+( )+\S+))\4
/ \
+` (.*~|~.*)
$1

For counting purposes, each line goes in a separate file, but you can run the code from a single file with the -s flag.

Bringing the best features of .NET regex and Retina together: balancing groups, arbitrary length lookbehinds and repeated regex substitution.

Essentially, the long regex encodes a valid solution and the regex engine's backtracker finds one of the optimal ones for me.

Explanation

First, let's consider how we can find a valid solution (not necessarily producing the correct output) with a regex. We can use .NET's balancing groups to help us count the stretchy parts. Consider the following simpler regex:

\S+( )+.+(?<=(?(1)!)^([^|]+(\|+|(?<-1>\|)*))+>)

We can disect that.

\S+( )+.+

This matches the entire string, pushing one capture onto the group 1 stack for each space in the input. We will use that stack to ensure that the stretchy parts exactly fill the space captured into those groups.

Next is a lookbehind. The catch is that lookbehinds are matched from right to left in .NET (so that's how you should read them). This gives us the opportunity to traverse the string a second time, figuring out whether there's a subset of stretchy part that sums to the number of matched spaces. Going through the lookbehind from right-to-left:

>

This is just ensure that we're actually starting from the end of the string (the snake's tail).

(
  [^|]+
  (
    \|+
  |
    (?<-1>\|)+
  )
)+

For each stretchy part, this either just matches the entire part without doing anything (\|+), or it matches the entire part while popping captures off stack 1 ((?<-1>\|)*). Having this alternation ensures that we can only fully extend a stretchy part or leave it unchanged, and not get stuff like |/\|. Then we move on to the next stretchy part with [^|]+.

(?(1)!)^

Finally, we ensure that we've traverse the entire string (both snakes), and that stack 1 is completely empty. I.e. that we've found a subset of stretchy part that exactly sums to the number of spaces we've captured earlier.

The backtracker will go back and forth through the string trying all combinations of unchanged and extended parts until the subset sum problem is solved. If such a subset doesn't exist, the lookbehind will fail. This will cause the backtracker to go back to the \S+( )+.+ part and try capturing one space less with ( )+ (which will just be cover by .+ instead). Due to the greediness of + we therefore try filling as many spaces as possible.

You can check the validity of this approach with this slightly modified substitution:

\S+(( )+).+(?<=(?(2)!)^([^|]+(\|+|(?<-2>\|)*))+>)
=$1=

Which will give you a string =spaces= with exactly the number of spaces that can be filled with the given snakes.

I've had to add some more trickery to actually expand the correct |s. Basically, I want to replace all |s which were matched using the (?<-1>\|)+ branch. The idea is to match an individual character, put the solver in a lookaround and set a flag if the match happens to be inside that branch. If that flag wasn't set we invalidate the match at the end to avoid replacement of other characters.

To do this, we use a bunch of nested lookarounds. Again, .NET's variable-length lookbehinds are matched from right to left, so if we nest lookaheads and lookbehinds, we can let the regex engine traverse the string several times. For golfing reasons, the solver is reversed in my actual solution (starting at the end, picking up the spaces from right to left, and then solving the subset sum from left to right), but otherwise the structure of the solver is exactly the same. Let's dissect the full regex:

.(?=(.+)...)

We match a single character, then capture the remainder of the string and move the cursor to the end of the string. We will use this group 1 later to check in the solver whether we're at the position of the match.

(?<=....+( )+\S+)

This is like the first part of the simple solver above, except that we pick up the spaces from right to left. The backtracking of the number of spaces works exactly the same as before, except that we're using group 5 now.

(?=<((\|+|(?<-5>\|(?=\1())?)+)[^|]+)+$(?(5)!))

This is the same as before, except we're going from left to right, and whenever we match a | in the expanding branch, we check if it's the one being matched right with

(?=\1())?

This is an optional lookahead. It tries to match group 1 again (which, here, is only possible if we're right after the character being matched), and if we do, we capture an empty string into group 4, which indicates that we did find the current character in one of the expanded bits. If \1 doesn't match, 4 won't capture anything, and the ? ensures that the failing lookahead won't affect the solver at all.

Finally, after all the solving is done, we just check with \4 whether this lookahead was used. If so, we want to replace the current character with /\.

One difficulty remains: removing the right amount of spaces. The shortest way to do this I've found so far is to insert a space along with the /\ and then get rid of one space between the tongues for each of those marker spaces in a separate step:

+` (.*~|~.*)
$1


TSQL

Image recognition? Sounds like a job made for SQL :)

WITH cte AS (
  SELECT LEN(data)-LEN(REPLACE(data,'#','')) c FROM test_t
)
SELECT
  CASE WHEN COUNT(DISTINCT c)>2                           THEN 'triangle'
       WHEN SUM(CASE WHEN c=0 THEN 0 ELSE 1 END) = MAX(c) THEN 'square'
                                                          ELSE 'rectangle'
       END result
FROM cte;

An SQLfiddle with sample data and test.


Find the Block on the Extended Periodic Table Using the Diagonal Rule

Charcoal, 59 bytes
Ｎθ⊞υ²Ｗ›θ⊗Συ«≧⁻⊗Συθ⊞υ⁺⁴⌈υ»§”>-◧βYTＢ↷p{ï⭆Σ]¬∕↷›”ＬΦυ‹﹪⊖θΣυΣ✂υκ

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

Input the atomic number.
⊞υ²

Start with just an s-shell.
Ｗ›θ⊗Συ«

Repeat while the number of electrons left will fill all the shells twice...
≧⁻⊗Συθ

... remove those electrons, and...
⊞υ⁺⁴⌈υ

... add another shell which can hold 4 more electrons than the previous.
»§”>-◧βYTＢ↷p{ï⭆Σ]¬∕↷›”ＬΦυ‹﹪⊖θΣυΣ✂υκ

Count how many of the remaining shells have no electrons and look that up in the compressed string of block letters. (Because of the way Sum works in Charcoal, the calculation is adjusted slightly to avoid a sum of no elements, which ends up offsetting the result by 1, which is compensated by moving the z to the beginning of the string where it can be cyclically indexed.)


Python, 441 chars

from math import*
V=[map(float,raw_input().replace('?','0').split())+[0]]
for i in' '*9:
 W=[]
 for a,b,c,A,B,C,R in V:
  if B and C:A=A or pi-B-C
  if a:
   if A:R=R or a/sin(A)
   else:
    if b and c:A=acos((b*b+c*c-a*a)/2/b/c)
    elif R:N=asin(a/R);W+=[(b,c,a,B,C,N,R)];A=pi-N
  else:a=R*sin(A)
  W+=[(b,c,a,B,C,A,R)]
 V=W
V=[T for T in V if all(t>0 for t in T)]
if V:
 for T in V:print' '.join(map(str,T[:-1]))
else:print'No solution'

Does your typical trig to compute the answer.  The current possible solutions are stored as tuples in V.  Any unknown values are recorded as 0.  A seventh variable R is the value a/sin(A)==b/sin(B)==c/sin(C).

I use a trick where the a/b/c values are cycled each iteration to avoid lots of redundant logic.  The inner loop only needs to compute values of the A side or angle.


Avoid sub literals. In many cases, you can simply use {} for code blocks. For example, don't write the following code.

sub ($a){$a*2}

Instead, use blocks syntax. This also lets you to use $_, @_, and %_ placeholder variables, if you only need a single variable. If you need more, you can use $^a, $^b variables, and so on.

{$_*2}

Also, in certain rare cases, it's possible to use whatever code (especially when you have simple expressions). The * replaces the placeholder argument.

* *2


Python 2, 76 73 72 70 69 68 bytes

n=input();c=k=m=11
while n:m*=k/c;k+=c;n-=`k`==`k`[::~m%k-c]
print k

Thanks to @WheatWizard for golfing off 3 bytes!

Thanks to @ØrjanJohansen for golfing off 1 byte!

Thanks to @xnor and @ØrjanJohansen for paving the way to 68 bytes!

Input is 0-indexed. Try it online! or verify the first 31 test cases.

Background

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

meaning that (p - 1)! + 1 is evenly divisible by p if and only if p is prime.

If p > 1 is not prime, it is composite; let q be the smallest prime divisor of p. Clearly, q ≤ p/q. There are two cases:

If q = p/q, we have that p = q².

If q = 2, (p - 1)! = 3! = 6, so (p - 1)! is congruent to 2 modulo p.

If p/q = q > 2, so 2q < p. This way, q and 2q are both among 1, …, p - 1, whose product is the factorial of p - 1, so 2p = 2q² = q · 2q divides (p - 1)! evenly.
If q < p/q, q and p/q are both among 1, …, p - 1, so p = q · p/q divides (p - 1)! evenly.

Summing up,

for all integers p > 1.

Now, for all integer congruences and all integers a, b, and c, the following holds.

When a = -1, b = 11, and c = -1, we follow that

and, since 21 and -23 are congruent modulo 44 and -1 and 11p-1 are congruent modulo 11p, we arrive at the following conclusion.

For all possible values of p, the outcome (11, 21, or 11p - 1) will fall in the range 0, …, 11p - 1, so these values match those that will be returned by Python's % operator.

How it works

We initialize c, k, and m to 11 after the saving the input in n. c will be constant for the remainder of the program. Since there are three occurrences of c on the following line and assigning c costs only two bytes, this saves a byte. k can be thought of 11p using the meaning of p from the previous paragraph; initially, k = 11 = 11 · 1!. m takes the place of 11 · (p - 1)!; initially, m = 11 = 11 · 0!. k and m will satisfy the relationship m = 11 · (k/11)! at all times.

n represents the number of “Stephen's palindromes” we have to find. Since k = 11 initially, we can output k verbatim without further computation. However, when n is positive, we enter the while loop. The loop begins by multiplying m by k/c = p, then adding 11 to k, thus incrementing p. If k is a member of the sequence, we subtract 1 from n and start over. Once n reaches 0, we found the sequence member at the desired index and break out of the loop, then print the last value of k.

The expression

`k`==`k`[::~m%k-c]

performs the actual test, and it's result (True / 1 for sequence members, 0 / False otherwise) is subtracted from n. As seen before, ~m % k = (-m - 1) % k = (-11 · (p - 1)! - 1) % 11p equals 10 if p is prime, 21 if p = 4, and 11p - 1 > 43 if p > 4 is composite. Thus, after subtracting c = 11, we're left with -1 for prime p and a positive integer larger than 9 otherwise.

For prime p, `k`[::-1] gives us the string representation of k with reversed digit order, so comparing it to `k` checks whether k is a palindrome. If it is, all conditions are fulfilled and k is a sequence member. However, if p is not prime, the large range step and the fact that k will always have more than one digit mean that `k`[::-1] cannot have the same number of digits as `k`, let alone be equal to it.


Classify Quadrilaterals | Help me with my math exam!

APL (Dyalog), 104 89 80 82 81 79 78 bytes

⍙←{⍵⍺⍺1⌽⍵}
⎕←(|x){⍵≡2⌽⍵:≡⍙¨0⍺⍵⋄2 4=+/1=2|+⍙↑⍵(=⍙⍺)}2|1+-⍙(12○x←-⍙⎕+.×1 0J1)÷○1

Try it online!

Input/Output
Takes a 4×2 matrix of coordinates as input
Outputs

1 1 1 for Square
1 1 0 for Rhombus
1 0 1 for Rectangle
1 0 0 for Parallelogram
1 0 for Kite
0 1 for Trapezium
0 0 for Quadrilateral

Algorithm
First, find all 4 side lengths and angles of the quadrilateral
If both pairs of opposite angles are equal (OA), then the shape is some kind of parallelogram. Determine if all side lengths are equal (AS, Adjacent Sides) and if all angles are equal (AA).
+--------+----------------+----------------+
|        |       AA       |      ~AA       |
+--------+----------------+----------------+
|   AS   |     Square     |    Rhombus     |
|--------+----------------+----------------+
|  ~AS   |    Rectangle   |  Parallelogram |
+--------+----------------+----------------+

If not OA, then:

Determine if there are exactly 2 pairs of equal adjacent sides and if they are separated (aabb instead of aaab). If so, the shape is a kite.

Determine if there are exactly 1 pair of parallel opposite sides. If so, the shape is a trapezium.

Otherwise, the shape is a quadrilateral.

Code
⍙←{⍵⍺⍺1⌽⍵} defines a new operator. In APL, an operator means a higher-order function. This operator takes 1 functional argument (⍺⍺) and returns a monadic function that:

Rotates (1⌽) the argument (⍵)
Apply ⍺⍺ between it and ⍵

This is especially useful for scalar functions since most of them implicitly map across array arguments, allowing ⍙ to apply those between each adjacent pair of elements with wrap around. For example +⍙1 2 3 4 is 1 2 3 4 + 2 3 4 1 which evaluates to 3 5 7 5.

x←-⍙⎕+.×1 0J1 converts the input coordinate matrix into an array of complex numbers representing the vectors of the 4 sides of the shape.

⎕, when referenced, takes and returns input

1 0J1 represents the vector [1,i] ("vector" in the mathematical sense, and "i" as the square root of -1). In APL, a complex number a+bi is written aJb

+.× matrix multiplication. Mathematically, the result would be a 4×1 matrix. However, +.× is called "inner product" in APL which generalizes matrix multiplication and vector inner product and allows you to do even stuff like "multiply" a 3-dimensional array with a 2-dimensional one. In this case, we are multiplying a 4×2 matrix and a 2-element vector, resulting in a 4-element vector (of the complex number representations of the 4 given vertices).

-⍙ is pairwise subtraction with wrap around as noted above. This gives the vectors of the 4 sides of the shape (as complex numbers). These vectors point in the "reverse" direction but that doesn't matter.

x← stores that into the variable x

2|1+-⍙(12○x)÷○1 finds (a representation of) the exterior angles at the 4 vertices of the shape.

12○x finds the principal argument, in radians, of each of the 4 side vectors.

÷○1 divides by π so that the angles are easier to work with. Thus, all angles are expressed as a multiple of a straight angle.

-⍙ Pairwise subtraction with wrap around as noted above. This gives the 4 exterior angles.

2|1+ The principal argument is capped (-1,1] and pairwise subtraction makes the range (-2,2]. This is bad since the same angle has 2 different representations. By doing "add 1 mod 2", the angle is re-capped at (0,2]. Although all angles are 1 more than what it should be, it's fine if we keep that in mind.

|x finds the magnitude of each of the 4 side vectors

{⍵≡2⌽⍵:≡⍙¨0⍺⍵⋄2 4=+/1=2|+⍙↑⍵(=⍙⍺)} defines and applies a function with the array of 4 exterior angles as right argument ⍵ and the array of 4 side lengths as right argument ⍺.

The function has a guarded expression. In this case, ⍵≡2⌽⍵ is the guard.
If the guard evaluates to 1 then the next expression ≡⍙¨0⍺⍵ is executed and its value returned.
If the guard evaluates to 0, that expression is skipped and the one after that 2 4=...=⍙⍺) gets executed instead.

⍵≡2⌽⍵ checks if both pairs of opposite angles are equal.

2⌽⍵ rotates the angles array by 2 places.
⍵≡ checks if that is the same as ⍵ itself

≡⍙¨0⍺⍵ returns a unique value for each parallelogram-type shape.

0⍺⍵ is the 3-element array of the scalar 0, the side lengths array ⍺, and the angles array ⍵.
≡⍙¨ executes ≡⍙ for each of those elements.
≡⍙ checks if all values of an array are equal by checking if rotating it by 1 gives the same array. Scalars do not rotate so ≡⍙0 returns 1. As noted above, ≡⍙⍺ checks for a rhombus and ≡⍙⍵ checks for a rectangle.

2 4=+/1=2|+⍙↑⍵(=⍙⍺) returns a unique value for each non-parallelogram-type shape. This is achieved by intertwining the checks for kite and trapezium.

2=+/1=2|+⍙⍵ checks for a trapezium.

+⍙⍵ gives the adjacent angle sums. The interior angles of parallel lines sum to a straight angle, thus so does the exterior angles of parallel sides of a quadrilateral. So, each pair of parallel sides should lead to two 1 or -1 in the adjacent angle sums.

1=2| However, the angles in ⍵ are 1 more than what they should be, so the angles actually sum to 1 or 3. This can be checked by "mod 2 equals 1".

+/ sums the array. This gives a count of adjacent angle sums which is 1 or 3.

2= check if that equals 2. (I.e. if there is exactly one pair of parallel sides)

4=+/1=2|+⍙(=⍙⍺) checks for a kite.

(=⍙⍺) gives an array indicating which adjacent sides are equal. Unlike ≡, = work element-wise. Thus, this is a 4-element array with 1s where the length of that side is equal to that of the "next" side.

+⍙ Pairwise sum with wrap around.

1=2| Since (=⍙⍺) gives a boolean array (one with only 0s and 1s), the only possible values of pairwise sum are 0, 1 and 2. So 1=2| is same as just 1=.

+/ sums the array. This gives a count of pairwise sums which is 1.

4= check if that equals 4. The only way that happens is if (=⍙⍺) is 1 0 1 0 or 0 1 0 1. As noted above, this means the shape is a kite.

2 4=+/1=2|+⍙↑⍵(=⍙⍺) intertwines the above checks.

⍵(=⍙⍺) is the 2-element nested array of the array ⍵ and the array (=⍙⍺)

↑ promotes the nested array to a proper matrix. Since ⍵(=⍙⍺) is a 2-element array of 4-element arrays, the result is a 2×4 matrix.

+⍙ Since ⌽ (and, by extension, ⍙) rotates the last (horizontal) axis, +⍙ to a matrix is same as applying +⍙ to each row individually.

1=2| both residue/mod (|) and equals (=) works on a per-element basis, even to matrices.

+/ By default, reduce (/) works along the last (horizontal) axis. So +/ sums along rows and turn a 2×4 matrix into a 2-element simple array.

2 4= Since = works per-element, this checks the kite and trapezium conditions simultaneously.


Python 3, 274 272 271 bytes
2 bytes saved thanks to @orlp.

def g(p):
 q=lambda a:[[i,a]for i in range(len(p)-a)if p[i][:-1]==p[i+a][:-1]or p[i][-1]in p[i+a]]
 for n in q(1)+q(3):
  s=sum(n);c=p[:s]+p[s+1:];c[n[0]]=p[s]
  if g(c):return p[n[0]]+' <- '+p[s]+','+g(c)
 return' 'if len(p)<2else[]
print(g(input().split(','))[:-2]or'')

This is extremely slow. However, you can try it with a memoize. This has a few extra list-tuple conversions, but is otherwise equivalent.
import functools
@functools.lru_cache(maxsize=None)
def g(p):
 q=lambda a:[[i,a]for i in range(len(p)-a)if p[i][:-1]==p[i+a][:-1]or p[i][-1]in p[i+a]]
 for n in q(1)+q(3):
  s=sum(n);c=list(p[:s]+p[s+1:]);c[n[0]]=p[s]
  if g(tuple(c)):return p[n[0]]+' <- '+p[s]+','+g(tuple(c))
 return' 'if len(p)<2else[]
print(g(tuple(input().split(',')))[:-2]or'')

Even this one is astronomically slow with certain inputs.
The code uses strings, not numbers, so it also supports notation like KH instead of 13H.
Example:
$ python accordion.py
5H,9C,11H,7S,7D,12D,6H,10S,3H,4D,12C,2S,3C,5C,7H,6S,1H,8S,2H,11S,4C,10D,12H,9H,2D,4H,6C,13H,11C,2C,10H,8C,1S,11D,3S,12S,7C,5D,13S,8D,4S,6D,13C,3D,8H,13D,1D,9D,9S,1C,5S,10C
7S <- 7D,7D <- 12D,3C <- 5C,12H <- 9H,11C <- 2C,3S <- 12S,13D <- 1D,1D <- 9D,9D <- 9S,2S <- 6S,7H <- 1H,6S <- 8S,1H <- 2H,8S <- 11S,2H <- 9H,10D <- 2D,9H <- 4H,4H <- 4C,5C <- 4C,4D <- 4C,4C <- 12C,10S <- 11S,11H <- 11S,6H <- 3H,12D <- 2D,12C <- 2C,2C <- 6C,6C <- 8C,12S <- 13S,5D <- 6D,6D <- 8D,8D <- 3D,4S <- 9S,13S <- 9S,11D <- 3D,7C <- 1C,1S <- 1C,1C <- 13C,8C <- 13C,13C <- 13H,13H <- 10H,2D <- 3D,3D <- 3H,3H <- 8H,8H <- 10H,11S <- 5S,5H <- 10H,5S <- 9S,10H <- 10C,10C <- 9C,9C <- 9S


7 5 vertices, 14 10 edges

(Graph made with this online tool and paint.)

A-F are our six nodes, and J is a helper node. The three 1-nodes enforce that opposite nodes are different, while the 2-node makes sure that A, C and E can neither be all mines, nor all empty.

Edit: -2 vertices thanks to  CalculatorFeline and H.PWiz!


Python 2, 93 bytes
There is a trailing linefeed.

p=1+2*bool(input())-1;s='print"p=%r+2*bool(input())-1;s=%r*(p>0);exec s"%(p,s)'*(p>0);exec s

Try it with input | Try it without input
This is modified from my answer on a similar question.
If there is input, then it will increment p. So the resulting program will be p=2+..., p=3+..., etc.


Several bases but not twice the same digit

JavaScript (Node.js),192,155,154,152,151,145,136,113,99,92 90 bytes

thanks to @Arnauld for reminding me that i can return [0,1,2,3] -> which is [2,8,10,16] saves 8 bytes, and for the brilliant idea (which help to reduce by 23+ bytes)
thanks to @Kevin Cruijssen for reducing by 1 bytes

f=([c,...a],t="")=>c?[1,4,5,8].find(b=>T=!/(.).*\1/.test(n=t+c.toString(b*2))&&f(a,n))+T:a

Try it online!
Explanation:
[c,...a] - @Arnauld trick for taking one item at a time
c?***:" " ->if c is undefined we managed to get to the end result- [] - if i would put "" than the find would not considered that legit. ([]+5="5" JS FTW)
[1,4,5,8].find every time we find the correct base (the output will be of this array (1,4,5,8)->(2,8,10,16) its legit.
now how the find works -> if it finds something it returns the element (1-8)
and than i add the result of the inner solution. if it doesnt find then it returns undefined + T is now false -> NaN which in the parent call will be considered false
!/(.).*\1/.test(n=t+b) determine if the string has duplicates, if so:
f(a,n)) just go the the next number(a is now array.slice(1)) with the new string(n)
we assign result to T(temp) of the result because find stops when it finds and so we know that the last result will be f() which is result B


Dancing arrays. Output them with some forward-backward moves

Python 2, 135 128 126 bytes

Pretty naive solution:

a,f,b=input()
b+=1
l=len(a)
i=0
e=min(l,f)
while f>b:
    print'\n'.join(map(str,a)[i:e])+'\n';i=e-b
    if e==l:f=b
    e=min(l,e+f-b)

Try it online!

Input format is [array], F, B except you can also use (). (You can't use {} because that's unordered; thanks to Felipe Batista for pointing that out because I forgot).
Output format is as specified in the challenge, with a single trailing newline at the end of all output and no leading whitespace.

-7 bytes by changing if f>b: while 1: to while f>b
-2 bytes by changing break to f=b because that causes the while loop to exit.


Monday Mini-Golf #7: Simplify ingredient measurements

Mathematica, 349 334 330 322 bytes

This answer section felt a little lonely. So uh, here's my attempt. Input should be given as in the test cases.

n=ToExpression@StringSplit@InputString[];i=#~Mod~1&;b=#&@@n;If[Length@n==3,{x,y,z}=n,{x,y,z}=If[IntegerQ@b,{b,0,Last@n},{0,b,Last@n}]];v={0,1/4,1/3,1/2,2/3,3/4};s=<|T->16,t->3,o->16,q->4,p->2,f->16|>;r=<|T->c,t->T,o->l,f->p,p->q,q->g|>;If[v~MemberQ~i[a=(x+y)/s@z],{x,y,z}={Floor@a,i@a,r@z}]~Do~3;Print@Row[{x,y,z}/. 0->""]

Explanation

First get the user input, split that input on whitespace, and assign that to n. i=#~Mod~1& creates a function that gets the fractional part of a number, by taking it mod 1. b=#&@@n will simply get the first item in n; that would be everything up to the first space.

If n is 3 elements long, that means we have an integer, a fraction, and a unit. {x,y,z}=n will assign x, y and z to be the three parts of n.
The other case is that n is not 3 elements long; that means it’ll be 2 elements long instead. To stay consistent with above, we want x to be the integer part, y to be the fraction, and z the unit. So in this case, we need to check:

If b (the first element of n) is an integer, then x=b, y=0 and z=Last@n (the last element of n).
If b isn’t an integer, that means we only have a fraction with no integer. So we want to swap x and y from above; instead, x=0, y=b, and z is the same as above.

Now we need to set up some lists:

v = {0, 1/4, 1/3, 1/2, 2/3, 3/4} is the list of acceptable fractions, as stated in the question.

s = <|T -> 16, t -> 3, o -> 16, q -> 4, p -> 2, f -> 16|> is an association (key-value pair, like a dictionary in Python) that represents the amount needed of a given unit to go “up” to one of the next largest unit. For example, o -> 16 is because 16 ounces are required before we go up to 1 pound.

r = <|T -> c, t -> T, o -> l, f -> p, p -> q, q -> g|> is the association that actually represents what the next unit up is. For example, T -> c means one unit larger than Tablespoons is cups.

If[v~MemberQ~i[a = (x + y)/s@z], {x, y, z} = {Floor@a, i@a, r@z}]~Do~3

Now, the maximum number of times we need to go up a unit is 3; that would be fluid ounces (f) -> pints (p) -> quarts (q) -> gallon (g). So, now we do the following 3 times:

Add x and y, (the integer and fractional parts)
From the s association above, get element z; that is, access the current unit, and get the corresponding value in that association.
Divide (x+y) by that value we got above, assign it to a, then get its fractional part.
If that part is in the list v, then we can go up one unit; set x to a rounded down (integer part), set y to the fractional part of a, then access the association r with the current unit z to get the next unit up, and set that to z.
If it’s not part of v instead, we don’t do anything, since it can’t be simplified.

Once that’s done 3 times, we print out the result:

Print@Row[{x,y,z}/. 0->””]

This simply prints out {x,y,z} in a row, but replaces any zeroes (if there’s no integer, or no fraction), with an empty string, so those don’t print out.


Retina, 167 165 157 150 123 bytes

This totally looks like a challenge that should be solved with a single regex... (despite the header saying "Retina", this is just a vanilla .NET regex, matching valid inputs).

^(?=\D*((?=(?<3>1+))1)+)((?=A(?<1-3>.+)|B(?<1-4>.+)|C(?<1-5>.+)).(?=A.*(?!\3)(\1)|B.*(?!\4)(\1)|C.*(?!\5)(\1)).)+(?!\3|\4)1

Input format is the list of instructions of the form AB, followed by n in unary using the digit 1. There are no separators. Output is 1 for valid and 0 for invalid.

Try it online! (The first two characters enable a linefeed-separated test suite.)

Alternative solution, same byte count:

^(?=\D*((?=(?<3>1+))1)+)((?=A(?<1-3>.+)|B(?<1-4>.+)|C(?<1-5>.+)).(?=A.*(?!\3)(\1)|B.*(?!\4)(\1)|C.*(?!\5)(\1)).)+(?<-5>1)+$

This can possibly be shortened by using 1, 11 and 111 instead of A, B and C but I'll have to look into that later. It might also be shorter to split the program into several stages, but where's the challenge in that? ;)

Explanation

This solution makes heavy use of .NET's balancing groups. For a full explanation see my post on Stack Overflow, but the gist is that capturing groups in .NET are stacks, where each new capture pushes another substring and where it's also possible to pop from such a stack again. This lets you count various quantities in a string. In this case it lets us implement the three rods directly as three different capturing groups where each disc is represented by a capture.

To move discs around between rods we make use of a weird quirk of the (?<A-B>...) syntax. Normally, this pops a capture from stack B and pushes onto stack A the string between that popped capture and the beginning of this group. So (?<A>a).(?<B-A>c) matched against abc would leave A empty and B with b (as opposed to c). However, due to .NET variable-length lookbehinds it's possible for the captures of (?<A>...) and (?<B-A>...) to overlap. For whatever reason, if that's the case, the intersection of the two groups is pushed onto B. I've detailed this behaviour in the "advanced section" on balancing groups in this answer.

On to the regex. Rods A, B and C correspond to groups 3, 4 and 5 in the regex. Let's start by initialising rod A:

^                 # Ensure that we start at the beginning of the input.
(?=               # Lookahead so that we don't actually move the cursor.
  \D*             # Skip all the instructions by matching non-digit characters.
  (               # For each 1 at the end of the input...
    (?=(?<3>1+))  # ...push the remainder of the string (including that 1)
                  # onto stack 3.
  1)+
)

So e.g. if the input ends with 111, then group 3/rod A will now hold the list of captures [111, 11, 1] (the top being on the right).

The next bit of the code has the following structure:

(
  (?=A...|B...|C...).
  (?=A...|B...|C...).
)+

Each iteration of this loop processes one instruction. The first alternation pulls a disc from the given rod (onto a temporary group), the second alternation puts that that disc onto the other given rod. We'll see in a moment how this works and how we ensure that the move is valid.

First, taking a disc off the source rod:

(?=
  A(?<1-3>.+)
|
  B(?<1-4>.+)
|
  C(?<1-5>.+)
)

This uses the weird group-intersection behaviour I've described above. Note that group 3, 4 and 5 will always hold substrings of 1s at the end of the string whose length corresponds to the disc's size. We now use (?<1-N>.+) to pop the top disc off stack N and push the intersection of this substring with the match .+ onto stack 1. Since .+ always necessarily covers the entire capture popped off N, we know that this simply moves the capture.

Next, we put this disc from stack 1 onto the stack corresponding to the second rod:

(?=
  A.*(?!\3)(\1)
|
  B.*(?!\4)(\1)
|
  C.*(?!\5)(\1)
)

Note that we don't have to clean up stack 1, we can just leave the disc there, since we'll put a new one on top before using the stack again. That means we can avoid the (?<A-B>...) syntax and simply copy the string over with (\1). To ensure that the move is valid we use the negative lookahead (?!\N). This ensures that, from the position where we want to match the current disc, it's impossible to match the disc already on stack N. This can only happen if either a) \N will never match because the stack is completely empty or b)the disc on top of stackNis larger than the one we're trying to match with\1`.

Finally, all that's left is ensuring that a) we've matched all instructions and b) rods A and B are empty, so that all discs have been moved onto C.

(?!\3|\4)1

We simply check that neither \3 nor \4 can match (which is only the case if both are empty, because any actual disc would match) and that we can then match a 1 so that we haven't omitted any instructions.


One assignment, 2075 (optimal)

This should be the optimal value (unless I have a big error in reasoning or my testing sucks).

First of all. There are only 7 different numbers (mod 128) you can express in 99. All values of 7 or more 9 evaluate to the same number 71. (Because 10^8 mod 128 == 0, 10^9 mod 128 == 0, ...)

If one of the 4 values you can express with an even number of nines, than outputting this number is clearly the optimal solution.

Otherwise I try to reach the number with one assignment statement (assign to 99) and print 99. As it turns out the maximal program size with this approach is 22 char. Clearly using Goto takes definitely more than that. The only possibility that a one-assignment solution might be beaten is a solution with two assignments. I tested this (hopefully with no errors, the code for this is quite messy), and found no solution for any ASCII char.

Therefore only checking the 4 direct numbers and the one-assignment approach should be enough to find the optimal solution. The following Python (2 and 3 compatible) program generates all programs and sums up their lengths. It uses a simple IDA* approach.

from itertools import count

def nines_to_dec(nines):
    return ((10**nines - 1) // 9) % 128

def shortest_representation(ascii_value):
    # try simple output,
    # max code length is 8, (8 nines == 10 nines == 12 nines == ...)
    # if this works, than this is the shortest representation

    for nines in range(2, 9, 2):
        if nines_to_dec(nines) == ascii_value:
            return "9" * nines

    # otherwise try one assignment
    for length in count(1):
        result = assignment(ascii_value, length, [])
        if result:
            return "99 " + result + "\n99"

def assignment(value, left, nines_list):
    if left == 0:
        eval_numbers = [nines_to_dec(nines) for nines in nines_list]

        if (sum(eval_numbers[::2]) - sum(eval_numbers[1::2])) % 128 == value:
            return " ".join("9" * nines for nines in nines_list)
        else:
            return False

    for nines in range(1, 8):
        left2 = left - nines - 1 # -1 for space
        if left2 >= 0:
            result = assignment(value, left2, nines_list + [nines])
            if result:
                return result

    return False

lengths = []
for i in range(128):
    program =shortest_representation(i)
    lengths.append(len(program))
    print("ASCII-value: {}, ASCII-char: {}".format(i, chr(i)))
    print(program)

print(sorted(lengths))
print(sum(lengths))

The output is of the following form:

....
ASCII-value: 65, ASCII-char: A
99 9 999999 9999999
99
ASCII-value: 66, ASCII-char: B
99 9 99 9999 99
99
ASCII-value: 67, ASCII-char: C
99 9 99 9 99 9999
99
....

You can find the complete output at: http://pastebin.com/bKXLAArq

The char with the shortest program (2 char) is vertical tab - 11 with a program length of 2, the chars with the longest programs (22 char) are bell - 7 and A - 65.

The sum for all programs is 2075.

And by the way, I used the k/q interpreter from tmartin. I hat quite some troubles with the other ones (Python, Perl, CJam). Not sure if it was my fault.


Python 2, 20 bytes

print";print'print'"

-7 bytes thanks to tsh
Try it online!

Old answer:
Python 2, 27 bytes

'';print";print 2*"'';print

Try it online!
Train of thought behind this answer:
Begin with a simple print, because we need to print something.
print"a"

We also need to print something in the inverted case, ie. have a print inside quotes.
print"print"

The non-inverted case is pretty good at this point. Let's focus on the inverted case. We now start with the string print, which can't be followed immediately by a print statement. Let's fix this with a semicolon.
print";print"

Good stuff. Except, the inverted code doesn't actually print anything. We'll need to print the print at the start, because it ends up in quotes, but also print whatever comes after the second quote, because it ends up in quotes too. The obvious way around this is to append print and multiply the last string by 2.
print";print 2*"print

Now the inverted code works fine, though we have to be wary of the fact that the section before the first quote and the section after the second quote need to be kept the same throughout future changes. As for the non-inverted code, it throws a syntax error - once again, we need to introduce a semicolon to separate expressions.
;print";print 2*";print

Python doesn't really like the look of that lone semicolon, so we must satisfy the snake's hunger with two of the same no-op expression, inserted before the first semicolon and the last semicolon. Most expressions will work fine in the first case, but in the second case it must follow print";print 2*" in the non-inverted code without breaking anything. We can use '', which simply gets concatenated with the prior string.
'';print";print 2*"'';print


Python 3, 67 tokens

import sys
import time

class Bunny():
    def __init__(self):
        self.direction = [0, 1]
        self.coords = [-1, -1]

    def setCoords(self, x, y):
        self.coords = [x, y]

    def rotate(self, dir):
        directions = [[1, 0], [0, 1], [-1, 0], [0, -1]]
        if dir == 'L':
            self.direction = directions[(directions.index(self.direction) + 1) % 4]
        if dir == 'R':
            self.direction = directions[(directions.index(self.direction) - 1) % 4]

    def hop(self):
        self.coords = self.nextTile()

    # Returns where the bunny is about to jump to
    def nextTile(self):
        return [self.coords[0] + self.direction[0], self.coords[1] + self.direction[1]]

class BoardState():
    def __init__(self, map):
        self.unvisited = 0
        self.map = []

        self.bunny = Bunny()
        self.hopsLeft = 0

        for x, row in enumerate(map):
            newRow = []
            for y, char in enumerate(row):
                if char == '#':
                    newRow.append(1)
                    self.unvisited += 1

                elif char == 'S':
                    newRow.append(2)

                    if -1 in self.bunny.coords:
                        self.bunny.setCoords(x, y)
                    else:
                        print("Multiple starting points found", file=sys.stderr)
                        sys.exit(1)

                elif char == ' ':
                    newRow.append(0)

                elif char == 'O':
                    newRow.append(2)

                else:
                    print("Invalid char in input", file=sys.stderr)
                    sys.exit(1)

            self.map.append(newRow)

        if -1 in self.bunny.coords:
            print("No starting point defined", file=sys.stderr)
            sys.exit(1)

    def finished(self):
        return self.unvisited == 0

    def validCoords(self, x, y):
        return -1 < x < len(self.map) and -1 < y < len(self.map[0])

    def runCom(self, com):
        if self.finished():
            return

        if self.hopsLeft < self.unvisited:
            return

        if com == 'F':
            x, y = self.bunny.nextTile()
            if self.validCoords(x, y) and self.map[x][y] != 0:
                self.bunny.hop()
                self.hopsLeft -= 1

                if (self.map[x][y] == 1):
                    self.unvisited -= 1
                self.map[x][y] = 2

        else:
            self.bunny.rotate(com)

class loop():
    def __init__(self, loops, commands):
        self.loops = loops
        self.commands = [*commands]

    def __str__(self):
        return "loop({}, {})".format(self.loops, list(self.commands))

    def __repr__(self):
        return str(self)

def rejectRedundantCode(code):
    if isSnippetRedundant(code):
        return False

    if type(code[-1]) is str:
        if code[-1] in "LR":
            return False
    else:
        if len(code[-1].commands) == 1:
            print(code)
            if code[-1].commands[-1] in "LR":
                return False

    return True

def isSnippetRedundant(code):
    joined = "".join(str(com) for com in code)

    if any(redCode in joined for redCode in ["FFF", "RL", "LR", "RRR", "LLL"]):
        return True

    for com in code:
        if type(com) is not str:
            if len(com.commands) == 1:
                if com.loops == 2:
                    return True

                if type(com.commands[0]) is not str:
                    return True

                if com.commands[0] in "LR":
                    return True

            if len(com.commands) > 1 and len(set(com.commands)) == 1:
                return True

            if isSnippetRedundant(com.commands):
                return True

    for i in range(len(code)):
        if type(code[i]) is not str and len(code[i].commands) == 1:
            if i > 0 and code[i].commands[0] == code[i-1]:
                return True
            if i < len(code) - 1 and code[i].commands[0] == code[i+1]:
                return True

        if type(code[i]) is not str:
            if i > 0 and type(code[i-1]) is not str and code[i].commands == code[i-1].commands:
                return True
            if i < len(code) - 1 and type(code[i+1]) is not str and code[i].commands == code[i+1].commands:
                return True

            if len(code[i].commands) > 3 and all(type(com) is str for com in code[i].commands):
                return True

    return False

def flatten(code):
    flat = ""
    for com in code:
        if type(com) is str:
            flat += com
        else:
            flat += flatten(com.commands) * com.loops

    return flat

def newGen(n, topLevel = True):
    maxLoops = 9
    minLoops = 2
    if n < 1:
        yield []

    if n == 1:
        yield from [["F"], ["L"], ["R"]]

    elif n == 2:
        yield from [["F", "F"], ["F", "L"], ["F", "R"], ["L", "F"], ["R", "F"]]

    elif n == 3:
        for innerCode in newGen(n - 1, False):
            for loops in range(minLoops, maxLoops):
                if len(innerCode) != 1 and 0 < innerCode.count('F') < 2:
                    yield [loop(loops, innerCode)]

        for com in "FLR":
            for suffix in newGen(n - 2, False):
                for loops in range(minLoops, maxLoops):
                    if com not in suffix:
                        yield [loop(loops, [com])] + suffix

    else:
        for innerCode in newGen(n - 1, False):
            if topLevel:
                yield [loop(17, innerCode)]
            else:
                for loops in range(minLoops, maxLoops):
                    if len(innerCode) > 1:
                        yield [loop(loops, innerCode)]

        for com in "FLR":
            for innerCode in newGen(n - 2, False):
                for loops in range(minLoops, maxLoops):
                    yield [loop(loops, innerCode)] + [com]
                    yield [com] + [loop(loops, innerCode)]

def codeLen(code):
    l = 0
    for com in code:
        l += 1
        if type(com) is not str:
            l += codeLen(com.commands)

    return l

def test(code, board):
    state = BoardState(board)
    state.hopsLeft = flatten(code).count('F')

    for com in code:
        state.runCom(com)

    return state.finished()

def testAll():
    score = 0
    for i, board in enumerate(boards):
        print("\n\nTesting board {}:".format(i + 1))
        #print('\n'.join(board),'\n')
        start = time.time()

        found = False
        tested = set()

        for maxLen in range(1, 12):
            lenCount = 0
            for code in filter(rejectRedundantCode, newGen(maxLen)):
                testCode = flatten(code)
                if testCode in tested:
                    continue

                tested.add(testCode)

                lenCount += 1
                if test(testCode, board):
                    found = True

                    stop = time.time()
                    print("{} token solution found in {} seconds".format(maxLen, stop - start))
                    print(code)
                    score += maxLen
                    break

            if found:
                break

    print("Final Score: {}".format(score))

def testOne(board):
    start = time.time()
    found = False
    tested = set()
    dupes = 0

    for maxLen in range(1, 12):
        lenCount = 0
        for code in filter(rejectRedundantCode, newGen(maxLen)):
            testCode = flatten(code)
            if testCode in tested:
                dupes += 1
                continue

            tested.add(testCode)

            lenCount += 1
            if test(testCode, board):
                found = True
                print(code)
                print("{} dupes found".format(dupes))
                break

        if found:
            break

        print("Length:\t{}\t\tCombinations:\t{}".format(maxLen, lenCount))

    stop = time.time()
    print(stop - start)

#testAll()
testOne(input().split('\n'))

This program will test a single input board, but I find this test driver more useful. It will test every single board at the same time and print how long it took to find that solution. When I run that code on my machine (Intel i7-7700K quad core CPU @ 4.20 GHz, 16.0 GB RAM), I get the following output:

Testing board 1:
2 token solution found in 0.0 seconds
['F', 'F']

Testing board 2:
4 token solution found in 0.0025103092193603516 seconds
[loop(17, [loop(3, ['F']), 'R'])]

Testing board 3:
4 token solution found in 0.0010025501251220703 seconds
[loop(17, [loop(3, ['F']), 'L'])]

Testing board 4:
5 token solution found in 0.012532949447631836 seconds
[loop(17, ['F', loop(7, ['F', 'L'])])]

Testing board 5:
5 token solution found in 0.011022329330444336 seconds
[loop(17, ['F', loop(5, ['F', 'L'])])]

Testing board 6:
4 token solution found in 0.0015044212341308594 seconds
[loop(17, [loop(3, ['F']), 'L'])]

Testing board 7:
8 token solution found in 29.32585096359253 seconds
[loop(17, [loop(4, [loop(5, [loop(6, ['F']), 'L']), 'L']), 'F'])]

Testing board 8:
8 token solution found in 17.202533721923828 seconds
[loop(17, ['F', loop(7, [loop(5, [loop(4, ['F']), 'L']), 'F'])])]

Testing board 9:
6 token solution found in 0.10585856437683105 seconds
[loop(17, [loop(7, [loop(4, ['F']), 'L']), 'F'])]

Testing board 10:
6 token solution found in 0.12129759788513184 seconds
[loop(17, [loop(7, [loop(5, ['F']), 'L']), 'F'])]

Testing board 11:
7 token solution found in 4.331984758377075 seconds
[loop(17, [loop(8, ['F', loop(5, ['F', 'L'])]), 'L'])]

Testing board 12:
8 token solution found in 58.620323181152344 seconds
[loop(17, [loop(3, ['F', loop(4, [loop(3, ['F']), 'R'])]), 'L'])]

Final Score: 67

This last test just barely squeaks in under the minute restriction.

Background

This was one of the most fun challenges I've ever answered! I had a blast pattern hunting and looking for heuristics to cut down on things.

Generally, here on PPCG I tend to answer relatively easy questions. I'm especially fond of the string tag because it's generally pretty well suited for my languages. One day, about two weeks ago, I was looking through my badges and I realized that I had never gotten the revival badge. So I looked through the unanswered tab to see if anything caught my eye, and I found this question. I decided that I would answer it no matter the cost. It ended up being a bit harder than I thought it would, but I finally got a brute-force answer that I can say I'm proud of. But this challenge is totally out of the norm for me since I don't usually spend more than an hour or so on a single answer. This answer took me a little over 2 weeks and at least 10+ of work to finally get to this stage, though I wasn't keeping careful track.

The first iteration was a pure brute force solution. I used the following code to generate all snippets up to length N:

def generateCodeLenN(n, maxLoopComs, maxLoops, allowRedundant = False):
    if n < 1:
        return []

    if n == 1:
        return [["F"], ["L"], ["R"]]

    results = []

    if 1:
        for com in "FLR":
            for suffix in generateCodeLenN(n - 1, maxLoopComs, maxLoops, allowRedundant):
                if allowRedundant or not isSnippetRedundant([com] + suffix):
                    results.append([com] + suffix)

    for loopCount in range(2, maxLoopComs):
        for loopComs in range(1, n):
            for innerCode in generateCodeLenN(loopComs, maxLoopComs, maxLoops - 1, allowRedundant):
                if not allowRedundant and isSnippetRedundant([loop(loopCount, innerCode)]):
                    continue

                for suffix in generateCodeLenN(n - loopComs - 1, maxLoopComs, maxLoops - 1, allowRedundant):
                    if not allowRedundant and isSnippetRedundant([loop(loopCount, innerCode)] + suffix):
                        continue

                    results.append([loop(loopCount, innerCode)] + suffix)

                if loopComs == n - 1:
                    results.append([loop(loopCount, innerCode)])

    return results

At this point, I was sure that testing every single possible answer would be way too slow, so I used isSnippetRedundant to filter out snippets that could be written with a shorter snippet. For example, I would refuse to yield the snippet ["F", "F", "F"] because the exact same effects could be achieved with [Loop(3, ["F"]), so if it we get to the point where we test length-3 snippets, we know that no length-3 snippet could solve the current board. This used a lot of good mnemonics, but ultimately was waaaay too slow. Testcase 12 took just over 3,000 seconds using this approach. This is clearly significantly too slow. But using this information and a bunch of computer cycles to brute force short solutions to every board, I could find a new pattern. I noticed that almost every solution found would generally look like something like the following:

[<com> loop(n, []) <com>]

nested several layers deep, with the single coms on each side being optional. This means that solutions like:

["F", "F", "R", "F", "F", "L", "R", "F", "L"]

would never appear. In fact, there was never a sequence of more than 3 non-loop tokens. One way to utilize this would be to filter out all of these and not bother to test them. But generating them was still taking a non-negligible amount of time, and filtering through the millions of snippets like this would barely cut time off. Instead I drastically rewrote the code-generator to only generate snippets following this pattern. In pseudo code, the new generator follows this general pattern:

def codeGen(n):
    if n == 1:
        yield each [<com>]

    if n == 2:
        yield each [<com>, <com>]

    if n == 3:
        yield each [loop(n, <com length 2>]
        yield each [loop(n, <com>), <com>]

    else:
        yield each [loop(n, <com length n-1>)]
        yield each [loop(n, <com length n-2>), <com>]
        yield each [<com>, loop(n, <com length n-2>)]

        # Removed later
        # yield each [<com>, loop(n, <com length n-3>), <com>]
        # yield each [<com>, <com>, loop(n, <com length n-3>)]
        # yield each [loop(n, <com length n-3>), <com>, <com>]

This cut the longest test case down to 140 seconds, which is a ridiculous improvement. But from here, there were still some things I needed to improve. I started more aggressively filtering out redundant/worthless code and checking to see if code has been tested before. This cut it down further, but it wasn't enough. In the end, the final piece that was missing was the loop counter. Through my highly advanced algorithm (read: random trial and error) I determined that the optimal range to allow loops to run in is [3-8]. But there's a huge improvement in there: If we know that [loop(8, [loop(8, ['F', loop(5, ['F', 'L'])]), 'L'])] can't solve our board, then there's absolutely no way that [loop(3, [loop(8, ['F', loop(5, ['F', 'L'])]), 'L'])] or any loop count from 3-7 could solve it. So rather than iterating through all the loop sizes from 3-8, we set the loop count on the outer loop to the max. This ends up cutting the search space down by a factor of maxLoop - minLoop, or 6 in this case.

This helped a lot, but ended up inflating the score. Certain solutions I had found earlier by brute force require larger loop numbers to run (for example, boards 4 and 6). So rather than setting the outer loop count to 8, we set the outer loop count to 17, a magical number also calculated by my highly advanced algorithm. We know we can do this because increasing the loop count of the outermost loop has no effect on the solution's validity. This step actually reduced our final score by 13. So not a trivial step.


Jelly, 8 bytes

_ƝṠÞ+SƊƑ

Try it online!

How it works

_ƝṠÞ+SƊƑ  Main link. Argument: n (integer)

_Ɲ        Take the differences of neighboring digits.
          This maps n = abcd to [a-b, b-c, c-d].
       Ƒ  Fixed; apply the link to the left and return 1 if the result is equal to
          its argument, 0 if not.
      Ɗ       Drei; combine the three links to the left into a monadic chain.
  ṠÞ              Sort the differences by their signs (negative, zero, positive).
     S            Take the sum of the differences, yielding 0 if and only if the
                  first digit is equal to the last.
    +             Add the sum to each difference.


CJam, 27 26 bytes

80qf{i2b7Te[4/~\)\@+++2bc}

Try it online!

Explanation

The Braille code points are neatly ordered so that the individual dots do count up in binary. However, the ordering of the bits in the code points is different. We want the following order:

04
15
26
37

Whereas the characters are laid out in Unicode in this order:

03
14
25
67

(Which kinda makes sense, because historically, Braille only used the first six dots.) Note that we don't need the 7 dot, since the input is guaranteed to be in the ASCII range. So given a list of bits [6 5 4 3 2 1 0] of an input character, we want to reorder them into [3 6 5 4 2 1 0], to pull the bit representing the bottom-left dot to the most significant position.

80     e# Push 80... we'll need this later.
q      e# Read all input.
f{     e# Map this block onto each character, putting a copy of the 80
       e# below each character.
  i    e#   Convert the character to its code point.
  2b   e#   Get its binary representation.
  7Te[ e#   Pad it to 7 bits with zeros. We've now got some bit list
       e#   [6 5 4 3 2 1 0].
  4/   e#   Split into chunks of 4: [[6 5 4 3] [2 1 0]]
  ~    e#   Dump them onto the stack: [6 5 4 3] [2 1 0]
  \    e#   Swap them: [2 1 0] [6 5 4 3]
  )    e#   Pull off the last element: [2 1 0] [6 5 4] 3
  \    e#   Swap: [2 1 0] 3 [6 5 4]
  @    e#   Rotate: 3 [6 5 4] [2 1 0]
  ++   e#   Concatenate twice: [3 6 5 4 2 1 0]
       e#   That's the reordering done.
  +    e#   Prepend the 80. That puts it in the 2^7 position of the
       e#   binary digit list, which gives it a value of 10240, which
       e#   is where the Braille characters start.
  2b   e#   Convert the bits back to an integer.
  c    e#   Convert the code point to the corresponding integer.
}%


Python+Graphviz

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import networkx as nx
import os

"""Tool to generate collatz sequence graphs."""

def collatz_one(x):
    """Make a single step in the collatz sequence."""
    if x % 2 == 0:
        x = x/2
    else:
        x = 3*x + 1
    return x

def main(max_collatz=20):
    """Create the collatz graph. """
    G = nx.DiGraph()
    seen = [1]
    G.add_node("1")
    edges = []

    for i in range(1, max_collatz):
        while i != 1:
            if i not in seen:
                seen.append(i)
                G.add_node(str(i))
                j = collatz_one(i)
                edges.append((str(i), str(j)))
                i = j
            else:
                i = 1

    for i, j in edges:
        G.add_edge(i, j)
    nx.write_dot(G, 'test.dot')
    os.system("dot -Tpng test.dot -o test.png")

if __name__ == '__main__':
    from argparse import ArgumentParser
    parser = ArgumentParser(description=__doc__)
    parser.add_argument("-m", dest="m",
                        help=("The first 1..m elements are guaranteed "
                              "to be included"),
                        default=20,
                        type=int)

    args = parser.parse_args()
    main(args.m)

Image

Created with dot and m=20:


Calculate the p-adic norm of a rational number

Julia, 94 80 75 bytes

f(m,n,p)=(k=gcd(m,n)
g(m)=m%p>0?g(m÷p)p:1
m!=0?print(g(n÷k),/,g(m÷k)):0)

Note: using linefeeds in place of semicolons for readability - will work same either way.

This is quite simple - the g(m,n) function uses recursion and remainder (%) to extract the p^n factor from input m, with n=1 as default and then multiplied by p on each step of the recursion, so that the output will be p^n. The code applies that to n/gcd(m,n), and then to m/gcd(m,n) to obtain the appropriate expression. k=gcd(m,n) is used to avoid calculating the gcd(m,n) twice, to save characters. m!=0 is a test to handle the case where x=0.

The output is of the form N/1 or 1/N as appropriate, where N is p^e.


Mathematica 134 Bytes

Max@ComponentMeasurements[ArrayComponents[ImageData@ColorQuantize[RemoveAlphaChannel[#,White],4,Dithering->False],2],"Holes"][[All,2]]&

Usage (applied to .png images)

%/@cookies

Output:

{8,8,10,7}

Here's the code to bring in the cookie examples:

cookieURLs={"https://i.stack.imgur.com/UCV1A.png","https://i.stack.imgur.com/5n7AY.png","https://i.stack.imgur.com/ZbZx6.png","https://i.stack.imgur.com/M8jTo.png"};
cookies=Import/@cookieURLs;

I'm sure this can be shortened, but I think it's fairly bullet-proof as is. The original images have many more colors than the eye can see.

Here are the original cookies:

Here are the cookies after cleanup to get them into a 4 component array:

ArrayPlot[ArrayComponents[ImageData@ColorQuantize[RemoveAlphaChannel[#,White],4,Dithering->False],2]]&/@cookies//Row

After that, all is needed is to use ComponentMeasurements to count holes.
This will always report at least 1.  You could have one really big chocolate chip filling the cookie border, so the 0 or 1 case will always be ambiguous.


JavaScript, 232 bytes

function c(d){for(var l,o,f,c,p=/^.(\d+).+?$/gm,a=/(T\s+)?C.{7}M .(\d+)/g,r='';l=p.exec(d);)for(f=0;o=a.exec(d);)o[2]==l[1]&&(c=d.slice(0,o.index).split('\n').length,r+=f++?', ':'\n'+l[0]+' -> ',r+=o[1]?'['+c+']':c);return r.trim()}

To be called with

var data = require( 'fs' ).readFileSync( process.argv[2] ).toString();
console.log( c( data ) );

Explanation

function c(d){
    for(
        // Initialise variables
        var l,o,f,c,p=/^.(\d+).+?$/gm,a=/(T\s+)?C.{7}M .(\d+)/g,r='';
        // Find lines beginning with a label
        l=p.exec(d);)
            for(
                // Reset a have-we-output-this-line flag
                f=0;
                // Find CALL FROM statements
                o=a.exec(d);)
                    // Filter to CALL FROM statements which have the current line
                    o[2]==l[1]&&(
                        // Calculate the line number of this CALL FROM statement
                        c=d.slice(0,o.index).split('\n').length,
                        // Concat the output for this line
                        r+=f++?', ':'\n'+l[0]+' -> ',r+=o[1]?'['+c+']':c);
    // Trim an initial new line
    return r.trim()}


Brachylog (v2), 9 bytes

;.≜^dl10∧

Try it online!

This is a function submission. The TIO link contains a wrapper that makes a function into a full program.

Explanation

;.≜^dl10∧
 .≜        Brute-force all integers, outputting the closest to 0
;  ^         for which {the input} to the power of the number
    d        has a list of unique digits
     l10     of length 10
        ∧  (turn off an unwanted implicit constraint)


Ruby 664 671 677 687 701 (678 bytes)

_={│:[1,4],─:[2,8],┌:[4,8],┐:[4,2],└:[1,8],┘:[1,2],┼:[1,4,2,8]}
s=->a,l,b{l==[]&&a==[]?b:(l.product(l).any?{|q,r|q,r=q[0],r[0];(q[0]-r[0])**2+(q[1]-r[1])**2>a.size**2}?!0:(w,f=l.pop
w&&v=!a.size.times{|i|y=_[x=a[i]]
f&&y&[f]==[]||(k=l.select{|p,d|w!=p||y&[d]==[]}
(y-[f]).map{|d|z=[w[0]+(d<2?-1:(d&4)/4),w[1]+(d==2?-1:d>7?1:0)]
g=d<3?d*4:d/4
b[z]?_[b[z]]&[g]!=[]||v=0:k<<[z,g]}
v||r=s[a[0...i]+a[i+1..-1],k,b.merge({w=>x})]
return r if r)}))}
c=eval"[#{gets}]"
r=s[6.downto(0).map{|i|[_.keys[i]]*c[i]}.flatten,[[[0,0],nil]],{}]
h=j=k=l=0
r.map{|w,_|y,x=w
h>x&&h=x
j>y&&j=y
k<x&&k=x
l<y&&l=y}
s=(j..l).map{|_|' '*(k-h+1)}
r.map{|w,p|y,x=w
s[y-j][x-h]=p.to_s}
puts s

This is not the shortest program I could come up with, but I sacrificed some brevity for execution speed.

You can experiment with the program here. Note that ideone has an execution time limit, so for inputs consisting of more than about 12 pieces, the program will probably time out.

There's also a test suite for the program. Note that the last two tests are disabled on ideone, due to the time limit mentioned above. To enable these tests, delete the x_ prefix from their names.

The program finds a solution using Depth-first search; it places pieces one at a time and keeps tracks of loose ends. The search stops when there are no more loose (unconnected) ends and all pieces have been placed.

This is the ungolfed program:

N, W, S, E = 1, 2, 4, 8

# given a direction, find the opposite
def opposite (dir)
  dir < 3 ? dir * 4 : dir / 4
end

# given a set of coordinates and a direction,
# find the neighbor cell in that direction
def goto(from, dir)
  y, x = from

  dx = case dir
  when W then -1
  when E then 1
  else 0
  end

  dy = case dir
  when N then -1
  when S then 1
  else 0
  end

  [y+dy, x+dx]
end

CONNECTIONS = {
  ?│ => [N, S],
  ?─ => [W, E],
  ?┌ => [S, E],
  ?┐ => [S, W],
  ?└ => [N, E],
  ?┘ => [N, W],
  ?┼ => [N, S, W, E],
}

BuildTrack =-> {
  piece_types = CONNECTIONS.keys
  piece_counts = gets.split(?,).map &:to_i

  pieces = 6.downto(0).map{|i|piece_types[i]*piece_counts[i]}.join.chars

  def solve (available_pieces, loose_ends=[[[0,0],nil]], board={})

    return board if loose_ends==[] and available_pieces==[]

    # optimization to avoid pursuing expensive paths
    # which cannot yield a result.
    # This prunes about 90% of the search space
    c = loose_ends.map{ |c, _| c }
    not_enough_pieces = c.product(c).any? { |q, r|
      ((q[0]-r[0])**2+(q[1]-r[1])**2) > available_pieces.size**2
    }
    return if not_enough_pieces

    position, connect_from = loose_ends.pop

    return unless position

    available_pieces.size.times do |i|
      piece = available_pieces[i]

      remaining_pieces = available_pieces[0...i] + available_pieces[i+1..-1]

      piece_not_connected_ok = connect_from && CONNECTIONS[piece] & [connect_from] == []
      next if piece_not_connected_ok

      new_loose_ends = loose_ends.select  { |pos, dir|
        # remove loose ends that may have been
        # fixed, now that we placed this piece
        position != pos || CONNECTIONS[piece] & [dir] == []
      }

      invalid_placement = false

      (CONNECTIONS[piece]-[connect_from]).map do |dir|
        new_pos = goto(position, dir)
        new_dir = opposite(dir)

        if board[new_pos]
          if CONNECTIONS[board[new_pos]] & [new_dir] != []
            # do nothing; already connected
          else
            # going towards an existing piece
            # which has no suitable connection
            invalid_placement = true
          end
        else
          new_loose_ends << [new_pos, new_dir]
        end
      end

      next if invalid_placement

      new_board = board.merge({position => piece})

      result = solve(remaining_pieces, new_loose_ends, new_board)
      return result if result
    end
    nil
  end

  def print_board board
    min_x = min_y = max_x = max_y = 0

    board.each do |position, _|
      y, x = position
      min_x = [min_x, x].min
      min_y = [min_y, y].min
      max_x = [max_x, x].max
      max_y = [max_y, y].max
    end

    str = (min_y..max_y).map{|_|
      ' ' * (max_x - min_x + 1)
    }

    board.each do |position, piece|
      y, x = position
      str[y-min_y][x-min_x] = piece
    end
    puts str
  end

  print_board(solve(pieces))
}


JavaScript (ES6),  118 113  109 bytes

s=>s.toUpperCase(A=[':)',...'NF1G]H5S9T[X=Z','{N}','M','--*']).replace(/[{-]..|:?./g,c=>A[A.indexOf(c)^1]||c)

Try it online!
How?
Because the input is guaranteed to contain exclusively [a-zA-Z] and/or the special patterns, we can use the following minimal regular expression to match them all:
/[{-]..|:?./g
 [{-]..        // either "{" or "-" followed by 2 other characters
               // -> to match "{N}" or "--*"
        :?.    // or any character, preceded by an optional ":"
               // -> to match ":)" or any single character

Working on the uppercase version of the input, we look for the position of each matched pattern in the lookup array A[] and replace it with its counterpart, or leave it unchanged if it is not found (which may only happen for ABCDEIJKLOPQRUVWY).


Display the mouse pointer trails... of the future!

Javascript

My program predicts the direction of the pointer by using the average of the angular change in direction of the last 20 mouse moves.  It also uses the variance of the angular change to create a "cloud" of possible locations and directions of the pointer.  The color of each pointer in the "cloud" is supposed to represent the likelihood of it being the new position of the mouse pointer, where darker colors represents a greater likelihood.  The distance of the pointer cloud ahead of the mouse is calculated using the speed of mouse movement.  It doesn't make the best predictions but it looks neat.

Here's a fiddle: http://jsfiddle.net/5hs64t7w/4/

Increasing the size of the pointer cloud is interesting to see. It can be set by changing the cloudSize variable on the first line of the program. Here is a fiddle with a cloud size of 10: http://jsfiddle.net/5hs64t7w/5/

I used these sources to get formulas for circular mean and variance:
Circular Mean: http://en.wikipedia.org/wiki/Circular_mean
Circular Variance: http://www.ebi.ac.uk/thornton-srv/software/PROCHECK/nmr_manual/man_cv.html

Here is the code if anyone is interested:

    var cloudSize = 3;

    var canvas = document.getElementById('canvas_element');
    var c = canvas.getContext('2d');
    var prevX = -1;
    var prevY = -1;
    var curX = -1;
    var curY = -1;
    var distance = 0;
    var direction = 0;

    function drawMouse(x, y, angle, gray){
        var grayVal = Math.round(gray*255);
        var grayString = "rgb(" + grayVal + "," + grayVal +"," + grayVal + ")";
        c.fillStyle = grayString;
        c.strokeStyle = grayString;
        c.lineWidth = 1;
        c.beginPath();
        c.moveTo(x, y);
        c.lineTo(x + 16*Math.cos(angle + Math.PI/2.0 + Math.PI/8.0), y + 16*Math.sin(angle + Math.PI/2.0 + Math.PI/8.0));
        c.moveTo(x, y);
        c.lineTo(x + 16*Math.cos(angle + Math.PI/2.0 - Math.PI/8.0), y + 16*Math.sin(angle + Math.PI/2.0 - Math.PI/8.0));
        c.lineTo(x + 16*Math.cos(angle + Math.PI/2.0 + Math.PI/8.0), y + 16*Math.sin(angle + Math.PI/2.0 + Math.PI/8.0));
        c.stroke();
        c.fill();
        c.beginPath();
        c.moveTo(x, y);
        c.lineTo(x + 24*Math.cos(angle + Math.PI/2), y + 24*Math.sin(angle + Math.PI/2));
        c.stroke();
    }

    function sum(array){
        var s = 0.0;
        for(var i=0; i<array.length; i++){
            s += array[i];
        }
        return s;
    }

    var sins = [];
    var coss = [];
    var lengths = [];
    var times = [];
    var index = 0;
    var limit = 20;
    var variance = 0;
    var prevTime = new Date().getTime();
    function updateDistanceAndDirection(x, y){
        var angle = Math.atan2(prevY - curY, prevX - curX);
        sins[index] = Math.sin(angle);
        coss[index] = Math.cos(angle);
        lengths[index] = Math.sqrt((curX-prevX)*(curX-prevX) + (curY-prevY)*(curY-prevY));
        var time = new Date().getTime();
        times[index] = time - prevTime;

        variance = 1.0 - Math.sqrt(sum(coss)*sum(coss)+sum(sins)*sum(sins))/sins.length;

        direction = Math.atan2(1/sins.length*sum(sins),1/coss.length*sum(coss));
        var speed = sum(lengths)/(sum(times)/200);
        distance = Math.min(Math.max(40, speed), 100);
        prevTime = time;
        index = (index+1)%limit;
    }

    function drawMice(count){
        c.clearRect(0, 0, canvas.width, canvas.height);

        for(var i=count; i>=0; i--){
            var dir = direction + i*variance;
            drawMouse(curX - distance*Math.cos(dir), curY - distance*Math.sin(dir), dir - Math.PI/2, i/count);
            dir = direction - i*variance;
            drawMouse(curX - distance*Math.cos(dir), curY - distance*Math.sin(dir), dir - Math.PI/2, i/count);
        }
    }

    canvas.onmousemove = function (event) {
        curX = event.clientX;
        curY = event.clientY;

        updateDistanceAndDirection(curX, curY);

        drawMice(cloudSize);

        prevX = curX;
        prevY = curY;
    };


Snails, 29 30 39 bytes
!{t\Oo\.+c\.,\O!{t\O{w!(.,~}2

It works by tracing out 2 sides of the rectangle, and then checking whether there is some square containing an O such that traveling in a straight line from the square in 2 of the cardinal directions would result in hitting a side of the rectangle.
Prints the maximum of 1 and the grid's area if the input is "arborally satisfied"; otherwise 0.


Haskell, 48 bytes

a%b=sum[((a**p+b**p)/2)**(1/p)|p<-[2,1,-1,1e-9]]

Try it online!

This uses the fact that the root-square, arithmetic, harmonic, and geometric means are all special cases of the generalized mean ((a**p+b**p)/2)**(1/p) for p=2,1,-1,0. The geometric mean uses the limit p->0+, approximated as p=1e-9 which suffices for precision.


JavaScript
var a=3,b=3,a2=3,b2=3
[a2,b2]=[a2*a,b2*a]
[a2,b2]=[a2-b*b,b2-b*b]
[a2,b2]=[a2/(a-b),b2/(a-b)]
console.log([a2/a,b2/a])

Output:
[1, NaN]

Note that 0/0 = NaN
Hint

 Try add some semicolons.
 This program is actually var a=3,b=3,a2=3,b2=3[a2,b2]=...=[a2/(a-b),b2/(a-b)];console.log([a2/a,b2/a]).
 And the NaN is [3/0,undefined/0]/3.


Sort and Table a Sentence by Word Lengths

R, 28 bytes

split(w<-scan(,""),nchar(w))

Try it online!

split does the trick; results in a list() where the element names are the lengths and  the elements are vectors containing the words.


APL (Dyalog Unicode) 17.0, 0 bytes

Dyalog 17.0 expects programs to terminate themselves cleanly and will throw an EOF INTERRUPT (and exit with a code 2) if they don't: Try it online!

In contrast, here is the minimal program which does terminate itself cleanly, causing no error (and code 0 upon exit): Try it online!


JavaScript (Node.js),  504 481  474 bytes
Builds a BigInt from a string encoded in base 126 and converts it to base 3.
Because the data string contains many unprintable characters, it is not shown at all below.

_=>0+Buffer(`...`).reduce((n,v)=>n*126n+BigInt(v-1),0n).toString(3)

Try it online!
The theoretical length of the string is:
$$\left\lceil\frac{\log(3^{1777})}{\log(126)}\right\rceil=404$$
Because a few characters need to be escaped, we actually need \$410\$ bytes to store it in the source.


Jelly, 9 bytes

2*Ɱ%µẠȧQL

A monadic Link accepting a positive integer, n, which yields a positive integer, the period.

Try it online! Or see the test-suite.

How?

2*Ɱ%µẠȧQL - Link: integer, n
2         - literal two
  Ɱ       - map across [1..n]
 *        - exponentiate -> [1,2,4,8,...,2^n]
   %      - modulo n -> [1%n,2%n,4%n,8%n,...,2^n%n]
    µ     - start a new monadic chain - call that X
     Ạ    - all (X)? -> 0 if we reach zero, else 1 - i.e. 0 if n is a power of 2
       Q  - de-duplicate (X) -> the repeating 2^k%n values
      ȧ   - logical AND -> 0 if n is a power of 2 else Q(X)
        L - length (0 has a length of 1 (after an implicit make_digits))


Calculate a tip using the smallest number of coins

JavaScript (ES6), 93 bytes

(x,m,M)=>(g=(t,c=1e4)=>t>x*M?0:t<x*m?[...'1343397439'].some(d=>g(t+(c/=-~d/2)))*r:r=t)(0)/100

Try it online!

How?

We recursively compute a sum of bill/coin values until it falls within the acceptable range, always trying the highest value first.

This is guaranteed to use the minimum amount of bills and coins because for any solution \$\{b_0,\dots,b_n\}\$ returned by this algorithm:

all terms \$b_0\$ to \$b_n\$ are required, otherwise the algorithm would have selected \$\{b_0,\dots,b_{k-1},x\}\$ with \$x \ge b_k\$ for some \$0 \le k < n\$
for any \$0 \le k < n\$ and any \$x \le b_n\$, \$\{b_0,\dots,b_{k-1},b_k-x,b_{k+1},\dots,b_n\}\$ cannot be a solution, otherwise \$\{b_0,\dots,b_{n-1}\}\$ would have been selected
there may exist some \$0 < x < b_n\$ such that \$\{b_0,\dots,b_{n-1},x\}\$ is also valid, but that would not use less bills/coins than the selected solution

The bill/coin values \$c_n\$ expressed in cents are computed with:

$$\begin{cases}c_0=10000\\c_{n+1}=\dfrac{c_n}{(d_n+1)/2}\end{cases}$$

where \$(d_0,\dots,d_9) = (1,3,4,3,3,9,7,4,3,9)\$.

 n | c(n)  | d(n) | k = (d(n)+1)/2 | c(n+1) = c(n)/k
---+-------+------+----------------+-----------------
 0 | 10000 |   1  | (1+1)/2 = 1    |      10000
 1 | 10000 |   3  | (3+1)/2 = 2    |       5000
 2 |  5000 |   4  | (4+1)/2 = 2.5  |       2000
 3 |  2000 |   3  | (3+1)/2 = 2    |       1000
 4 |  1000 |   3  | (3+1)/2 = 2    |        500
 5 |   500 |   9  | (9+1)/2 = 5    |        100
 6 |   100 |   7  | (7+1)/2 = 4    |         25
 7 |    25 |   4  | (4+1)/2 = 2.5  |         10
 8 |    10 |   3  | (3+1)/2 = 2    |          5
 9 |     5 |   9  | (9+1)/2 = 5    |          1


Retina, worst case (3+original length) bytes

EDIT: added support for newlines, in order to try this code in actual kolmogorov complexity challenges. Behaviour on strings without newlines remains unchanged.

Retina is great at substituting substrings, so that's what we're going to do!

This program looks for repeated sequences of characters and replaces them every time with a single character not appearing in the full string. The generated program then starts with the "compressed" string and applies all substitutions in reverse.

This code adds 3 bytes of boilerplate (a newline at the beginning, and a \` towards the end to suppress a trailing newline), so in the worst case (when there are no repeated sequences worth substituting) we have a length of 3 bytes more than the starting string. On average, this will shave a few bytes from the original length, not much but still a compression.

Here's the code with some comments:

First, we use a trick with transliteration ranges to change newlines into ¶, which is how newlines are printed in a Retina program

T`µ¶·`µ-·

then we start the main loop, duplicating the first line

{`^.+
$&¶$&

we only substitute when the sequence is repeated enough times (depending on its length)

^.*?((......+).*?\2|(.....?).*?\3.*?\3|(...).*?\4.*?\4.*?\4|(..).*?\5.*?\5.*?\5.*?\5.*?\5).*
"$2$3$4$5
^"(.+)|^.*
$+

to find a character not in the string, we append a list of candidates to the string, using " as separator, and then remove duplicates

^(.*)¶(.*)
$2" 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#%&\'()*+,-./:;?@\^_`{|}~¶$2¶$1
D`(?<=^.*).
^.*"(.)?.*¶(.+)
$2¶$1

here the actual substitution in the text happens

+`^(.*)(.+)(.*¶(.)¶\2(¶|$))
$1$4$3

in case we couldn't find a repeated sequence or an unused character, we restore the string to the original state (which makes us break from the loop)

}`(.*)¶(¶.*|.*¶)(¶|$)
$1$3

at the end, we add the 3 bytes of boilerplate

^
¶
\-1=`.*¶
\`$&

Try it online!

In the linked example, the 292 bytes paragraph gets compressed to a 286 bytes Retina code.

NOTE: the substitutions made are not optimal, we just make every time the first suitable substitution we find; I don't know if an algorithm finding the optimal substitutions could run in a reasonable amount of time.


Python (83)

r=lambda A,B,R=range(4):[sum(A[m]*B[m^p]*(-1)**(14672>>p+4*m)for m in R)for p in R]

Takes two lists A,B in [1,i,j,k] order and returns a result in the same format.

The key idea is that with [1,i,j,k] corresponding to indices [0,1,2,3], you get the product's index (up to sign) by XOR'ing the indices. So, the terms that get placed in index p are those who indices XOR to p, and are thus the products A[m]*B[m^p].

It only remains to make the signs work out. The shortest way I found was to simply code them into a magic string. The 16 possibilities for (m,p) are turned into numbers 0 to 15 as p+4*m. The number 14672 in binary has 1's at the places where -1 signs are needed. By shifting it the appropriate number of places , a 1 or 0 winds up at the last digit, making the number odd or even, and so (-1)** is either 1 or -1 as needed.


I copied my password to the clipboard! Can you delete it?

PowerShell, 3 bytes

scb

That's a default alias for Set-Clipboard. When called with nothing piped in and no arguments supplied, it blows away the current clipboard contents.


Jelly, 10 bytes
UÐeẎṙṁ⁸UÐe

A dyadic Link accepting the marix on the left and the rotation integer on the right (uses the reverse meaning of positive / negative)
Try it online!
How?
UÐeẎṙṁ⁸UÐe - Link: matrix of integers, M; integer, R
 Ðe        - apply to even indices of M:
U          -   reverse each
   Ẏ       - tighten
    ṙ      - rotate left by R
     ṁ     - mould like:
      ⁸    -   chain's left argument, M
        Ðe - apply to even indices:
       U   -   reverse each


Calculate Network Average Clustering Coefficient


SOGL V0.12, 8 6 bytes
I».»⌡±

Try it Here! or try the first couple numbers (changed a bit so it'd work)
0-indexed.
Explanation:
I       increment the input
 »      floor divide by 2
  .     push the original input
   »    floor divide by 2
    ⌡   that many times
     ±    negate

Or simpler:
(input + 1) // 2 negated input // 2 times
        I     »     ±      .     »    ⌡


0.9514747859 (4204-byte output)

Note: the image above is not the actual file I used, but it is the image.

Here is a hexdump of the file: https://gist.github.com/pommicket/cf2982e8ecf09a4de89d3a849526c64b

The file is in the netpbm format, and can be generated with this C code:

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

int main(int argc, char **argv) {
    if (argc < 2) {
        fprintf(stderr, "Please pass in seed.\n");
        return EXIT_FAILURE;
    }
    srand(atoi(argv[1]));
    FILE *fp = fopen("image.pgm", "w");
    int width = 2, height = 1993;
    fprintf(fp, "P5 %d %d 255 ", width, height);
    for (int i = 0; i < width * height; i++) {
        fputc(rand() & 0xFF, fp);
    }
    fclose(fp);
    return 0;
}

The random seed must be passed into the program. After trying some seeds, I got one which produced a 4204 byte gzipped file. As Nnnes pointed out, tar will include metadata in the file, so your results might differ from mine.

netpbm isn't supported everywhere, but it works with imagemagick's convert (so just do convert image.pgm image.png to turn it into a png).

Why this image/format?

A file which consists of entirely random bytes is very hard to compress (in fact, any possible compression algorithm will do on average, no better than not compressing for random files). The content of the actual file is just P5 2 1993 followed by 3986 random bytes, which is why gzip has such a hard time compressing it.


Clearing the most significant bit from an integer

C (gcc), 49 44 40 39 bytes

i;f(n){for(i=1;n/i;i*=2);return n^i/2;}

Try it online!


Crash (i.e. cause the interpreter to stop working and force close) Python

Should have been a code-golfing contest ;) - I guess the creativity is the statement the code makes: "I just don't know what's happening here..."

Copy and paste the following character in IDLE running on Windows:

The crash has something to do with the character being encoded as UTF-16 by Windows and the unsuccessful conversion to a UTF-8 character by IDLE...

Edit: python bug #13153


Advent Challenge 6: Transport Dock Relabeling!

Mathematica, 106 bytes

sSelect[MinMax/@s~TakeList~#&/@Join@@Permutations/@IntegerPartitions@Tr[1^s],Unequal@@Join@@Range@@@#&]

Try it online!

Martin saved 16 bytes


C++

I wrote this one up today. It is not the most efficient way and does not always generate the most random looking word searches but it gets the job done and it does it relatively quick.

Bonus: Supports Palindromes too!!!

It works by taking input for the word and the size of the word search. It then generates infurators by dropping letters, inserting letters, or flipping letters. It then adds those to the grid as well as the correct word. It then checks all instances of the first letter in every direction for the word. If 1 instance is not found ( 2 for palindromes ) it brute forces the cycle over. It then outputs the word search to console as well as a file.

Here it is at 213 lines of code with whitespace and comments.

#include <fstream>
#include <iostream>
#include <string>
#include <vector>

#include <stdio.h>
#include <time.h>

// Keep Track of Coordinates
struct XY {

public:
    int X;
    int Y;
};

// Just in case someone breaks the rules
std::string ToUppercase( const std::string& pWord ) {
    char *myArray = new char[ pWord.size() + 1 ];
    myArray[ pWord.size() ] = 0;
    memcpy( myArray, pWord.c_str(), pWord.size() );

    for ( unsigned int i = 0; i < pWord.size(); i++ ) {
        if ( (int) myArray[ i ] >= 97 && (int) myArray[ i ] <= 122 ) {
            myArray[ i ] = (char) ( (int) myArray[ i ] - 32 );
        }
    }

    return std::string( myArray );
}

// Random number between a max and min inclusively
int RandomBetween( int pMin, int pMax ) {
    return rand() % ( pMax - pMin + 1 ) + pMin;
}

// Find all instances of a character
std::vector<XY> FindHotspots( const std::vector<char> &pWordSearch, char pFirstChar, unsigned int pLength ) {
    std::vector<XY> myPoints;
    for ( unsigned int i = 0; i < pLength; i++ ) {
        for ( unsigned int j = 0; j < pLength; j++ ) {
            if ( pWordSearch[ i * pLength + j ] == pFirstChar ) {
                XY myXY;
                myXY.X = i;
                myXY.Y = j;
                myPoints.push_back( myXY );
            }
        }
    }
    return myPoints;
}

// Searchs each index from specific point in certain direction for word
// True if word is found
bool Found( const std::vector<char> &pWordSearch, const std::string &pWord, int pRow, int pCol, int pX, int pY, int pLength ) {
    for ( unsigned int i = 0; i < pWord.length(); i++ ) {
        if ( pRow < 0 || pCol < 0 || pRow > pLength - 1 || pCol > pLength - 1 )
            return false;
        if ( pWord[ i ] != pWordSearch[ pRow * pLength + pCol ] )
            return false;
        pRow += pX;
        pCol += pY;
    }
    return true;
}

// Goes through all the hotspots and searchs all 8 directions for the word
int FindSolution( const std::vector<char> &pWordSearch, const std::string &pWord, unsigned int pLength ) {
    std::vector<XY> myHotspots = FindHotspots( pWordSearch, pWord[ 0 ], pLength );

    int mySolutions = 0;
    for ( unsigned int i = 0; i < myHotspots.size(); i++ ) {
        if ( Found( pWordSearch, pWord, myHotspots[ i ].X, myHotspots[ i ].Y, 1, 0, pLength ) )
            mySolutions++;
        if ( Found( pWordSearch, pWord, myHotspots[ i ].X, myHotspots[ i ].Y, 1, 1, pLength ) )
            mySolutions++;
        if ( Found( pWordSearch, pWord, myHotspots[ i ].X, myHotspots[ i ].Y, 0, 1, pLength ) )
            mySolutions++;
        if ( Found( pWordSearch, pWord, myHotspots[ i ].X, myHotspots[ i ].Y, -1, 1, pLength ) )
            mySolutions++;
        if ( Found( pWordSearch, pWord, myHotspots[ i ].X, myHotspots[ i ].Y, -1, 0, pLength ) )
            mySolutions++;
        if ( Found( pWordSearch, pWord, myHotspots[ i ].X, myHotspots[ i ].Y, -1, -1, pLength ) )
            mySolutions++;
        if ( Found( pWordSearch, pWord, myHotspots[ i ].X, myHotspots[ i ].Y, 0, -1, pLength ) )
            mySolutions++;
        if ( Found( pWordSearch, pWord, myHotspots[ i ].X, myHotspots[ i ].Y, 1, -1, pLength ) )
            mySolutions++;
    }
    return mySolutions;
}

// Generate words that are similar
//
// 1. Word with last character same as first
// 2. Word with 1 character removed
// 3. Word with 1 character added
std::vector<std::string> GenerateInfurators( const std::string &pWord ) {
    std::vector<std::string> myInfurators;
    for ( unsigned int i = 0; i < pWord.size() / 2; i++ ) {
        char myReplace = '0';
        do {
            myReplace = pWord[ RandomBetween( 0, pWord.size() - 1 ) ];
        } while ( myReplace == pWord[ pWord.size() - 1 ] );
        myInfurators.push_back( pWord.substr( 0, pWord.size() - 2 ) + myReplace );
    }

    for ( unsigned int i = 1; i < pWord.size() - 2; i++ ) {
        myInfurators.push_back( pWord.substr( 0, i ) + pWord.substr( i + 1 ) );

        std::string myWord = pWord;
        myInfurators.push_back( myWord.insert( i, 1, pWord[ i - 1 ] ) );
    }

    return myInfurators;
}

// Adds word in random position in word search
void AddWordRandomly( std::vector<char> &pWordSearch, const std::string &pWord, unsigned int pLength ) {
    int myXDirec = 0;
    int myYDirec = 0;
    do {
        myXDirec = RandomBetween( -1, 1 );
        myYDirec = RandomBetween( -1, 1 );
    } while ( myXDirec == 0 && myYDirec == 0 );

    int myRow = 0;
    if ( myXDirec == 0 ) {
        myRow = RandomBetween( 0, pLength - 1 );
    } else if ( myXDirec > 0 ) {
        myRow = RandomBetween( 0, pLength - pWord.size() - 1 );
    } else {
        myRow = RandomBetween( pWord.size(), pLength - 1 );
    }

    int myCol = 0;
    if ( myYDirec == 0 ) {
        myCol = RandomBetween( 0, pLength - 1 );
    } else if ( myYDirec > 0 ) {
        myCol = RandomBetween( 0, pLength - pWord.size() - 1 );
    } else {
        myCol = RandomBetween( pWord.size(), pLength - 1 );
    }

    for ( unsigned int i = 0; i < pWord.size(); i++ ) {
        pWordSearch[ myRow * pLength + myCol ] = pWord[ i ];
        myRow += myXDirec;
        myCol += myYDirec;
    }
}

// Checks for palindromes
bool WordIsPalindrome( const std::string &pWord ) {
    for ( unsigned int i = 0; i < pWord.size(); i++ ) {
        if ( pWord[ i ] != pWord[ pWord.size() - 1 - i ] )
            return false;
    }
    return true;
}

int main() {
    // Handle all input
    std::string myWord;
    std::cin >> myWord;
    myWord = ToUppercase( myWord );

    std::string myStrLength;
    std::cin >> myStrLength;
    unsigned int mySideLength = std::stoi( myStrLength );

    // Setup variables
    // New time seed
    // Generate infurators
    // Add words
    std::vector<char> myWordSearch;
    srand( ( unsigned int ) time( 0 ) );
    std::vector<std::string> myWords = GenerateInfurators( myWord );
    myWords.push_back( myWord );

    bool myWordIsPalindrome = WordIsPalindrome( myWord );

    // Brute force words until 1 instance only
    // 2 instances for palindromes
    do {
        for ( unsigned int i = 0; i < mySideLength * mySideLength; i++ ) {
            myWordSearch.push_back( myWord[ RandomBetween( 0, myWord.size() -1 ) ] );
        }

        for ( unsigned int j = 0; j < 10; j++ ) {
            for ( unsigned int i = 0; i < myWords.size() - 1; i++ ) {
                AddWordRandomly( myWordSearch, myWords[ i ], mySideLength );
            }
        }
        AddWordRandomly( myWordSearch, myWord, mySideLength );
    } while ( ( FindSolution( myWordSearch, myWord, mySideLength ) != 1 && !myWordIsPalindrome ) ||
            ( FindSolution( myWordSearch, myWord, mySideLength ) != 2 && myWordIsPalindrome ) );

    // Output to console && text file
    std::ofstream myFile( "word_search.txt" );
    for ( unsigned int i = 0; i < mySideLength; i++ ) {
        for ( unsigned int j = 0; j < mySideLength; j++ ) {
            myFile << myWordSearch[ i * mySideLength + j ] << "";
            std::cout << myWordSearch[ i * mySideLength + j ] << " ";
        }
        myFile << "\n";
        std::cout << "\n" << std::endl;
    }
    myFile.close();

    system( "pause" );
    return 0;
}

I am far from a C++ expert so I'm sure there's places where this code could be improved but I was happy with how it ended up.

Here's the outputs.

BANANA-12:
BBBBBABANABB
BBANAAANANBB
BABAANABBABA
BNAANAAANABN
BANNNNNANBBB
AANABNNANNAA
NAANANAAAABA
ANNNBAANNNBN
ABABNAANABNA
BNNANNAAANNB
BBABAAANBBAB
BBANANNBBABB

ELEMENT-14:
MLELEMEEETNEET
EMTTELTEETELEE
EMNNELEENLNTEL
TLTNEEMEEELMTM
TLEMLNLMEEEETE
TTEEEEEENLNTLE
NETNENEEMTTMEN
ELELTETEEMNMEE
MTEEMTNEEEENEM
ELENEEEMMENNME
ELLEELELTMLETL
ETLTNEMEEELELE
EELTLLLLLMNEEE
EEEELEMNTLEEEE

ABRACADABRA-22:
ACRABAACADABBADBRRAAAA
BBABAABAARBAAAARBAABAA
RARRARBAAABRRRRAAABBRA
DABARRARABBBBABABARABR
BRBACABBAAAABAARRABDAD
ABRRCBDADRARABAACABACR
DCAAARAABCABRCAAAARAAA
AAABACCDCCRACCDARBADBA
CAARAAAAAACAAABBAACARA
ADRABCDBCARBRRRDAABAAR
RARBADAARRAADADAABAAAB
BBRRABAABAAADACACRBRAA
ARBBBDBRADCACCACARBABD
CAARARAAAACACCDARARAAA
ARABADACRARCDADABADBBA
RARAADRRABADBADAABBAAA
RAAAABBBARRDCAAAAAARRA
BABBAAACRDBABCABBBRAAR
AARARAARABRAAARBRRRAAB
BAAAARBRARARACAARAAAAA
ADCBBABRBCBDBRARAARBAA
AARBADAAAARACADABRAABB

Bonus: RACECAR-14:
RRACEARCECARAR
RRRRRRRRRCARAR
RARRAACECARAAA
CCACECRREAECAR
RECEAEEAAECEAE
RCRRREACCCCEAR
RRRARCERREERRR
CCARAAAAECCARC
ECECARRCCECCRR
CARRRACECCARAC
ACRACCAAACCCAR
ARRECRARRAAERR
RRCRACECARRCRR
RRRRACECRARRRR

I may update this to generate slightly more "random" looking word searches.


sh (+ curl + grep), 28 26 bytes

curl -L isup.me/$1|grep ^I

Outputs via exit status (0 for up, 1 for down).  Looks for an I at the beginning of a line, which matches when the domain is up (even for the special case of isup.me/isup.me).


Javascript, 104 (114 chars - 10 bonus)
All due credit here.  Simply posting this to get the "first answer" -10 bonus ;-).
p='$.post("/unicoin/'
setInterval(p+'rock",function(o){'+p+'mine?rock="+o.rock,StackExchange.options.user)})',2e4)

setInterval accepts both functions and strings of code. After susbtituting the variable p, the following gets executed every 20 seconds:
$.post("/unicoin/rock", function(o) {
    $.post("/unicoin/mine?rock=" + o.rock, StackExchange.options.user)
}

Edits are welcome.  I don't know javascript well enough to really competitively golf this.


Take It or Leave It III: A Game Show for Computers

Java, $3889.5 Median
        int highest=0;
        int topp=0,tott=0;
        for(int i=0;i<1000;i++){
            if(Read()>topp&&tott+Read()-i>tott){
                topp=Read();
                tott += Read();
                tott -= i;
                Take();
            }else{
                if(tott-i>i/2){
                    tott -= i;
                    Pass();
                }else{
                    End();
                    break;
                }
            }
            if(highest/1.1>tott){
                End();
                break;
            }
            if(tott>highest)
            highest=tott;
        }

Try it Online


Write an interactive Deadfish interpreter

Perl 5, 90 bytes

do{print+(map{$?+=/i|x/-/d/;$?**=1+/s|k/;$?=~s/-1|^256$/0/;"$?
"x/o|c/}/./g),'>> '}while<>

Try it online!

Thanks to @xfix for his help on this previously! Saved 4 bytes thanks to @Xcali!


Groovy, 656 bytes

That was too long...

i={println"Invalid map."
System.exit(1)}
m=[]
q=System.in.newReader()
r=q.readLine()
while(r!=''){m<<r
r=q.readLine()}
o=m[0].size()
m.each{if(it.size()!=o)i()}
f=[0]*4
m.eachWithIndex{l,n->s=l.indexOf('S')
e=l.indexOf('E')
if(s!=-1){f[0]=s;f[1]=n}
if(e!=-1){f[2]=e;f[3]=n}}
v=[]
t={x,y,d->if(d.contains([x,y])|y>=m.size()|x>=o|x<0|y<0)return
a=m[y][x]
def p=d+[[x,y]]
if(a=='E')v=p
if(a=='J'|a=='0'|a=='S'){t(x-1,y,p)
t(x+1,y,p)
t(x,y+1,p)
t(x,y-1,p)}}
t(f[0],f[1],[])
if(!v)i()
o=0
p=''
v.inject{t,s->
c=m[s[1]][s[0]]
k=[t[0]-s[0],t[1]-s[1]]
z=[[0,1]:0,[1,0]:1,[0,-1]:2,[-1,0]:3][k]
p+=((((o-z)==0)?'':(z>0?'R':'L'))+(c=='J'?'M':'')+'F')
o=z
s}
println p

Output for the maze:

RFFLFRFMFLFRFLFF

Ungolfed:

invalid = {
    println "Invalid map."
    System.exit(1)
}
map = """01001E
010110
000P00
1110J1
S00111""".split('\n')

//map = [""]// TODO remove this, this is type checking only
//map.remove(0)
//reader = System.in.newReader()
//line = reader.readLine()
//while (line != '') {
//    map << line.replace('P','1')
//    line = reader.readLine()
//}

size = map[0].size()
map.each {if(it.size() != size) invalid()}

startAndEnd = [0,0,0,0]
map.eachWithIndex {it, idx -> s=it.indexOf('S');e=it.indexOf('E');
    if(s!=-1){ startAndEnd[0]=s; startAndEnd[1]=idx}
    if(e!=-1){ startAndEnd[2]=e; startAndEnd[3]=idx}}

def validPath = []

testMove = {x, y, visited ->// visited is an array of x y pairs that we have already visited in this tree
    if (visited.contains([x,y]) || y>=map.size() || x>=size || x<0 || y<0)
        return;

    def valueAtPos = map[y][x]
    def newPath = visited + [[x,y]]

    if (valueAtPos == 'E') validPath = newPath
    if ((valueAtPos == 'J' || valueAtPos == '0' || valueAtPos == 'S') && !validPath) {
        testMove(x-1, y, newPath)
        testMove(x+1, y, newPath)
        testMove(x, y+1, newPath)
        testMove(x, y-1, newPath)
    }
}
if (!validPath) invalid()
testMove(startAndEnd[0],startAndEnd[1], [])

println validPath

orintation = 0
path = ''
validPath.inject {first, second ->
    def chr = map[second[1]][second[0]]
    def sub = [first[0]-second[0],first[1]-second[1]]
    println "acc:$first, second:$second"
    def newOrin = [[0,1]:0, [1,0]:1, [0,-1]:2, [-1,0]:3][sub]
    path += ((((orintation - newOrin)==0)?'':(newOrin>0?'R':'L')) + (chr=='J'?'M':'') + 'F')
    orintation = newOrin
    second
}
println "path: $path"

I will try this again in python soon to see if I can shorten it further.


Determine if land is fully enclosed by fences


Ruby, 43
y=gets.to_r;puts"#{y.to_i} + (#{y-y.to_i})"

Pretty straightforward.


JavaScript (ES6), 47 bytes

f=(n,a=[b=1])=>n--?f(n,[b,...a.map(e=>b+=e)]):b
f=(n,a=[b=1])=>--n?f(n,[b,...a.map(e=>b+=e)]):b

First one is 0-indexed, second is 1-indexed.


Haskell, 59 bytes

a#((b:c):r)=b*p(a++map tail r)+(c:a)#r
_#_=0
p[]=1
p l=[]#l

This does a Laplace-like development along the first column, and uses that the order of the rows doesn't matter. It works for any numeric type.

Input is as list of lists:

Prelude> p [[1,2],[3,4]]
10


05AB1E, 7 6 bytes
Six byte solution
Since prime factorisation is now allowed, this is my six byte solution:
LDÒ€gÏ

Explanation:
L       # Create the list [1, ..., input]
 D      # Duplicate this list
  Ò     # Get the prime factorisation of each number
   €g   # Get the length of each prime factorisation (length 1 = prime)
     Ï  # Keep the numbers for which is the index is equal to 1

Uses CP-1252 encoding. Try it online!.

Previous solution
Uses Wilson's theorem. Code:
LÐ<!n%Ï

Explanation:
L        # Generate the list [1, ..., input].
 Ð       # Triplicate the list.
  <      # Decrement the last one by one.
   !     # Take the factorial.
    n    # Square each.
     %   # Modulo the list by [1, ..., input].
      Ï  # Take the values for which the indices are equal to 1.

Visual explanation for input n = 9:
 Command - Stack

L        # [1, 2, 3, 4, 5, 6, 7, 8, 9]
 Ð       # [1, 2, 3, 4, 5, 6, 7, 8, 9] × 3
  <      # [1, 2, 3, 4, 5, 6, 7, 8, 9] × 2, [0, 1, 2, 3, 4, 5, 6, 7, 8]
   !     # [1, 2, 3, 4, 5, 6, 7, 8, 9] × 2, [1, 1, 2, 6, 24, 120, 720, 5040, 40320]
    n    # [1, 2, 3, 4, 5, 6, 7, 8, 9] × 2, [1, 1, 4, 36, 576, 14400, 518400, 25401600, 1625702400]
     %   # [1, 2, 3, 4, 5, 6, 7, 8, 9], [0, 1, 1, 0, 1, 0, 1, 0, 0]

Which leaves us (using Ï):
[1, 2, 3, 4, 5, 6, 7, 8, 9],
[0, 1, 1, 0, 1, 0, 1, 0, 0]

    2  3     5     7

Uses CP-1252 encoding. Try it online!.


Mathematica, 223
r[p_,t_]:=Module[{l},l=Exponent[p[x],x];Re@Select[NestWhile[Table[#[[i]]-p[#[[i]]]/Product[If[i!=j,#[[i]]-#[[j]],1],{j,l}],{i,l}]&,Table[(0.9+0.1*I)^i,{i,l}],2*Max[Table[Abs[#1[[i]]-#2[[i]]],{i,l}]]>t&,2],Abs[Im[#]]<t^.5&]]

This solution implements the Durand–Kerner method for solving polynomials. Note that this is not a complete solution (as will be shown below) because I cannot yet handle Wilkinson's Polynomial to the specified precision. First an explanation of what I'm doing:

#[[i]]-p[#[[i]]]/Product[If[i!=j,#[[i]]-#[[j]],1],{j,l}]&:
Thus function computes for each index i the next Durand-Kerner approximation. Then this line is encapsulated in a Table and applied using a NestWhile to the input points generated by Table[(0.9+0.1*I)^i,{i,l}]. The condition on the NestWhile is that the max change (over all terms) from one iteration to the next is greater than the specified precision. When all terms have changed less than this, the NestWhile ends and Re@Select removes the zeros that do not fall on the real line.
Example output:
> p[x_] := x^2 - 2
> r[p, .01]
{1.41421, -1.41421}

> p[x_] := x^4 - 8 x^3 + 18 x^2 - 27
> r[p, 10^-6]
{2.99999, 3., 3.00001, -1.}

> p[x_] := x^20 - 210 x^19 + ... + 2432902008176640000 (Wilkinson's)
> Sort[r[p, 2^-32]]
{1., 2., 3., 4., 5., 6., 7.00001, 7.99994, 9.00018, 10.0002, 11.0007, \
11.9809, 13.0043, 14.0227, 14.9878, 16.0158, 16.9959, 17.9992, \
19.0001, 20.}

As you can probably see, when the degree grows higher this method begins to bounce around the correct values, never really homing in completely. If I set the stopping condition of my code to be anything stricter than "from one iteration to next the guesses changed by no more than epsilon" then the algorithm never stops. I guess I should just use Durand-Kerner as input to Newton's method?


Bl lu ur rr ry yv vi is si io on - Blur the text

Python 3, 57 55 bytes

lambda s:"".join((c+" "+c)*c.isalnum()for c in s)[2:-2]

Try it online!

How:

For each alpha-numeric character c in the string, replace it with c+" "+c.
E.g: "abcd" -> "a ab bc cd d"
Remove the redundant first and last 2 characters:
E.g: "a ab bc cd d" -> "ab bc cd"


Haskell, 91 85 83 80 75 74 bytes

n#m=([n#(div m d+d+1)|d<-[2..m-1],mod m d<1]++[mod n m<1&&m<n])!!0
f x=x#x

Try it online!

f x=x#x                           -- call # with x for both parameters
n#m
         |d<-[2..m-1],mod m d<1   -- for all divisors d of m
    [n#(div m d+d+1)           ]  -- make a list of recursive calls to #,
                                  -- but with m set to m/d+d+1
   ++ [mod n m<1&&m<n]            -- append the Redivosite-ness of n (m divides n,
                                  -- but is not equal to n)
                           !!0    -- pick the last element of the list
                                  -- -> if there's no d, i.e. m is prime, the
                                  --    Redivosite value is picked, else the
                                  --    result of the call to # with the smallest d

Edit: -2 bytes thanks to @BMO, -3 bytes thanks to @H.PWiz and -5 -6  bytes thanks to @Ørjan Johansen


JavaScript (ES6), 253 bytes

x=>eval('n=(" "+x).replace(/D.{11}|[CSF]/g,d=>({C:4,S:5,F:6}[d]|(d[2]<"S")*2+(d[8]<"f"))).split` `;for(i=c=f=o="";v=n[++i];v<9?v<4?(n[i]=7,i=0,s=n.indexOf`5`,v==0?f=i=s:v==1?c=i=s:v==2?f=1:c=1):v==4&c?c=!(i=n.indexOf("4",i+1)):v==6&f?i=n:0:o+=v+" ");o')

Explanation

Could be golfed better but I'm done for now.

x=>
  eval(`                                  // use eval to enable for loop without return
    n=(" "+x)                             // n = array of [ "", ...notes/commands ]
                                          // empty first element means f and c can be set
                                          //     to i (always true) in the cases below
      // DS fine => 0, DS coda => 1, DC fine => 2, DC coda => 3, C => 4, S => 5, F => 6
      .replace(/D.{11}|[CSF]/g,d=>({C:4,S:5,F:6}[d]|(d[2]<"S")*2+(d[8]<"f")))
      .split\` \`;
    for(
      i=                                  // i = position in note array
      c=                                  // c = look out for coda if true
      f=                                  // f = look out for fine if true
      o="";                               // o = output string
      v=n[++i];                           // v = note/command
      v<9?                                // if not a note
        v<4?(                             // if DS/DC
          n[i]=7,                         // change it to NOP
          i=0,                            // reset i here to save doing it in DC cases
          s=n.indexOf\`5\`,
          v==0?f=i=s:                     // case: D.S. al fine
          v==1?c=i=s:                     // case: D.S. al coda
          v==2?f=1:                       // case: D.C. al fine
          c=1                             // case: D.C. al coda
        ):
        v==4&c?c=!(i=n.indexOf("4",i+1)): // case: C
        v==6&f?i=n:                       // case: F
        0                                 // case: S
      :o+=v+" "                           // add the note
    );o                                   // return the output
  `)

Test

var solution = x=>eval('n=(" "+x).replace(/D.{11}|[CSF]/g,d=>({C:4,S:5,F:6}[d]|(d[2]<"S")*2+(d[8]<"f"))).split` `;for(i=c=f=o="";v=n[++i];v<9?v<4?(n[i]=7,i=0,s=n.indexOf`5`,v==0?f=i=s:v==1?c=i=s:v==2?f=1:c=1):v==4&c?c=!(i=n.indexOf("4",i+1)):v==6&f?i=n:0:o+=v+" ");o')
<input type="text" id="input" value="a b C c d D.C. al coda e f F g g# C gb a# D.C. al fine" />
<button onclick="result.textContent=solution(input.value)">Go</button>