Abstract Syntax Tree Golfing: FizzBuzz, Python


CJam, 29 + 29 = 58 bytes

The 0 code:

0{"_~"]]z(3\+2b(2b2>a\+z~[}_~

The 1 code:

1{"_~"]]z(3\+2b(2b2>a\+z~[}_~

Explanation

0                       " Push the current bit. ";
{"_~"                   " The basic quine structure. ";
    ]                   " Make an array of the current bit, the function and _~.
                          That is the code fragment itself. ";
    ]                   " Make an array of all code fragments in the stack. ";
    z(                  " Extract the array of the bits. ";
    3\+2b(2b2>          " Convert from base 2, decrease by one and convert back,
                          keeping the length. ";
    a\+z                " Put the bits back to the original position. ";
    ~                   " Dump the array of code fragments back into the stack. ";
    [                   " Mark the beginning position of the array of the next code fragment. ";
}_~


C

Not exactly a long division - this answer uses the method used in the real old days.

#include <stdio.h>
#include <stdlib.h>
int main() {
    int a,b;
    scanf("%d %d", &a, &b);
    int *p=calloc(b, sizeof(int));
    int *q=p;
    while(a--) {
        (*p)++;
        if(p-q<b-1) p++;
        else p-=b-1;
    }
    p=q;
    int r=0, i;
    for(i=0; i<b; i++) r+=p[i]-p[b-1];
    printf("%d %d\n", p[b-1], r);
    return 0;
}

Explanation:

Suppose you are given a number of sheep and you need to split them up into b number of groups. The method used here is to assign each sheep into a different group until the total number of groups reaches b, then start from the first group again. This repeats until there are no more sheep. Then, the quotient will be the number of sheep in the last group, and the remainder will be the sum of the differences between each group and the last group.

An illustration for 8/3:

       |Group 1 | Group 2 | Group 3
-------------------------------------
       | 1      | 2       | 3        // first sheep in group 1, second sheep in group 2, etc
       | 4      | 5       | 6
       | 7      | 8       |
-------------------------------------
total: | 3      | 3       | 2

So the quotient is 2 and the remainder is (3-2)+(3-2)=2.


Normal and inverted exclamation and question mark pairs

Retina, 39 37 34 bytes

\w[^.]*?([!?])
$1$0
T`?!`¿¡`\S\b

Try it online.

Explanation

\w[^.]*?([!?])
$1$0

This matches a sentence ending in an exclamation or question mark, and prepends that punctuation character to the sentence. Now we know that all the ! or ? which are immediately followed by a non-space character must be those we inserted, because the original ones should be separated from the next character by a space.

T`!?`¡¿`\S\b

This transliteration stage turns all ! and ? into ¡ and ¿, respectively, provided they're found in a match of \S\b, which applies only to the ones we just inserted. Replacing both in two separate substitutions in the same byte count, but I prefer the semantics of a transliteration stage here.


Letter Boxed, part 2: this time, solve it

Jelly, 38 bytes

iⱮⱮL>2ƊƇẠƇ’:3IẠƲƇŒPU=ḢɗƝẠ$ƇFQL=ʋƇ12ịḷḢ

Try it online!

A dyadic link taking the flattened letters as left argument and the dictionary as right. Returns a list of strings of one of the shortest solutions, or a zero if there is no solution.

Full explanation to follow once it’s a bit better golfed.


05AB1E, 3 bytes

Code:

ÝJg

Uses the CP-1252 encoding. Try it online!

Explanation:

Ý     # Range [0 .. input]
 J    # Join into one string
  g   # Get the length of the string


Mathematica
The 2D code generates a graph showing the path of the water. I displayed the vertex numbers for convenient cross-checking with the 3D display.  Normally the vertex numbers would be hidden.
Input:
r=10;c=7;
result=flow2D[{r,c},3]

Actually, the result contains multiple objects. The first object, result[[1]], is the 2D graph shown here.

The 3 dimensional pipes are Tube's  (3D lines) plotted in 3 space.  The coordinates computed based on the vertices of the 2D graph along a 3rd coordinate that was randomly generated (This allows the pipes to assume different positions along y each time the code is run.)
The axes are displayed to help the reader convince herself that the 3D rendering is indeed based on the 2D rendering.
The 3D input of interest here is:
Graphics3D[{CapForm[None],verticalPipes,allRungs,Darker@Red,connections},
ImageSize->600,Axes-> True,Ticks->{Range[1,2 r,2],Range[c],Range[10]},ViewPoint->{0,-2,1.5}]

The number or rows, columns and entry column are taken from the 2D code.  They do not have to be re-entered.

2D Code
In the coming days I will document and tidy up the code for 2D and 3D.
flow2D[{rows_,columns_},startColumn_]:=
Module[{r=rows,c=columns,g,j,h,ends,middle,midcuts,direction="down",turns=0,path,rungs},

   (*complete gridgraph*)
g=GridGraph[{r,c},VertexSize-> Medium,GraphStyle->"Prototype",EdgeStyle->"Thick",
  VertexLabels->"Name",ImagePadding-> 30,ImageSize->470];

(*horizontal pipes that must be removed*)
ends=Table[r(c1-1)+r1\[UndirectedEdge] r(c1)+r1,{c1,1,c-1},{r1,{1,r}}];

(*horizontal pipes to consider removing *)
middle=Table[r(c1-1)+r1\[UndirectedEdge] r(c1)+r1,{c1,1,c-1},{r1,2,r-1}];
midcuts=RandomSample[#,RandomInteger[Round[{r/15,2r/5}]]]&/@middle;

rungs=Flatten[midcuts(*Join[ends,midcuts]*)];

j=EdgeDelete[g,Flatten[Join[ends,midcuts]]];

h[path_]:= Module[{start=path[[-1]],right,left,up,down,newnodes},
     {v=NeighborhoodGraph[j,start,1,(*VertexLabels\[Rule]"Name",*)ImagePadding->25],
     VertexList[v]};newnodes=Complement[VertexList[v],path];
     If[newnodes=={},path,
     h[Append[path,
  Switch[direction,
   "down",Which[
     MemberQ[newnodes,start+r],(turns++;direction="right";start+r),
     MemberQ[newnodes,start-r],(turns++;direction="left";start-r),
     MemberQ[newnodes,start-1],start-1],
   "right",Which[
     MemberQ[newnodes,start-1],(turns++;direction="down";start-1),
     MemberQ[newnodes,start+r],start+r],
   "left",Which[
     MemberQ[newnodes,start-1],(turns++;direction="down";start-1),
     MemberQ[newnodes,start-r],start-r]
    ]]]]];
{HighlightGraph[j,path=h[{r*startColumn}],ImageSize->300],path,rungs,ends,midcuts}]

convert[node_,r_,c_]:=Append[footing[[Quotient[node-1,r]+1]],Mod[node-1,r]+1(*Mod[node,r]*)]
connect[a_\[UndirectedEdge]b_,r_,c_]:=Tube[Line[{convert[a,r,c],convert[b,r,c]}],0.2]

3D Code and results
r=10;c=7;
result=flow2D[{r,c},3];
g2D=result[[1]];
path2D=result[[2]];
\[AliasDelimiter]
xScale=2;
footing = {#, RandomInteger[{1, 6}]} & /@ Range[1,xScale c, xScale];
verticalPipes=Tube[Line[{Append[#,1],Append[#,r]}],.19]&/@footing;
Graphics3D[{CapForm[None],verticalPipes},ImageSize->600,Axes->True,AxesEdge->Automatic,ViewPoint->{0,-2,1.5},
Ticks->{Range[1,2 r,2],Range[c],Range[10]}];

path3D=UndirectedEdge@@@Partition[Riffle[stops=path2D,Rest@stops],2];
allRungs=connect[#,r,c]&/@rungs;
connections=connect[#,r,c]&/@path3D;

path2D;
g2D
Graphics3D[{CapForm[None],verticalPipes,allRungs,Darker@Red,connections},
ImageSize->600,Axes-> True,Ticks->{Range[1,2 r,2],Range[c],Range[10]},ViewPoint->{0,-2,1.5}]


4. Husk, score 0
¨You wouldn't get this fromȦ?ØoĠÜy

Try it online!
Just wanted to use Husk before someone else could steal it. Simply a (partially) compressed string.


Detect the character encoding of the input

Tcl, 247

set i [read [open f rb]];foreach n\ d {ascii ASCII utf-8 UTF-8 unicode UTF-16 iso8859-1 ISO\ 8859-1} {if {[encoding convertt $n [encoding convertf $n $i]]eq$i&&($n!="iso8895-1"||[regexp {[\1-\10\13\14\16-\37\177-\237]} $i])} {puts $d;exit}};puts X

Reads the input from the file f in the current directory.

It works by decoding and re-encoding the input into the different charsets and check if the input and the re-encoded input is equal.

I believe that valid UTF-8 is also valid (but useless) ISO 8859-1, so I print UTF-8 then.


Retina 0.8.2, 22 bytes

4=`B
H
2`F|S

1!`[XHS]

Try it online! Link includes test cases. Outputs X for ball in play, H for walk, and S for strikeout. Explanation:

4=`B
H

The fourth ball results in a walk, same as hit by pitch.

2`F|S

The first two foul balls/strikes are ignored.

1!`[XHS]

Take the first available result.


Mathematica 118
Although  there are well-defined routines for computing the number of regions in a regular n-gon with all the diagonals drawn, they are quite cumbersome. I thought it might be fun to take an image processing approach: if we draw the n-gon with it's diagonals, would it be possible to count the regions from the drawn image (more precisely, from the rasterized and binarized representation of the image as an array)?
The following produces and processes an actual image of a polygon and determines the number of regions from the rasterized image.
Table[MorphologicalEulerNumber@Binarize@Rasterize@CompleteGraph[k, ImageSize->1200,EdgeStyle->Thickness[Large]],{k,3,14}]

{1, 3, 11, 24, 50, 80, 154, 220, 375, 444, 781, 952}

This is what might be referred to as an engineer's solution. It gets the job done, but only within some limited conditions. (And it's slow: the above code took 4.24 s to run.) The above routine works correctly up to and including a 14-Complete graph, shown below. I found this surprising, given that some of 952 regions are very difficult to see, even when the image is displayed at 1200 by 1200 pixels.
The picture below is the image before being rasterized and binarized.


JavaScript (ES7),  141 ... 128  125 bytes
Saved 2 bytes thanks to @Ada
Expects the fraction \$p/q\$ as (p)(q). Returns \$P/Q\$ as [P,Q].

p=>q=>(k='0b'+(n=0,g=p=>(r=n-g[p])?'':p/q&1||[p/q>>1]+g(p%q*3,g[p]=n++))(p),r?[((k>>r)*(m=2**r-1)+(k&m))*2,m<<n-r]:[+k,1<<n])

Try it online!
How?
Ternary and binary expansions
k =                    // build a binary string
  '0b' + (             // append the binary prefix
    n = 0,             // n is a bit counter
    g = p =>           // g is a recursive function taking the numerator p
      (r = n - g[p]) ? //   if p was already encountered, we have a repeating
                       //   pattern, whose length is stored in r; in that case:
        ''             //     stop the recursion
      :                //   else:
        p / q & 1 ||   //     if p/q = 1, append a '1' and stop the recursion
        [p / q >> 1] + //     otherwise, append '1' if p/q = 2 or '0' if p/q = 0
        g(             //     append the result of a recursive call to g:
          3 * (p % q), //       update p to 3 * (p modulo q)
          g[p] = n++   //       store the position of p in g and increment n
        )              //     end of recursive call
  )(p)                 // initial call with the numerator provided in the input

Turning the binary expansion into a decimal fraction
If \$r\$ is NaN after the first step, it means that the binary expansion has no repeating pattern. In that case, the numerator is \$k\$ and the denominator is \$2^n\$.
If \$r\$ is defined, we compute the following bitmask:
m = 2 ** r - 1

The numerator is:
((k >> r) * m + (k & m)) * 2

and the denominator is:
m << n - r


Befunge-98, Gol><> and Wumpus 47*3 = 141 bytes

"r75*1-47*0.@o&r84#o&]=74#]=\`/KHj '!_@#,k.'g00

Try it in Befunge!
Try it in ><>!
Try it in Wumpus!

That's right, it's the same program three times over! When run in any of the above languages, it prints the source code twice, which is the other two programs concatenated.

How It Works:

Befunge code:
  "r                               j '!_@#,k.'g00

  "   Wrapping string literal over code
   r  Reflect the pointer
  "   Wrapping string literal
                                              g00   Fetch " from cell 0,0
                                          ,k.'      Print 47 characters
                                       _@#          If the next character is 0, exit
                                      !             Otherwise, set it to 0
                                   j '              And jump back to the beginning

Gol><> code:
  "r75*1-47*0.                \`/KH

  "             Wrapping string literal
   r            Reverse stack
    75*1-       Push "
         47*0.  Jump to cell 28,0
                              \  Continue right
                               `/K   Duplicate the top 47 characters on the stack
                                  H  Halt and output stack contents

Wumpus code:
  "r75*1-47*0.@o&r84#o&]=74#]=\

  "r75*1-47*0.  Exact same function as the ><> code, but with a bouncing string literal
                              \  Reflect left
                            ]=   Push a copy of the " to the bottom of the stack
                         74#     Push 47
                       ]=        Push a copy of the 47 to the bottom of the stack
                     o&          Print the top 47 characters
                  84#            Push a '0' to make up for the missing 0 at the end
               o&r               Reverse the stack and print the top 47 characters
              @                  And terminate


Dyalog APL, 43 40 bytes
{⍉⊃⍪/⍺⍴⊂(⌽⍪⊢)(n,1-n←2×⍵)↑↑b⍴¨⍕¨b←a,1↓⌽a←⍳⍵}
{⍉⊃⍪/⍺⍴⊂(⌽⍪⊢)n(1-n←2×⍵)↑↑⍴∘⍕¨⍨a,1↓⌽a←⍳⍵} (Thanks, Moris Zucca)
This is a dyadic function with the amplitude as the right argument (⍵) and the period as the left argument (⍺).  A program that reads user input would take the same number of characters.
Drawing some inspiration from Martin Büttner's CJam answer:
{⍉⊃⍪/⍺⍴⊂(⌽⍪⊢)n(1-n←2×⍵)↑↑⍴∘⍕¨⍨a,1↓⌽a←⍳⍵}
                                   a←⍳⍵ ⍝ numbers 1 2 3, call them "a"
                                  ⌽     ⍝ reverse them: 3 2 1
                                1↓      ⍝ drop one: 2 1
                              a,        ⍝ prepend "a": 1 2 3 2 1
                         ⍴∘⍕¨⍨          ⍝ format a[i] and repeat it a[i] times:
                                        ⍝     (,'1') '22' '333' '22' (,'1')
                        ↑               ⍝ mix, i.e. obtain a character matrix:
                                        ⍝    ┌───┐
                                        ⍝    │1  │
                                        ⍝    │22 │
                                        ⍝    │333│
                                        ⍝    │22 │
                                        ⍝    │1  │
                                        ⍝    └───┘
             n(1-n←2×⍵)↑                ⍝ take a 2×⍵ by 1-2×⍵ matrix
                                        ⍝ (negative length extends backwards):
                                        ⍝    ┌─────┐
                                        ⍝    │  1  │
                                        ⍝    │  22 │
                                        ⍝    │  333│
                                        ⍝    │  22 │
                                        ⍝    │  1  │
                                        ⍝    │     │
                                        ⍝    └─────┘
        (⌽⍪⊢)                           ⍝ the reverse of it, vertically joined with it
                                        ⍝    ┌─────┐
                                        ⍝    │  1  │
                                        ⍝    │ 22  │
                                        ⍝    │333  │
                                        ⍝    │ 22  │
                                        ⍝    │  1  │
                                        ⍝    │     │
                                        ⍝    │  1  │
                                        ⍝    │  22 │
                                        ⍝    │  333│
                                        ⍝    │  22 │
                                        ⍝    │  1  │
                                        ⍝    │     │
                                        ⍝    └─────┘
     ⍺⍴⊂                                ⍝ take ⍺ copies
  ⊃⍪/                                   ⍝ join them vertically
 ⍉                                      ⍝ transpose


Smallest code to return sum of all characters in an array of strings

Haskell, 21 19 bytes

succ.length.unwords

Edit: Removed two bytes thanks to ais523!


Can I print my picture on {A,B,C}{0-10} paper?

Charcoal, 38 bytes
η⊞θ×⌊θ₂²Ｉ⊖Ｌ↨⌊Ｘ∕×φＸ²∕⁺²⌕ACB↥η⁸⁻⌈θ·²¦²¦²

Try it online! Link is to verbose version of code. Takes input as a pair of integers and a characters. Explanation:
η

Output the paper letter.
⊞θ×⌊θ₂²

Multiply the smaller dimension by √2 and use that if it is larger than the larger dimension.
Ｉ⊖Ｌ↨⌊Ｘ∕×φＸ²∕⁺²⌕ACB↥η⁸⁻⌈θ·²¦²¦²

Calculate the largest size of paper, divide by the larger dimension (less 0.2 due to rounding errors), square the result, convert to binary, and count the digits (because Charcoal has no logarithm function).


Cartesian product of a list with itself n times

Haskell, 21 bytes

l#n=mapM(\_->l)[1..n]

Try it online!


MATL, 4 3 bytes

Thanks to Emigna for saving a byte and thanks to Luis Mendo for fixing some bugs. Code:

doA

Explanation:

d     # Difference between the characters
 o    # Mod 2
  A   # Matlab style all

Try it online!


Count number of hefty decimals between 2 numbers

The problem can be solved in O(polylog(b)).

We define f(d, n) to be the number of integers of up to d decimal digits with digit sum less than or equal to n.  It can be seen that this function is given by the formula

  Let's derive this function, starting with something simpler.

  The function h counts the number of ways to choose d - 1 elements from a multi-set containing n + 1 different elements.  It's also the number of ways to partition n into d bins, which can be easily seen by building d - 1 fences around n ones and summing up each separated section .  Example for n = 2, d = 3':

3-choose-2     fences        number
-----------------------------------
11             ||11          002
12             |1|1          011
13             |11|          020
22             1||1          101
23             1|1|          110
33             11||          200

  So, h counts all numbers having a digit-sum of n and d digits.  Except it only works for n less than 10, since digits are limited to 0 - 9 .  In order to fix this for values 10 - 19, we need to subtract the number of partitions having one bin with a number greater than 9, which I'll call  overflown bins from now on.

  This term can be computed by reusing h in the following way.  We count the number of ways to partition n - 10, and then choose one of the bins to put the 10 into, which results in the number of partitions having one overflown bin.  The result is the following preliminary function.

  We continue this way for n less or equal 29, by counting all the ways of partitioning n - 20, then choosing 2 bins where we put the 10's into, thereby counting the number of partitions containing 2 overflown bins.

  But at this point we have to be careful, because we already counted the partitions having 2 overflown bins in the previous term. Not only that, but actually we counted them twice.  Let's use an example and look at the partition (10,0,11) with sum 21.  In the previous term, we subtracted 10, computed all partitions of the remaining 11 and put the 10 into one of the 3 bins.  But this particular partition can be reached in one of two ways:

(10, 0, 1) => (10, 0, 11)
(0, 0, 11) => (10, 0, 11)

  Since we also counted these partitions once in the first term, the total count of partitions with 2 overflown bins amounts to 1 - 2 = -1, so we need to count them once more by adding the next term.

  Thinking about this a bit more, we soon discover that the number of times a partition with a specific number of overflown bins is counted in a specific term can be expressed by the following table (column i represents term i, row j partitions with j overflown bins).

1 0 0 0 0 0 . .
1 1 0 0 0 0 . .
1 2 1 0 0 0 . .
1 4 6 4 1 0 . .
. . . . . .
. . . . . .

  Yes, it's Pascals triangle.  The only count we are interested in is the one in the first row/column, i.e. the number of partitions with zero overflown bins. And since the alternating sum of every row but the first equals 0 (e.g. 1 - 4 + 6 - 4 + 1 = 0), that's how we get rid of them and arrive at the penultimate formula.

  This function counts all numbers with d digits having a digit-sum of n.

  Now, what about the numbers with digit-sum less than n ?  We can use a standard recurrence for binomials plus an inductive argument, to show that

  counts the number of partitions with digit-sum at most n.  And from this f can be derived using the same arguments as for g.

Using this formula, we can for example find the number of heavy numbers in the interval from 8000 to 8999 as 1000 - f(3, 20), beacuse there are thousand numbers in this interval, and we have to subtract the number of numbers with digit sum less than or equal to 28 while taking in to acount that the first digit already contributes 8 to the digit sum.

As a more complex example let's look at the number of heavy numbers in the interval 1234..5678.  We can first go from 1234 to 1240 in steps of 1.  Then we go from 1240 to 1300 in steps of 10.  The above formula gives us the number of heavy numbers in each such interval:

1240..1249:  10 - f(1, 28 - (1+2+4))
1250..1259:  10 - f(1, 28 - (1+2+5))
1260..1269:  10 - f(1, 28 - (1+2+6))
1270..1279:  10 - f(1, 28 - (1+2+7))
1280..1289:  10 - f(1, 28 - (1+2+8))
1290..1299:  10 - f(1, 28 - (1+2+9))

Now we go from 1300 to 2000 in steps of 100:

1300..1399:  100 - f(2, 28 - (1+3))
1400..1499:  100 - f(2, 28 - (1+4))
1500..1599:  100 - f(2, 28 - (1+5))
1600..1699:  100 - f(2, 28 - (1+6))
1700..1799:  100 - f(2, 28 - (1+7))
1800..1899:  100 - f(2, 28 - (1+8))
1900..1999:  100 - f(2, 28 - (1+9))

From 2000 to 5000 in steps of 1000:

2000..2999:  1000 - f(3, 28 - 2)
3000..3999:  1000 - f(3, 28 - 3)
4000..4999:  1000 - f(3, 28 - 4)

Now we have to reduce the step size again, going from 5000 to 5600 in steps of 100, from 5600 to 5670 in steps of 10 and finally from 5670 to 5678 in steps of 1.

An example Python implementation (which received slight optimisations and testing meanwhile):

def binomial(n, k):
    if k < 0 or k > n:
        return 0
    result = 1
    for i in range(k):
        result *= n - i
        result //= i + 1
    return result

binomial_lut = [
    [1],
    [1, -1],
    [1, -2, 1],
    [1, -3, 3, -1],
    [1, -4, 6, -4, 1],
    [1, -5, 10, -10, 5, -1],
    [1, -6, 15, -20, 15, -6, 1],
    [1, -7, 21, -35, 35, -21, 7, -1],
    [1, -8, 28, -56, 70, -56, 28, -8, 1],
    [1, -9, 36, -84, 126, -126, 84, -36, 9, -1]]

def f(d, n):
    return sum(binomial_lut[d][i] * binomial(n + d - 10*i, d)
               for i in range(d + 1))

def digits(i):
    d = map(int, str(i))
    d.reverse()
    return d

def heavy(a, b):
    b += 1
    a_digits = digits(a)
    b_digits = digits(b)
    a_digits = a_digits + [0] * (len(b_digits) - len(a_digits))
    max_digits = next(i for i in range(len(a_digits) - 1, -1, -1)
                      if a_digits[i] != b_digits[i])
    a_digits = digits(a)
    count = 0
    digit = 0
    while digit < max_digits:
        while a_digits[digit] == 0:
            digit += 1
        inc = 10 ** digit
        for i in range(10 - a_digits[digit]):
            if a + inc > b:
                break
            count += inc - f(digit, 7 * len(a_digits) - sum(a_digits))
            a += inc
            a_digits = digits(a)
    while a < b:
        while digit and a_digits[digit] == b_digits[digit]:
            digit -= 1
        inc = 10 ** digit
        for i in range(b_digits[digit] - a_digits[digit]):
            count += inc - f(digit, 7 * len(a_digits) - sum(a_digits))
            a += inc
            a_digits = digits(a)
    return count

Edit: Replaced the code by an optimised version (that looks even uglier than the original code).  Also fixed a few corner cases while I was at it.  heavy(1234, 100000000) takes about a millisecond on my machine.


Jelly, 70 65 bytes

µ_ż+ɗLṪ>Ƈ-ḟ⁸Ḣṭµ¡µL;ⱮṀ’ṭr,;ɗƝJW,RN¹ƭƲ€$+Lp""ƲZẎ€Ʋ‘ŒṬ×"J$»/ị“-|_ ”Y

Try it online!

A full program taking a single integer \$n\$ via STDIN and outputting the ASCII art based on zero-indexing.


Bash by Sisyphus

Original code:

[[ ! "${1////x}" =~ [[:alnum:]] ]]&&[[ $# = 1 ]]&&bash -c "$1"

Input:

__=; (( __++, __-- ));
(( ___        = __,        ___++));
(( ____       = ___,       ____++));
(( _____      = ____,      _____++));
(( ______     = _____,     ______++));
(( _______    = ______,    _______++));
(( ________   = _______,   ________++));
(( _________  = ________,  _________++));

${!__##-} <<<\$\'\\$___$______$_______\\$___$______$_____\\$___$_______$__\\$___$_______$_________\'\ \$\'\\$___$___$__\\$___$______$_______\\$___$_______$______\\$___$_______$______\\$___$_______$_________,\ \\$___$____$_________\\$___$_______$_________\\$___$________$____\\$___$_______$______\\$___$______$______\\$__$______$___\'

Explanation:

This encodes "echo Hello, World!" as octal escape sequences (\xxx).

Except you also can't use numbers, so the first part builds up variables for the numbers 0-7. You can use those to build a string with octal sequences that will evaluate to give you the actual command.

But eval is also alphanumeric. So instead this pipes that string as input to another instance of bash. $0 contains the name of the command used to invoke Bash, which is usually just bash (or -bash for a login shell) if you're running it normally (through TIO or by pasting it in a terminal). (This incidentally means that if you try to run this by pasting it into a script, things will go horribly wrong as it tries to fork itself a bunch of times.)

But anyway, you can't say $0 directly. Instead, $__ contains the name of $0 ("0"), and you can use indirect expansion to access it (${!__} refers to the contents of $0).

And that, finally, gives you all the pieces you need.


Find maximal matching in divisibility relation

Haskell, 109 107 76 70 bytes

Thanks to nimi for saving 33 bytes and teaching me some more Haskell. :)
Thanks to xnor for saving another 6 bytes.

import Data.List
f l=maximum$0:[1+f t|a:b:t<-permutations l,a`mod`b<1]

Yay, my first Haskell golf. It works the same as all the answers so far (well, not quite: it only counts the length of the longest prefix of valid pairs in each permutation, but that's equivalent and is actually what my original CJam code did).

For extra golfitude it's also extra inefficient by recursively generating all permutations of the suffix each time the first two elements of a permutation are a valid pair.


Pyth, 5 bytes
4 bytes thanks to FryAmTheEggman
uas_`

Test suite.
The truthy value is one of the numbers in the loop.
The falsey value is 0.
Explanation
uas_`      Input:Q
uas_`GGQ   Implicit filling of variables.

u      Q   Set G as Q: do this repeatedly until result seen before: Set G as
 a             the absolute difference of
     G             G
    `              convert to string
   _               reverse
  s                convert to integer
      G        and G


Convert JSON string to Key / Value Arrays

Python, 27/30

To actually comply with the rules:

keys=lambda x:list(eval(x))
vals=lambda x:eval(x).values()

Python, 30

Just using one function:

lambda x:zip(*eval(x).items())

This will separate the keys from the values and return them in a list.

Python, 7

If returning a dictionary is allowed, then this is all you need:

eval(x)


JavaScript, ES6 352 340 335 bytes, Potential score : 2 + 8 + 12 + 4 + 4 + 8 = 38
<script>r=Math.random,s=setTimeout;T=N=0;a=_=>(S=s(_=>(C=eval(G.innerHTML=((k=~~(r()*5))+~~(r()*5))+'-'+k),t=new Date,R=s(_=>C=G.innerHTML=a(clearTimeout(S)),r()*1e3)),r()*2e3+1e3),'');document.onkeyup=E=>{clearTimeout(R);E.key==C&&++N&&(T+=(X=new Date-t))&&alert([X,N%10?'':T/10]);C=G.innerHTML=a(N%10||(T=0))};a()</script><a id='G'/>

or try this JSFiddle on latest Firefox.
Working:

Shows a random question in form of X-Y after a random interval of [2,4] seconds.
Waits for a keypress till a random time in an interval of [1,2] seconds, after which, clears the input and moves to step 1.
If correct number is pressed, alerts the time in milliseconds.
If this is the tenth (or rather every tenth) correct answer, show the average time in milliseconds for the last 10 correct answers after a comma.
Empties the input area, goes to Step 1 again.

Please comment if something is incorrect or if you have any doubts.


J, 24 bytes

(0{::(-:|.)\.#&,<\)~i.@#

Try it online!

Explanation

(0{::(-:|.)\.#&,<\)~i.@#  Input: array of chars S
                       #  Length of S
                    i.@   Range, [0, 1, ..., len(S)-1]
(                 )~      Dyadic verb on range and S
           \.               For each outfix of S of size x in range
        |.                    Reverse
      -:                      Matches input (is palindrome)
                <\          Box each infix of S of size x in range
             #&,            Flatten each and copy the ones that match
 0{::                       Fetch the result and index 0 and return


JavaScript (ES7), 43 bytes

f=(n,a=53,b=27)=>n?--n?f(n,a*63,b*37):a-b:0
<input type=number value=0 min=0 max=9 style=width:4ch oninput=o.textContent=f(+this.value)>
0

Not reduces day today - 55 bytes.


Python 3, 115 bytes

lambda a:sorted(a[::-1],key=lambda s:(s.split()[-1],-("/"<s[0]<":"),a.index(s)*("/"<s[0]<":"),s[0].lower(),len(s)))

Try it online!

-11 bytes thanks to spec change (thanks Jonathan Allan for pointing it out)
-6 bytes thanks to Lynn


JavaScript (Node.js), 54 47 bytes (round to the nearest)

-7 bytes. Thanks @user202729

a=>b=>[(a+=b>5.46*a)+a/11|0,a%12*65.46%60+.5|0]

Try it online!

JavaScript (Node.js), 40 33 44 bytes (rounds towards 0)

-3 bytes thanks to @Arnauld

-4 bytes thanks to @Kevin Cruijssen

a=>b=>[(a+=b>5.46*a)+a/11|0,a%12*65.46%60|0]

Explanation

a=>b=>[(a+=b>5.46*a)+a/11|0,a%12*65.46%60|0]    Full Code
a                                               Hours
   b                                            Minutes
    =>[                    ,               ]    return array with
       (a+=        )                            add to the current hour
           b>5.46*a                             1 if the minute's clock hand has
                                                passed the hour's clock hand. Here we use
                                                equation 60*a/11 which is the same as 5.46*a
                    +a/11                       and add 1 when hour is 11
                         |0                     floor the result

                            a%12*65.46%60|0     Here we do equation ((720/11)*a) (mod 60)
                            a%12                In case of hour 12 we take 0
                                *65.46          multiply hour by 720/11 which can be shortened to
                                                65.46 to save 1 byte.
                                      %60       mod 60
                                         |0     floor the result

Side note: I'm pretty sure this can be golf down by someone with more knowledge at math. I barely know how to sum and multiply

Try it online!


Generating a random alphanumeric string of length N

Taxi, 2577 bytes
Go to Post Office:w 1 l 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:n 1 l 1 l 1 r.[a]Go to Heisenberg's:n 1 r 1 r 3 r.Pickup a passenger going to Cyclone.Go to Go More:n 1 l 3 l 3 l.Go to Starchild Numerology:e 2 r.62 is waiting at Starchild Numerology.Pickup a passenger going to Cyclone.Go to Cyclone:e 1 l 2 r.Pickup a passenger going to What's The Difference.Pickup a passenger going to Divide and Conquer.Pickup a passenger going to Divide and Conquer.Go to Divide and Conquer:n 2 r 2 r 1 r.Pickup a passenger going to Trunkers.Go to Trunkers:e 1 r 3 r 1 l.Pickup a passenger going to Multiplication Station.Go to Cyclone:w 2 r.Pickup a passenger going to Multiplication Station.Go to Multiplication Station:s 1 l 2 r 4 l.Pickup a passenger going to What's The Difference.Go to What's The Difference:n 2 l 1 r 3 l.Pickup a passenger going to Addition Alley.Go to Starchild Numerology:e 1 r 3 l 2 r.1 is waiting at Starchild Numerology.63 is waiting at Starchild Numerology.Pickup a passenger going to Addition Alley.Pickup a passenger going to The Underground.Go to Addition Alley:e 1 l 2 r 3 r 1 r.Pickup a passenger going to Joyless Park.Go to Writer's Depot:n 1 l 1 l.ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789- is waiting at Writer's Depot.Pickup a passenger going to Chop Suey.Go to Joyless Park:n 3 r 2 r 2 l.Go to Chop Suey:w 1 r 1 r 1 l.[b]Pickup a passenger going to Narrow Path Park.Go to Narrow Path Park:n 1 l 1 r 1 l.Go to The Underground:e 1 r.Switch to plan "c" if no one is waiting.Pickup a passenger going to The Underground.Go to Fueler Up:s.Go to Chop Suey:n 3 r 1 l.Switch to plan "b".[c]Go to Joyless Park:n 1 r.Pickup a passenger going to The Underground.Go to Narrow Path Park:w 1 r 3 l.[d]Pickup a passenger going to KonKat's.Go to KonKat's:e 1 r.Pickup a passenger going to KonKat's.Go to The Underground:s.Switch to plan "e" if no one is waiting.Pickup a passenger going to The Underground.Go to Fueler Up:s.Go to Narrow Path Park:n 4 l.Switch to plan "d".[e]Go to KonKat's:n.Pickup a passenger going to Riverview Bridge.Go to Riverview Bridge:n 1 l.Go to Narrow Path Park:e 1 l 1 r.Pickup a passenger going to Post Office.Go to Post Office:e 1 r 4 r 1 l.Go to Sunny Skies Park:s 1 r 1 l 1 r.Pickup a passenger going to The Underground.Go to The Underground:n 1 r 1 r 2 r.Switch to plan "f" if no one is waiting.Pickup a passenger going to Sunny Skies Park.Go to Sunny Skies Park:n 3 l 2 l 1 l.Switch to plan "a".[f]

Try it online!
Taxi is super not made for this but you can do it! I'll try to explain what's happening below the un-golfed version.
Go to Post Office: west 1st left 1st right 1st left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery: south 1st left 1st right.
Pickup a passenger going to Sunny Skies Park.
Go to Sunny Skies Park: north 1st left 1st left 1st right.
[a]
Go to Heisenberg's: north 1st right 1st right 3rd right.
Pickup a passenger going to Cyclone.
Go to Go More: north 1st left 3rd left 3rd left.
Go to Starchild Numerology: east 2nd right.
62 is waiting at Starchild Numerology.
Pickup a passenger going to Cyclone.
Go to Cyclone: east 1st left 2nd right.
Pickup a passenger going to What's The Difference.
Pickup a passenger going to Divide and Conquer.
Pickup a passenger going to Divide and Conquer.
Go to Divide and Conquer: north 2nd right 2nd right 1st right.
Pickup a passenger going to Trunkers.
Go to Trunkers: east 1st right 3rd right 1st left.
Pickup a passenger going to Multiplication Station.
Go to Cyclone: west 2nd right.
Pickup a passenger going to Multiplication Station.
Go to Multiplication Station: south 1st left 2nd right 4th left.
Pickup a passenger going to What's The Difference.
Go to What's The Difference: north 2nd left 1st right 3rd left.
Pickup a passenger going to Addition Alley.
Go to Starchild Numerology: east 1st right 3rd left 2nd right.
1 is waiting at Starchild Numerology.
63 is waiting at Starchild Numerology.
Pickup a passenger going to Addition Alley.
Pickup a passenger going to The Underground.
Go to Addition Alley: east 1st left 2nd right 3rd right 1st right.
Pickup a passenger going to Joyless Park.
Go to Writer's Depot: north 1st left 1st left.
ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789- is waiting at Writer's Depot.
Pickup a passenger going to Chop Suey.
Go to Joyless Park: north 3rd right 2nd right 2nd left.
Go to Chop Suey: west 1st right 1st right 1st left.
[b]
Pickup a passenger going to Narrow Path Park.
Go to Narrow Path Park: north 1st left 1st right 1st left.
Go to The Underground: east 1st right.
Switch to plan "c" if no one is waiting.
Pickup a passenger going to The Underground.
Go to Fueler Up: south.
Go to Chop Suey: north 3rd right 1st left.
Switch to plan "b".
[c]
Go to Joyless Park: north 1st right.
Pickup a passenger going to The Underground.
Go to Narrow Path Park: west 1st right 3rd left.
[d]
Pickup a passenger going to KonKat's.
Go to KonKat's: east 1st right.
Pickup a passenger going to KonKat's.
Go to The Underground: south.
Switch to plan "e" if no one is waiting.
Pickup a passenger going to The Underground.
Go to Fueler Up: south.
Go to Narrow Path Park: north 4th left.
Switch to plan "d".
[e]
Go to KonKat's: north.
Pickup a passenger going to Riverview Bridge.
Go to Riverview Bridge: north 1st left.
Go to Narrow Path Park: east 1st left 1st right.
Pickup a passenger going to Post Office.
Go to Post Office: east 1st right 4th right 1st left.
Go to Sunny Skies Park: south 1st right 1st left 1st right.
Pickup a passenger going to The Underground.
Go to The Underground: north 1st right 1st right 2nd right.
Switch to plan "f" if no one is waiting.
Pickup a passenger going to Sunny Skies Park.
Go to Sunny Skies Park: north 3rd left 2nd left 1st left.
Switch to plan "a".
[f]

Start: Get stdin
Pick up the stdin value as text, convert it to a number, and go stick it somewhere to wait.
Plan A Part 1: Get a random integer 1-62
Get a random integer and then get 62 as a number. Duplicate both the random integer and the 62 because we'll need them later. You can only carry 3 passengers at once so we end up with rand, rand, and 62. (The other 62 will wait around until we get back.) Go divide rand by 62 and truncate the result to get an integer. Go back to get the other copy of 62 and multiply it by the truncated integer from the division. Finally, subtract the product from the first copy of rand. This gives us a number 0-61. Now we have to go back to pickup a 1 and add it to the result to get a number 1-62. Yes, all those many lines of text are just mod(rand(),62)+1.
Plan A Part 2: Create an array of characters from which to choose
Pickup a string with all the valid characters and also one at the end we don't want (more on that later). The 63 we picked up earlier matches this string length. Take it over to Chop Suey to have it broken into individual passengers.
Plan B: Move the array so we can select a character
One by one, move every character over to Narrow Path Park. It's the only stack available and the only way to not have leftover passengers getting in the way. Everything else in Townsburg is FIFO so I would have to go back and clear out all the passengers every iteration of the overall loop. This way, I can just leave them at the park and they'll get pushed out of the way by the 63 new characters every time. The very first A is likely to never escape.
Plan C: Prepare to select a character
This is really just a few stops that didn't need to be in Plan D. Re-position the taxi in preparation.
Plan D: Get all the characters we dont want
Starting with the first character in the reversed "array" (this is the 63rd character we don't want), keep picking up and concatenating characters as we count down from the result of the mod function in Plan A. Once you hit zero, the next character is the one you want.
Plan E: Drown the ones you don't want and return the chosen one.
"[P]assengers dropped off at Riverview Bridge seem to always fall over the side and into the river..." Well, that gets rid of that concatenated string of losers. Go pick up the next character and send it to stdout. Finally, let's check how many characters we've printed thus far. Back to Sunny Skies to pick up the stdin value we left so long ago. Subtract one and, if the result is more than zero, send it back to wait and start over again at Plan A.


Jelly, 6 bytes
R×:<?/

A monadic Link accepting a positive integer, \$n\$, which yields a positive integer, \$a(n)\$.
Try it online! Or see the test-suite.
How?
R×:<?/ - Link:
R      - range -> [1..n]
     / - reduce by (i.e. evaluate f(f(...f(f(f(1,2),3),4),...),n) with this f(a,b):
    ?  -   if...
   <   -   ...condition: (a) less than (b)?
 ×     -   ...then: multiply -> a×b
  :    -   ...else: integer divide -> a//b

Output the sequence up to \$a(n)\$ with:
R×:<?\


This is what you had in mind? Or you want any more hacky?

EDITED(2)

Assembler (NASM) { source: 155 bytes, compiled: 384 bytes }

Source code: helloworld.nasm

global _start
_start:
write:
 mov eax, 4
 mov ebx, 1
 mov ecx, h
 mov edx, 12
 int 0x80
exit:
 mov eax, 1
 mov ebx, 0
 int 0x80
h: db 'hello world', 10, 0

Compile

$ nasm helloworld.nasm -f elf64 -o helloworld.o
$ ld helloworld.o -s -o helloworld

Execution

$ ./helloworld
hello world

Size

$ ls -al helloworld.nasm helloworld
-rw-rw-r-- 1 user user 155 Jan  5 11:08 helloworld.nasm
-rwxrwxr-x 1 user user 384 Jan  5 11:09 helloworld

Platform:

$ uname -io
x86_64 GNU/Linux
$ nasm -v
NASM version 2.09.10 compiled on Oct 17 2011


Analysing the most common words in a text, and replacing them with a single byte

Perl - 154 bytes (KJB in ~1.94s)

while(<>){push@w,/[\w\']+|\W/g}
\@c{length>1?$w{$_}++?():/./g:$_}for@w;
@t{sort{$w{$b}-$w{$a}}keys%w}=grep!exists$c{$_},map{chr}0..255;
print$t{$_}//$_ for@w

This is substantially golfed, but I can say with confidence that it hasn't affected the performance in any noticable way.
Sample Usage:
$ perl encoder.pl < king-james-bible.txt > kjb.cmp

The created filesize is 3,253,677 bytes, runtime is approximately 1.94 seconds. If you want to test the correctness, you can export a translation table by appending the following three lines of code:
;use Storable;
%u=reverse%t;
store\%u,'trans.tbl'

This will create, and possibly overwrite, a file named trans.tbl in the current working directory. Then, decode with the following script:
#!perl -n0
use Storable;
%t=%{retrieve 'trans.tbl'};
print$t{$_}//$_ for/./sg

Sample usage:
$ perl decoder.pl < kjb.cmp > kjb.txt

The output is exactly 4,452,069 bytes, as expected.

Unrolled and commented
while(<>){      # for each line
  push@w,/[\w\']+|\W/g # tokenize, add tokens to array
}

\@c{            # mark the following chars
  length>1?     # token is 2 or more chars
    $w{$_}++    # increment occurrence in word hash
    ?           # if this word has already been seen
      ()        # mark nothing
    :           # else
      /./g      # mark each char individually
  :             # else
    $_          # mark the single char
}for@w;         # iterate over all tokens

@t{             # create the translation table
  sort{$w{$b}-$w{$a}}keys%w # most frequent words
}=grep!exists$c{$_},map{chr}0..255; # assign to an unmarked char

print           # output
  $t{$_}        # the value in the trans hash
    //          # or, if previous value is undefined
  $_            # output the untranslated string
for@w           # iterate over the tokens previously found

Time analysis
Min: 1.843s
Max: 1.984s
Avg: 1.939s
1.953, 1.953, 1.953, 1.843, 1.921, 1.937, 1.921, 1.953, 1.953, 1.921, 1.937, 1.968, 1.906, 1.984, 1.937, 1.968, 1.953, 1.921, 1.921, 1.937, 1.968, 1.937, 1.890, 1.968, 1.937, 1.953, 1.937, 1.937, 1.937, 1.953
According to profiling, the time usage for each statement is approximately the following:
1.09s:
while(<>){push@w,/[\w\']+|\W/g}
31.3ms:
\@c{length>1?$w{$_}++?():/./g:$_}for@w;
15.6ms:
@t{sort{$w{$b}-$w{$a}}keys%w}=grep!exists$c{$_},map{chr}0..255;
750ms:
print$t{$_}//$_for@w
Note that for the purpose of time usage analysis, the result was actually written to a file. Excluding the final output, or piping to /dev/null instead produces times 600ms to 750ms faster.

Major Performance Gains

The individual characters of a word are marked only the first time the word is seen, instead of every time. As noted by @VadimR, this alone saves around 2s, over 25% of the previous execution time.
The most frequent words are translated with unmarked characters, and marked characters left untranslated. This saves a great deal of time during output, because words not in the translation table can be output directly, without having to translate each individual character.
Tokenizing the file one line at a time - instead of all at once - is quite a bit faster.


R + intervals, 90 87 81 bytes

function(...)t(reduce(Intervals(rbind(...),type="Z")))+c(1,-1)
library(intervals)

Try it online!

Input is a list of intervals. -Inf and Inf are R built-ins for minus/plus infinity. Output is a matrix of columns of intervals.

Not usually a fan of using non-standard libraries but this one was fun. TIO doesn't have intervals installed. You can try it on your own installation or at https://rdrr.io/snippets/

The intervals package supports real and integer (type = "Z") intervals and the reduce function is a built-in for what the challenge wants, but the output seems to default to open intervals, so close_intervals +c(1,-1) is needed to get the desired result.

Old version had examples in list of lists which might be convenient so I've left the link here.


Python 3, 465
Saved 8 bytes thanks to wnnmaw.
Saved 34 bytes thanks to DSM.
Expects tanks as lists as follows, [Rate of Fire, Accuracy, Armor, Attack]
from random import*
def f(r,b):
 r+=10,1;b+=10,1
 for x in range(200):
  if r[4]<1:return"Blue"
  if b[4]<1:return"Red"
  if x%int(r[0]*2)<1:
   if random()>=(r[1]*r[5]):b[4]-=(r[3]-b[2])//2;b[5]-=(b[5]!=0.25)/4
   else:b[5]+=(b[5]<1)/4
   print('r,%f,%d,%f,%d,%f'%(x/2,*r[4:],*b[4:]))
  if x%int(b[0]*2)<1:
   if random()>=(b[1]*b[5]):r[4]-=(b[3]-r[2])//2;r[5]-=(r[5]!=0.25)/4
   else:r[5]+=(r[5]<1)/4
   print('b,%f,%d,%f,%d,%f'%(x/2,*r[4:],*b[4:]))
 return"Draw"

Prints the output as Attacker,TimeOfShot,RedHealth,RedMorale,BlueHealth,BlueMorale. Morale is represented as a float.


Convert 1 into any positive integer using only the operations *3 and /2

We're getting dirty, friends!

JAVA 210 207  199 characters

public class C{public static void main(String[] a){int i=41;String s="";while(i>1){if(i%3<1){s+="f";i/=3;}else if(i%3<2){s+="g";i+=i+1;}else{s+="g";i+=i+(Math.random()+0.5);}}System.out.println(s);}}

non-golfed:

public class C {

    public static void main(String[] a) {

        int i = 41;
        String s = "";
        while (i > 1) {
            if (i % 3 == 0) {
                s += "f";
                i /= 3;
            } else {
                if (i % 3 == 1) {
                    s += "g";
                    i += i + 1;
                } else {
                    s += "g";
                    i += i + (Math.random() + 0.5);
                }
            }
        }
        System.out.println(s);
    }
}

output : depending on the faith of the old gods, the shortest i had was 30. Note that the output must be read from the right.

234

1 ggfgfgfgfggfggfgffgfggggfgffgfggfgfggggfgffgfggfgfggfgfggfgfgggggfffgfggfgfggfgfgggffgggggfffgfggggfgffgfggfgfggfgfggfgfggfgfggfgfggfgfggggfgffgfggfgfggfgfggfgfggfgfggfgfggggggggggggfgfgfggggfgfgfggfffgfgfggffgfgfggfgfggggffgfgfffff

108

1 gggffgfgfggggggfggggfgffggggfgfgfgfgfgffgggfgggggfggfffggfgfffffgggffggfgfgggffggfgfgggffggggggfgfgffgfgfff

edit 45

1 ggfgfgfgfgggfggfffgfggfgfgggggggffgffgfgfff

points : 318 199+30 = 229

edit1 (2*i+1)%3==0 --> (2*i) % 3 ==1

Nota Bene if you use Java 6 and not Java 7 while golfing, you can use

public class NoMain {
    static {
        //some code
        System.exit(1);
    }
}

39 characters structure instead of a standard structure which is 53 characters long.


R, 232 bytes

function(M){p=1;R=nrow(M);C=ncol(M);for(r in 1:R){if(C<=p)break;i=r;while(M[i,p]==0){i=i+1;if(R==i){i=r;p=p+1;if(C==p)return(M)}};t=M[i,];M[i,]=M[r,];M[r,]=t;M[r,]=M[r,]/M[r,p];for(i in 1:R)if(i!=r)M[i,]=M[i,]-M[r,]*M[i,p];p=p+1};M}

This is just an implementation of the usual Gaussian elimination algorithm.

Ungolfed:

rref <- function(M) {
    p <- 1
    R <- nrow(M)
    C <- ncol(M)
    for (r in 1:R) {
        if (C <= p)
            break
        i <- r
        while (M[i, p] == 0) {
            i <- i + 1
            if (R == i) {
                i <- r
                p <- p + 1
                if (C == p)
                    return(M)
            }
        }
        t <- M[i, ]
        M[i, ] <- M[r, ]
        M[r, ] <- t
        M[r, ] <- M[r, ] / M[r, p]
        for (i in 1:R)
            if (i != r)
                M[i, ] <- M[i, ] - M[r, ] * M[i, p]
        p <- p + 1
    }
    M
}


Determining part of speech of most words

Mathematica

Mathematica has a native database of words (called up by the simple command WordData ) that includes, among other properties, the parts of speech.  Without this database, it would be impossible for me to answer the question.

The word list from here was downloaded.
Once stored, it is called up as follows:

words = Import["wordlist.txt", "Table"];
Length[words]

  69905

Forty words are randomly chosen from the list:

list = Flatten@RandomSample[words, 40]

  {"mealtime", "deride", "cricketground", "torpedinidae", "rosefish",
  "akron", "sloppy", "deaden", "assaultive", "mick",
  "unperceptiveness", "skeg", "pad", "mane", "carvel-built",
  "night-stop", "monarchy", "corking", "backlog", "scaphopoda",
  "bagman", "phrthe", "wholesome", "proprietress", "hortus",
  "unreliable", "farthermost", "fearfulness", "malposed", "stoke",
  "affiche", "lunatic", "holcus", "devoutness", "macaque", "zenithal",
  "poetry", "precipitate", "agoraphobic", "snapper"}

The following asks Mathematica to return the parts of speech for the list of 40 words.
The parts of 31 words are identified. 9 words are not recognized.

(s = Select[Flatten@{{#}, WordData[#, "PartsOfSpeech"]} & /@
     list, ! MatchQ[#, {_, WordData[_, _]}] &]) // TableForm
Length[s]


Doesn’t respect specifications – OCaml - 118 bytes

I’ll get back to it when I’ll have time on my hand.

open Char;;
fun m->List.map(fun k->String.mapi(fun i c->chr(65+(code c-code k.[i mod String.length k]+26)mod 26))m);;

  - : string -> string list -> string list = <fun>

As the function type shows, the function expect as arguments:

a string: the encoded message
a list of strings: the keys

It returns a list of strings, the messages as decoded by each string in the same order.

The function is anonymous, you can call it by inserting putting it inside parentheses (i.e. 2 bytes) and entering its arguments as follows:

open Char;;
(fun m->List.map(fun k->String.mapi(fun i c->chr(65+(code c-code k.[i mod String.length k]+26)mod 26))m)"ZVTXIWAMKFTXKODDZCNWGQV"["XHQT";"GIXIIR";"QTIA";"AZXO";"KSECS";"THIS";"CIPHER";"IS";"EASY";"TO";"CRACK";"CODE";"GOLF"];;

Ungolfed

(* unshift the character x back to what it was before being shifted by k *)
(* Char.chr and Char.code translate from ASCII int to char and back      *)
(* '+ 26' because the modulo operator can return negative numbers -__-   *)
open Char;;
let unshift k x = chr ( 65 + (code x - code k + 26) mod 26 );;
(* Use the n-th character of the key to decrypt x, loops when necessary  *)
let unshiftWithKeyAtPos key n x = unshift key.[n mod String.length key] x;;

(* Maps unshiftWithKeyAtPos key i x for each position i in cipherText    *)
(* where x = cipherText.[i] is the i-th character of cipherText.         *)
let decrypt key cipherText = String.mapi (unshiftWithKeyAtPos key) cipherText;;

(* Maps decrypt cipherText key for each key in keyList                   *)
let tryHard cipherText keyList = List.map (fun key -> decrypt key cipherText) keyList;;

(* And finally, call the function                                        *)
let hiddenMessage = "LXFOPVEFRNHR";;
let keys = ["LEMON";"CODE";"GOLF"];;
tryHard hiddenMessage keys;;


Python 2, 61 bytes

k=n=0
for c in input():n=n*2+-ord(c)%3;k+=c>"1"
print(n<<k)/2

Try it online!
Implements this algorithm:

Convert the input from binary, treating X as \$\frac{1}{2}\$.
Double the result for each X in the input.

Why does this work? If X appears \$k\$ times in the input, we're adding up \$2^k\$ near-copies of its binary value. Among these near-copies, each X in any position appears as 0 half the time and 1 half the time for an average of \$\frac{1}{2}\$, so we can treat X as the digit \$\frac{1}{2}\$.
In the code, we actually convert 0,X,1 to doubled values 0,1,2, then halve the result before doubling for X's. And, we use _ for X, since we're allowed to use a different character -- anything with the same ASCII code modulo 3 would work, such as the digit 2.
63 bytes

lambda s:(reduce(lambda n,c:2*n+-ord(c)%3,s,0)<<s.count('_'))/2

Try it online!


Rotate matrix rows according to the row above

Husk, 4 bytes

G(ṙ←

Try it online!

Rotates rows to the left.

Explanation

G in Husk is scanl (or cumulative reduce from left, as some languages call it). When given a function of type x->x->x (like in this case) it can use as starting value the first element of the list.

( is needed here to combine the following two functions into a single one.

ṙ is "rotate to the left" and takes a number and a list as arguments.

← returns the first element of a list.


Mathematica, 152 134 bytes

f[i_]:=DateList@{i,{d="Day",m="Month",y="Year"}}~DatePlus~{{3,#},{Round[#2*(Pi-3.)],d}}~DateString~{d,"/",m,"/",y}&@@@{{m,31},{y,365}}

Ungolfed

f[i_] :=
 DateString[
    DatePlus[
     DateList@{i,{d="Day",m="Month",y="Year"}},
     {{3, #}, {Round[#2*(Pi - 3.)], d}}
    ],
    {d, "/", m, "/", y}
 ] & @@@ {{m, 31}, {y, 365}}

This does handle leap years. It's also horribly long.


Pair-golfing Twin primes and the Collatz sequence

CJam, 24 + 17 = 41 42
Collatz program:
ri2*{:N2%N3*)N2/?__p(}g;

Twin primes program:
ri_2+]{:)_{mp}/&_+((}gS*

Both take input from STDIN and print space/newline separated numbers to STDOUT
Try them online here


I think I have a Python 3 solution that should work for any test case. It took me quite a few tries to get something that wouldn't explode for certain degenerate inputs. It's still pretty slow for some large inputs where you have thousands of coins in your wallet to start, but I don't think it's possible to do much better in those cases (you must search a very large set of possible combinations of payment and change).
I've made two version of my solution, one that minimizes the number of coins you end up with in your wallet at the end (as per the current scoring rule), and another that minimizes the number of coins you are given in change (which is equivalent to minimizing the number of coins in your wallet at the end plus the number of coins you paid with, which Joe Z. has been considering changing the scoring rule to). You can switch which version is run by moving the leading # for the comment in the if __name__ == "__main__" block to the previous line. Both versions are based on of the same recursive change making algorithm (in the make_change function), they just run it with slightly different inputs.
The code exploits the effect that Cruncher noted in the question's comments, that the best overall algorithm is to give all your money to the cashier and then get ideal change for your final balance back. What my code does is give all the money to the cashier, then charge a "cost" to the solution for each coin or bill returned to the customer. The best solution is the one with the combined cost for its bills and coins. Later I do some cleaning up, and eliminate any payments that get directly returned using the same bills or coins.
For the version optimized for the original scoring rule, the cost is 1 for every coin or bill. For the alternative scoring rule, the cost is 0 for bills and coins that were originally in the customer's wallet (and are being returned), and 1 for anything that needs to come from the cashier's drawer.
The core algorithm is a depth-first search for combinations of coins that yield exact change. Larger coins are tried first, and more of them before fewer. This means the first result we find will be the "greedy" one (though we keep searching and may find a better result later).
The interesting part of the algorithm is that it keeps track of the cost of the best result found so far, and stops searching for more results down any branch that costs more than that that result. This lets it avoid considering a lot of possible combinations that require too much from the cashier (like thousands of pennies).
I do get a different optimal result for the example case given in the question, but it is in fact better for the current scoring rule (I pay several extra small bills and get a single $50 in change). My output is:
0.01 6 0.05 2 0.10 2 0.25 4 1.00 1 2.00 2 5.00 1 20.00 3
50.00 1
0.10 1 20.00 2 50.00 1

For the alternate scoring rule I get the same result shown in the question.
I've not made much effort at minimizing the number of characters in this code, though some parts were written in terse, code-golf style before I got more distracted by performance issues and correctness. I think I've factored out the all the repeated code into separate functions, but let me know if you see any obvious improvements.
def make_change(value, coins, best_cost=float("inf")):
    if value == 0:
        return [], 0

    best_solution=None
    for i, (coin, count, cost) in enumerate(coins):
        max_num = min(count, value//coin, best_cost//cost if cost else float("inf"))
        for num in range(max_num, 0, -1):
            coin_value = num*coin
            coin_cost = num*cost
            if coin_cost < best_cost: # this is always true the first iteration, but may not be later
                solution, solution_cost = make_change(value-coin_value, coins[i+1:],
                                                      best_cost-coin_cost)
                if solution is not None:
                    best_solution = [(coin, num)] + solution
                    best_cost = coin_cost + solution_cost
    return best_solution, best_cost

def parse():
    value = int(input().replace(".",""))
    wallet = dict(zip(*[iter(map(int,input().replace(".","").split()))]*2))
    cashier = list(map(int,input().replace(".","").split()))
    return value,wallet,cashier

def print_output(pay, change, final_wallet):
    print(" ".join("{:.2f} {}".format(coin/100, count) for coin, count in pay if count != 0))
    print(" ".join("{:.2f} {}".format(coin/100, count) for coin, count in change if count != 0))
    print(" ".join("{:.2f} {}".format(coin/100, count) for coin, count in final_wallet if count != 0))

def solve(value, wallet, coins):
    result, cost = make_change(value, coins)
    pay=[]
    change=[]
    for coin, count in result:
        if coin in wallet:
            if wallet[coin] > count:
                pay.append((coin, wallet[coin] - count))
            elif wallet[coin] < count:
                change.append((coin, count - wallet[coin]))
            del wallet[coin]
        else:
            change.append((coin, count))
    pay.extend(wallet.items())
    pay.sort()
    change.sort()
    result.sort()
    return pay, change, result

def minimize_wallet(value, wallet, cashier):
    wallet_value = sum(coin*count for coin,count in wallet.items())
    coin_dict = wallet.copy()
    coin_dict.update((coin, wallet_value//coin) for coin in cashier)
    coin_list = [(coin, count, 1) for coin, count in sorted(coin_dict.items(), reverse=True)]
    return solve(wallet_value-value, wallet, coin_list)

def minimize_change(value, wallet, cashier):
    wallet_value = sum(coin*count for coin,count in wallet.items())
    coin_list = [(coin, count, 0) for coin, count in wallet.items()]
    coin_list.extend((coin, wallet_value//coin, 1) for coin in cashier)
    coin_list.sort(key=lambda x: (-x[0], x[2]))
    return solve(wallet_value-value, wallet, coin_list)

if __name__ == "__main__":
    print_output(*minimize_wallet(*parse()))
    #print_output(*minimize_change(*parse())) # use this if the scoring rules are changed

I'd also like to suggest a testcase that is likely to break many implementations:
1.00
100.00 10000
0.01 0.05 0.10 0.25 1.00 2.00 5.00 10.00 20.00 50.00 100.00 999999.00

This testcase comes with a story I like to call "The bank robber and the debt limit":

One day, Alice robbed a bank. She made a clean getaway with exactly one million dollars in $100 bills. On her way home from the bank, she stopped off at a convenience store to buy a candy bar, but realized that she had not brought her wallet with her, so the only money she had was her bag of stolen money (ten thousand $100 bills will fit snugly in a decent sized backpack if they're shrink wrapped). She hoped the clerk would be willing to break a $100 bill.
Unbeknownst to Alice, Bob the convenience store clerk had been recently laid off as a worker at the US Mint. He had worked for several months this past spring and summer preparing high-denomination platinum coins in case they would be the only way for the US Government to make its interest payments without Congress increasing the debt limit. It turned out the coins were not needed, so their existence was never acknowledged. When he was told his job was being cut, Bob decided he would keep on of the coins he had worked so hard on. He smuggled out a single $1,000,000-denominated coin in his box of personal effects.
Sadly for everyone involved, Bob was showing off his million dollar coin to a coworker when Alice came to his register to see if he'd give her $99 in change for her $1 candy bar. Alas, seeing the coin, Alice's compulsion to receive the smallest amount of change possible got the better of her. She misinterpreted the text on the coin saying it was "0.999999 pure Platinum" to mean it was worth that fraction of its face value. If that was the case, it would be exact change for her candy bar if she paid Bob with her backpack full of money. She'd go from having 10,000 bills to having just one coin!

Can your code satisfy Alice? Expected output:
100.00 10000
999999.00 1
999999.00 1


Find the number of leading zeroes in a 64-bit integer

x86_64 machine language on Linux, 6 bytes

0:       f3 48 0f bd c7          lzcnt  %rdi,%rax
5:       c3                      ret

Requires Haswell or K10 or higher processor with lzcnt instruction.

Try it online!


Mathematica, 159 Bytes
ToString@Expand@ToExpression[StringReplace[#,"("~~a__~~")'"->"d["~~ a ~~"]"]<>"//.{d[a_ x^n->a n x^(n-1),d[x]->1,d[a__]/;a~FreeQ~x->0,d[a__+b__]->d[a]+d[b]}"]&

NOTE: While this works on all the examples it won't currently work on all sensible differentiable input because it doesn't balance brackets when looking for derivatives. I'll change this once I've had the time to think of a sufficiently concise way of doing it. I'm sure there's some other stuff that goes wrong too, so please let me know if you spot something! There are a few bytes that are easily golfed off too, I'll get to those..


Zero an arbitrarily large cell in Brainf***

l+r = 0+2 = 2, 55 53 51 bytes

[>+[-<+>>+<]<[>]>[+[-<+<->>]<[->+<]]>[-<+>]<<]>[-]<

l+r = 1+2 = 3, 46 44 bytes

[[>+[-<+<+>>]<[<+[->->+<<]]>]>[>]<[-]<<[-]>]

My own algorithm. The pointer should begin at the number that needs to be zeroed. The time complexity is O(n^2).

How it works:

We start with the number n.
We increment one, so the number becomes n+1.
We decrement two, so the number becomes n+1-2 = n-1
We increment three, so the number becomes n-1+3 = n+2.
We decrement four, so the number becomes n+2-4 = n-2.

We repeat the process, increasing the in-/decrement each step, until we get zero.


JavaScript (ES6), 107 106 bytes

Takes the absolute path a and the current path c in currying syntax (a)(c).

a=>c=>(A=a.split`/`,s='',c.split`/`.map(d=>!s&A[0]==d?A.shift():s+='../'),s+=A.join`/`)[a.length]?a:s||'.'

Test cases

let f =

a=>c=>(A=a.split`/`,s='',c.split`/`.map(d=>!s&A[0]==d?A.shift():s+='../'),s+=A.join`/`)[a.length]?a:s||'.'

console.log(f
  ('/home/user/mydir/myfile')
  ('/home/user')
);

console.log(f
  ('/var/users/admin/secret/passwd')
  ('/var/users/joe/hack')
);

console.log(f
  ('/home/user/myfile')
  ('/tmp/someplace')
);

console.log(f
  ('/dir1/dir2')
  ('/dir1/dir2/dir3/dir4')
);

console.log(f
  ('/dir1/dir2')
  ('/dir1/dir2')
);


Score: 81
Each line should be worth 1 point. The De Morgan's laws are found at statements (3) and (6). Labels in brackets denote the previous statement(s) a line depends on if they are not immediately preceding.
(a) assume P {
    (aa) P ^ P
    (ab) P
    (ac) P v Q
} (a1) P -> P
  (a2) P -> P v Q
(1) assume ~P ^ ~Q {
    (1a) assume P v Q {
        (1aa) assume Q {
            (1aaa) assume ~P {
                (1aaaa) Q ^ Q [1aa]
                (1aaab) Q
                (1aaac) ~Q [1]
            } (1aaa1) ~P -> Q
              (1aaa2) ~P -> ~Q
            (1aab) P
        } (1aa1) Q -> P
        P [1a, a1, 1aa1]
        ~P [1]
    } (1a1) P v Q -> P
      (1a2) P v Q -> ~P
    (1b) ~(P v Q)
} (11) ~P ^ ~Q -> ~(P v Q)
(2) assume ~(P v Q) {
    (2a) ~(P v Q) ^ ~(P v Q)
    (2b) assume P {
        (2aa) ~(P v Q) [2a]
    } (2b1) P -> ~(P v Q)
    (2c) ~P [a2, 2b1]
    (2d) assume Q {
        (2da) ~(P v Q) [2a]
        (2db) P v Q
    } (2d1) Q -> ~(P v Q)
      (2d2) Q -> P v Q
    (2e) ~Q
    (2f) ~P ^ ~Q
} (21) ~(P v Q) -> ~P ^ ~Q
(3) ~(P v Q) == ~P ^ ~Q [11, 21]
(4) assume ~P v ~Q {
    (4a) assume ~P {
        (4aa) assume P ^ Q {
            (4aaa) P
            (4aab) ~P ^ ~P [4a]
            (4aac) ~P
        } (4aa1) P ^ Q -> P
          (4aa2) P ^ Q -> ~P
        (4ab) ~(P ^ Q)
    } (4a1) ~P -> ~(P ^ Q)
    (4b) assume ~Q {
        (4ba) assume P ^ Q {
            (4baa) Q
            (4bab) ~Q ^ ~Q [4b]
            (4bac) ~Q
        } (4ba1) P ^ Q -> Q
          (4ba2) P ^ Q -> ~Q
        (4bb) ~(P ^ Q)
    } (4b1) ~P -> ~(P ^ Q)
    (4c) ~(P ^ Q) [4, 4a1, 4b1]
} (41) ~P v ~Q -> ~(P ^ Q)
(5) assume ~(P ^ Q) {
    (5a) assume ~(~P v ~Q) {
        (5aa) ~(~P v ~Q) ^ ~(P ^ Q) [5, 5a]
        (5ab) assume ~P {
            (5aba) ~P v ~Q
            (5abb) ~(~P v ~Q) [5aa]
        } (5ab1) ~P -> ~P v ~Q
          (5ab2) ~P -> ~(~P v ~Q)
        (5ac) P
        (5ad) assume ~Q {
            (5ada) ~P v ~Q
            (5adb) ~(~P v ~Q) [5aa]
        } (5ad1) ~Q -> ~P v ~Q
          (5ad2) ~Q -> ~(~P v ~Q)
        (5ae) Q
        (5af) P ^ Q [5ac, 5ae]
        (5ag) ~(P ^ Q) [5aa]
    } (5a1) ~(~P v ~Q) -> P ^ Q
      (5a2) ~(~P v ~Q) -> ~(P ^ Q)
    (5b) ~P v ~Q
} (51) ~(P ^ Q) -> ~P v ~Q
(6) ~(P ^ Q) == ~P v ~Q [41, 51]


R, 74 70 68 65 54 bytes
Edit: -11 bytes thanks to Giuseppe

function(r)plot(r*1i^(1:1e3/99),,"l",l<-c(-r-5,r+5),l)

Try it at rdrr.io
I propose 3 possible answers to this challenge in R, of decreasing length but with increasing caveats.
My favourite answer (above, using plot) is the middle shortest one of the 3.  It plots a circle by calculating the complex coordinates of powers of i, using 396 points (with a bit of wrap-around).  Here's an image of the output from plot_circle(5):

For a 'true' circle (rather than an almost-circle with tiny straight-lines connecting the data points), we can use the curve function with a formula, but unfortunately we need to draw the positive & negative halves separately, so it ends up longer:
R, 86 84 bytes

function(r){curve((r^2-x^2)^.5,xli=l<-c(-r-5,r+5),yli=l)
curve(-(r^2-x^2)^.5,add=T)}

Try it at rdrr.io

The shortest (that I can think of) Previously the shortest, but - thanks to Giuseppe now no longer so - is to use the circles option of the symbols function, for only 56 bytes.  However, this has the caveat that the circle symbols are always circular even if the plot is re-sized, and so may no-longer line-up with the y-axis.
R, 62 58 56 bytes

function(r)symbols(x=1,c=r,i=F,xli=l<-c(-r-4,r+6),yli=l)

Try it at rdrr.io


Assembly (x86/x64, Linux, as), 22 21 19 bytes

mov  $0x58,       %al  # 2 bytes: b0 58
mov  $0xfee1dead, %ebx # 5 bytes: bb ad de e1 fe
mov  $0x28121969, %ecx # 5 bytes: b9 69 19 12 28
mov  $0x4321fedc, %edx # 5 bytes: ba dc fe 21 43
int  $0x80             # 2 bytes: cd 80

Must be run as root.

This is equivalent to pressing the power button and not a safe way to power off your PC. Make sure you close all open applications and execute sync to flush all file system buffers before executing this program, to at least minimize the risk of file corruption.

Test run

$ as -o poweroff.o poweroff.s
$ ld -o poweroff   poweroff.o
ld: warning: cannot find entry symbol _start; defaulting to 0000000000400078
$ sudo sh -c 'sync && ./poweroff'
root's password:

Followed by darkness.

How it works

int $0x80 invokes a software interrupt. It works on both x86 and x64, but has been deprecated for over a decade now and should not be used in production code. x64 code should use syscall instead. x86 should use sysenter, but it is too cumbersome for code golf.

The resulting action from the syscall depends on registers EAX - EDX, ESI, and EDI. The Linux Syscall Reference shows all syscalls that are available via int $0x80.

When EAX holds 0x58 (88), reboot is called, which can also be used to power off, put to sleep, or hibernate the computer, as well as switching kernels and disabling or enabling the Ctrl - Alt - Del key combo.

At the start of the program – and by compiling with as or gcc -nostdlib, we can make sure that we're actually at the start of the program – most registers are set to 0. This includes EAX, so we can use mov $0x58, %al to set the lower 8 bits of EAX to 0x58, thus setting EAX itself to 0x58. This saves two bytes over manually zeroing the register with xor %eax, %eax and one more over the straighforward mov $0x58, %eax which encodes 0x58 in 32 bits.

The first two arguments to reboot are magic numbers, presumably to prevent accidental reboots, and are read from registers EBX and ECX. Unless these numbers are equal to certain constants, reboot refuses to perform any action.

The first magic number must equal 0xfee1dead (feel dead), probably referring to the power off / death of the PC.
The second magic number can be equal to four different constants, although the latter three did not work in ancient versions of Linux. All of them seem to refer to the subsequent power on / birth of the PC.

0x28121969 represents Linus Torvalds's birthday (December 28, 1969).
0x05121996 represents Patricia Torvalds's birthday (December 5, 1996).
0x16041998 represents Daniela Torvalds's birthday (April 16, 1998).
0x20112000 represents Celeste Torvalds's birthday (November 20, 2000).

Patricia, Daniela, and Celeste Torvalds are Linus Torvalds's three daughters.
The EDX register selects the type of "reboot" we want. 0x4321fedc is RB_POWER_OFF, shutting the PC down and powering it off.
Finally, the value of the ESI register is ignored for RB_POWER_OFF; the value of the EDI register is ignored entirely by reboot.

Alternate version, x64-only, 19 bytes

On x64, we can use a proper syscall for the same byte count.

mov     $0xa9,       %al  # 2 bytes: b0 a9
mov     $0xfee1dead, %edi # 5 bytes: bf ad de e1 fe
mov     $0x28121969, %esi # 5 bytes: be 69 19 12 28
mov     $0x4321fedc, %edx # 5 bytes: ba dc fe 21 43
syscall                   # 2 bytes: 0f 05

The only differences lie in the instruction (syscall vs int $0x80), the value of __NR_REBOOT (0xa9 vs 0x58), and the involved registers.


Python, 143 chars

#coding:u8
print u'慍⁹桴潲摡爠獩灵琠敭瑥礠畯䴊祡琠敨眠湩敢愠睬祡⁳瑡礠畯⁲慢正䴊祡琠敨猠湵猠楨敮眠牡灵湯礠畯⁲慦散吊敨爠楡獮映污潳瑦甠潰潹牵映敩摬ੳ湁湵楴敷洠敥⁴条楡੮慍⁹潇潨摬礠畯椠桴潨汬睯漠楈⁳慨摮'.encode("u16")[2:]

run at codepad.org


Pyth, 19 bytes * 2 - 10 = 28

Note that the online compiler/executor doesn't show output because it's an infinite loop.

K1#~K1I&!tPK!tPhyKK

Explained:

K1                      K=1
  #                     While true:
   ~K1                  K+=1
      I                 If
       &                logical AND
        !tPK            K is prime
            !tPhyK      2*K+1 is prime (y is double, h is +1)
                  K     Print K


What's the chance that I'll win a door prize?

MATL, 42 bytes

:<~QXJx`J`tf1Zry0*1b(-tzq]f1=vts3e8<]6L)Ym

This uses a probabilistic (Monte Carlo ) approach. The experiment is run a large number of times, from which the probability is estimated. The number of realizations is selected to ensure that the result is correct up to the fourth decimal with probability at least 90%. However, this takes a very long time and a lot of memory. In the link below the number of realizations has been reduced by a factor of 106 so that the program ends in a reasonable amout of
time; and only the first decimal is guaranteed to be accurate with at least 90% probability.

EDIT (July 29, 2016): due to changes in the language, 6L needs to be replaced by 3L. The link below incorporates that modification.

Try it online!

Background

Let p denote the probability to be computed. The experiment described in the challenge will be run for a number n of times. Each time, either you win the prize (“success”) or you don't. Let N be the number of successes. The desired probability can be estimated from N and n. The larger n is, the more accurate the estimation will be. The key question is how to select n to fulfill to the desired accuracy, namely, to assure that at least 90% of times the error will be less than 10−4.

Monte Carlo methods can be

Fixed-size: a value of n is fixed in advance (and then N is random);
Variable-size: n is determined on the fly by the simulation results.

Among the second category, a common used method is to fix N (desired number of successes) and keep simulating until that number of successes is achieved. Thus n is random. This technique, called inverse binomial sampling or negative-binomial Monte Carlo, has the advantage that the accuracy of the estimator can be bounded. For this reason it will be used here.

Specifically, with negative-binomial Monte Carlo x = (N−1)/(n−1) is an unbiased estimator of p; and the probability that x deviates from p by more than a given ratio can be upper-bounded. According to equation (1) in this paper (note also that the conditions (2) are satisfied), taking N = 2.75·108 or larger ensures that p/x belongs to the interval [1.0001, 0.9999] with at least 90% probability. In particular, this implies that x is correct up to the 4th decimal place with at least 90% probability, as desired.

Code explained

The code uses N = 3e8 to save one byte. Note that doing this many simulations would take a long time. The code in the link uses N = 300, which runs in a more reasonable amount of time (less than 1 minute in the online compiler for the first test cases); but this only assures that the first decimal is correct with probability at least 90%.

:        % Take k implicitly. Range [1 ... k]
<~       % Take n implicitly. Determine if each element in the previous array is
         % less than or equal than n
Q        % Add 1. This gives an array [2 ... 2 1 ... 1]
XJx      % Copy to clipboard J. Delete from stack
`        % Do...while. Each iteration is a Monte Carlo realization, until the
         % desired nunber of successes is reached
  J      %   Push previously computed array [2 ... 2 1 ... 1]
  `      %   Do...while. Each iteration picks one door and decrements it, until
         %   there is only one
    t    %     Duplicate
    f    %     Indices of non-zero elements of array
    1Zr  %     Choose one of them randomly with uniform distribution
    y0*  %     Copy of array with all values set to 0
    1b(  %     Assign 1 to chosen index
    -    %     Subtract
    tzq  %     Duplicate. Number of nonzero elements minus 1. This is falsy if
         %     there was only one nonzero value; in this case the loop is exited
  ]      %   End do...while
  f1=    %   Index of chosen door. True if it was 1 (success), 0 otherwise
  v      %   Concatenate vertically to results from previous realizations
  ts3e8< %   Duplicate. Is the sum less than 3e8? If so, the loop is exited
]        % End do...while
6L)      % Remove last value (which is always 1)
Ym       % Compute mean. This gives (N-1)/(n-1). Implicitly display


Haskell, 61 bytes

f n=[i|i<-[2..],gcd i n<2,all((/=i).f)[2..n-1],abs(n-i)>1]!!0

Try it online!

I'm fairly new to Haskell, so any golfing tips are appeciated.

Thanks to Wheat Wizard for 2 bytes and nimi for 4 bytes

Explanation:

f n=[i|i<-[2..],gcd i n<2,all((/=i).f)[2..n-1],abs(n-i)>1]!!0
f n=                                                          -- define a function f :: Int -> Int
    [i|i<-[2..],                                              -- out of positive integers greater than two
                gcd i n<2,                                    -- gcd of i and n is 1
                          all((/=i).f)[2..n-1],               -- i isn't already in the sequence
                                               abs(n-i)>1]    -- and |n-i| > 1
                                                          !!0 -- take the first element


Minimal Rotate-Right-Double numbers in base n

Python 2, 77 76 70 bytes

f=lambda n,m=1,i=1:i<m and f(n,m,i*n)or(m+m%n*i)/n-m*2and f(n,m+1)or m

Try it online!

Input: base n
Output: The smallest integer m satisfies the requirement.

Saved 6 bytes thanks to @Bubbler!

This is a brute-force search that starts at m = 1 and works its way up. Will run out of recursion limit if the actual solution is too large.

For each m, i keeps track of the current power of n, which is increased until i>m.


Python 2.

I'm cheating a little bit:

I only construct mobiles with one horizontal. I have a feeling (but I haven't proven it) that the optimal mobile under the given conditions actually always does only have one horizontal. Edit: Not always true; with 2 2 9 1 Nabb has found a counter-example in the comments below:

Size 18:                Size 16:
   |                        |
+-++--+-----+            +--++-+
| |   |     |            |   | |
2 9   2     1           -+-  9 1
                        | |
                        2 2

I just do stupid brute-forcing:

The given weights are shuffled randomly.
Two weights at a time are placed on the mobile in the best positions such that it stays balanced.
If the resulting mobile is better than any that we had before, remember it.
Rinse and repeat, until a pre-defined number of seconds is up.

My results for your sample inputs; each was run for 5 seconds (I'm aware that this is ridiculous for the small ones – just going through all possible permutations would be faster). Note that since there's a random element, subsequent runs may find better or worse results.

3 8 9 7 5
Tested 107887 mobiles, smallest size 20:
        |
+-+-----+-+--+
| |     | |  |
5 3     7 9  8

2 3 3 5 3 9
Tested 57915 mobiles, smallest size 23:
      |
+--+-++--+-+---+
|  | |   | |   |
3  5 9   3 3   2

8 8 8 8 8 8 8 8 8 8 8 8 8 8 8 7
Tested 11992 mobiles, smallest size 50:
                |
+-+-+-+--+-+-+-+++-+-+--+-+-+-+-+
| | | |  | | | | | | |  | | | | |
8 8 8 8  8 8 8 8 8 8 8  7 8 8 8 8

1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 7 7
Tested 11119 mobiles, smallest size 62:
                    |
+-+-+-+-+-+--+-+-+-+++-+-+-+--+-+-+-+-+-+
| | | | | |  | | | | | | | |  | | | | | |
2 7 5 6 6 8  3 2 3 7 9 7 8 1  1 7 9 5 4 4

3 4 4 4 4 5 5 5 5 6 6 6 6 7 7 7 7
Tested 16301 mobiles, smallest size 51:
                |
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| | | | | | | | | | | | | | | | |
4 6 5 7 7 4 6 5 3 5 6 4 7 6 7 5 4

The code (verbose, as this isn't code golf):

import time, random

def gcd(a, b):
    while b > 0:
        a, b = b, a % b
    return a

class Mobile(object):
    def __init__(self):
        self.contents = [None];
        self.pivot = 0;

    def addWeights(self, w1, w2):
        g = gcd(w1, w2)
        m1 = w2 / g
        m2 = w1 / g
        mul = 0
        p1 = -1
        while True:
            if p1 < 0:
                mul += 1
                p1 = mul * m1
                p2 = -mul * m2
            else:
                p1 *= -1
                p2 *= -1
            if self.free(p1) and self.free(p2):
                self.add(w1, p1)
                self.add(w2, p2)
                return

    def add(self, w, pos):
        listindex = self.pivot - pos
        if listindex < 0:
            self.contents = [w] + (abs(listindex) - 1) * [None] + self.contents
            self.pivot += abs(listindex)
        elif listindex >= len(self.contents):
            self.contents += (listindex - len(self.contents)) * [None] + [w]
        else:
            self.contents[listindex] = w

    def at(self, pos):
        listindex = self.pivot - pos
        if 0 <= listindex < len(self.contents):
            return self.contents[listindex]
        return None

    def free(self, pos):
        return all(self.at(pos + d) is None for d in (-1, 0, 1))

    def score(self):
        return 1 + 2 * len(self.contents) - self.contents.count(None)

    def draw(self):
        print self.pivot * " " + "|"
        print "".join("+" if c is not None or i == self.pivot else "-" for i, c in enumerate(self.contents))
        print "".join("|" if c is not None else " " for c in self.contents)
        print "".join(str(c) if c is not None else " " for c in self.contents)

    def assertBalance(self):
        assert sum((i - self.pivot) * (c or 0) for i, c in enumerate(self.contents)) == 0

weights = map(int, raw_input().split())

best = None
count = 0

# change the 5 to the number of seconds that are acceptable
until = time.time() + 5

while time.time() < until:
    count += 1
    m = Mobile()

    # create a random permutation of the weights
    perm = list(weights)
    random.shuffle(perm)

    if len(perm) % 2:
        # uneven number of weights -- place one in the middle
        m.add(perm.pop(), 0)

    while perm:
        m.addWeights(perm.pop(), perm.pop())

    m.assertBalance() # just to prove the algorithm is correct :)
    s = m.score()
    if best is None or s < bestScore:
        best = m
        bestScore = s

print "Tested %d mobiles, smallest size %d:" % (count, best.score())
best.draw()


Python 3, 132 130 bytes

r=round
bleen=6.1
m=1.08
a,b=eval(input())
d=1-2*(a>b)
print(*[[r(i/m),"-bleen"[i>0:]][i*i==49]for i in range(r(m*a),d+r(m*b),d)])

Takes input in the following example format:

-8, bleen


Find a mirror configuration to match laser destinations

Python, 671 654 bytes

Not a solution, but an attempt, read below.

import random as R
def V(F):
 for S,_x,_y in (F[0],0,1),(F[-1],0,-1),([L[0] for L in F],1,0),([L[-1] for L in F],-1,0):
  for i,C in enumerate(S):
   if not C in '+-|':
    x=_x;y=_y
    if not x: X=i;Y=y
    elif not y: Y=i;X=x
    while F[Y][X] != C:
     if F[Y][X]=='\\':x,y=y,x
     if F[Y][X]=='/':a=x+y;x,y=x-a,y-a
     X+=x;Y+=y
     try:
      if F[Y][X] in '+-|':return False
     except:
      return False
 return True
F=open(input()).read().split('\n')
while 1:
 _=[F[0]]+['\n'.join([L[0]+''.join([R.choice(' \\/')for i in range(len(F[0])-2)])+L[-1] for L in F[1:-1]])]+[F[-1]]
 if V(_):
  for l in _: print l
  break

I did not golf this to the max, since I'm not satisfied with the solution.
V validates a given solution by walking the field F for each character C it finds on the sideline. Solutions are generated at random. It's ugly, it works for entry1, but takes a Lot of time for the other entries. Since it randomly tries solutions, I don't consider this to be an actual solution for the given problem; but it might help others.

Run:
echo "entry1.txt" | python script.py


Mathematica

The basin size list can be gotten by

WatershedComponents[
 Image[Rest@ImportString[m,"Table"]] // ImageAdjust,
 CornerNeighbors -> False,
 Method -> "Basins"
 ] // Reverse@Sort@Part[Tally[Flatten@#], All, 2] &

where m is the given input data. To display a matrix like the ones in the question one can replace // Reverse@Sort@Part[Tally[Flatten@#], All, 2] & with /. {1 -> "A", 2 -> "B", 3 -> "C"} // MatrixForm or one can display it as an image instead using //ImageAdjust//Image.


Wolfram Language (Mathematica), 44 bytes

Max[PermutationOrder/@Permutations@Range@#]&

Try it online!

Wolfram Language (Mathematica), 31 bytes

@DanielSchepler has a better solution:

Max[LCM@@@IntegerPartitions@#]&

Try it online!


Computing truncated digits sums of powers of pi

Python - 191 Bytes

t=i=1L;k=n=input();f=2000*20**n;A=range(n+1)
for k in range(2,n):A=[(A[j-1]+A[j+1])*j>>1for j in range(n-k+1)];f*=k
while k:k=(1-~i*n%4)*f/A[1]/i**n;t+=k;i+=2
print sum(map(int,`t`[-n-4:-4]))

~4x faster version - 206 bytes
t=i=1L;k=n=input();f=2000*20**n;A=[0,1]+[0]*n
for k in range(1,n):
 f*=k
 for j in range(-~n/2-k+1):A[j]=j*A[j-1]+A[j+1]*(j+2-n%2)
while k:k=(1-~i*n%4)*f/A[1]/i**n;t+=k;i+=2
print sum(map(int,`t`[-n-4:-4]))

Input is taken from stdin. Output for n = 5000 takes approximately 14s with the second script (or 60s with the first).

Sample usage:
$ echo 1 | python pi-trunc.py
1

$ echo 2 | python pi-trunc.py
14

$ echo 3 | python pi-trunc.py
6

$ echo 4 | python pi-trunc.py
13

$ echo 5 | python pi-trunc.py
24

$ echo 50 | python pi-trunc.py
211

$ echo 500 | python pi-trunc.py
2305

$ echo 5000 | python pi-trunc.py
22852

The formula used is the following:

where An is the nth Alternating Number, which can be formally defined as the number of alternating permutations on a set of size n (see also: A000111). Alternatively, the sequence can be defined as the composition of the Tangent Numbers and Secant Numbers (A2n = Sn, A2n+1 = Tn), more on that later.
The small correction factor cn rapidly converges to 1 as n becomes large, and is given by:

For n = 1, this amounts to evaluating the Leibniz Series. Approximating π as 10½, the number of terms required can be calculated as:

which converges (rounded up) to 17, although smaller values of n require considerably more.
For the calculation of An there are several algorithms, and even an explicit formula, but all of them are quadratic by n. I originally coded an implementation of Seidel's Algorithm, but it turns to be too slow to be practical. Each iteration requires an additional term to be stored, and the terms increase in magnitude very rapidly (the "wrong" kind of O(n2)).
The first script uses an implementation of an algorithm originally given by Knuth and Buckholtz:

Let T1,k = 1 for all k = 1..n
Subsequent values of T are given by the recurrence relation:
Tn+1,k = 1/2 [ (k - 1) Tn,k-1 + (k + 1) Tn,k+1 ]
An is then given by Tn,1
(see also: A185414)

Although not explicitly stated, this algorithm calculates both the Tangent Numbers and the Secant Numbers simultaneously. The second script uses a variation of this algorithm by Brent and Zimmermann, which calculates either T or S, depending on the parity of n. The improvement is quadratic by n/2, hence the ~4x speed improvement.


Python, 69 bytes

lambda w,h:["UOnvd"[w/h/h>20::2]+"erweight","Normal"][18.5<=w/h/h<25]

Try it online!

Compare to 72 bytes:

lambda w,h:"Underweight"*(w/h/h<18.5)or"Normal"*(w/h/h<25)or"Overweight"


05AB1E, 63 52 50 bytes

Specialization formula

Îƒ0NU62201122vyÍ¹Ì°*8X*N>+÷+}16Xm÷+DX>£X__iÀ'.ìÁ},

Try it online!

BBP formula

ƒ4¹>°UX*8N*©>÷YX*®4+÷-1X*®5+÷-1X*®6+÷-1X*16Nm÷*ODN>£N__iÀ'.ìÁ},

Try it online!


Python 3, 259 247 226 bytes

lambda l,a,b:sum(2**-len({*m}^{*n})for v in{*sum(l,())}for m in p(v,a,l)for n in p(v,b,l)if not{*zip(m,m[1:])}&{*zip(n,n[1:])})
p=lambda i,j,l:sum([[[r+[i]for r in p(y,j,l)],[[y,x]]][j==y]for x,y in l if i==x],[])+[[i]]*(i==j)

Try it online!

This can probably be golfed down quite a bit, but for now I'm just happy it works.


Put together cut strips of paper to get original message

Python 3 - Trie and DFS

Trie is a tree shape data structure. If we build a trie from a collection of words, then each path from the root to a leaf node will represent a word from the collection.

To solve this problem, first we build a trie using the valid words. Suppose the original text has n rows and m columns, then we will have m strips to put together. We try to reconstruct the original text from left to right, column by column, using a recursive depth-first search. To perform branch elimination, we also maintain a list of heads on the trie, name it heads. Each head points to a node on the trie and point to the root at first. We will need n heads, each correspond to a row. Each time after a column(strip) is appended, heads[i] will be moved according to the character strip[i]. If we found any head that cannot be moved, then we know the column just appended is incorrect. After putting m columns, we get the original text.

I implemented this algorithm using Python. It is fast enough to solve a 40x80 case with 10000 valid word in instant.

I use this python 3 script to generate test cases. Run it with:

python3 make_script.py {dict path} {n rows} {n cols} > intput.txt

The following is a 40 x 80 case. The dictionary file can be found here, which has 10000 words.

80
40
c el efp e otl  desaiweseeme  jomp ebc g
synwds  irnsatseityl rkutpsiysei ssraat
gvmjewrell fclpadrll nbsvwiwteqdeniditba
uet criderndm eesih dalbrcra d iacnnoi e
lbipoeivedrwddivensne aeihrpaa eicangpni
 gontgtulvcbatdo glunsniiguoleu eigtbelh
xmsyyu ereio edvrttdonure tpselriniipnxs
ssdieop bgkg  wu  eloyr dllrhza t hic af
rttruminetnt rcu rasa ogosrywrnietvldgod
lpe aritour alolt yeomlpimmxryftenen  sn
cneregsc igodbsigeca r kbhiiisoss eagglp
crm nhdreh raokdtr rcfiotpsfgtjanotaaiaf
s pntenpnmv plemiaaxeeittgtg ncnaooaou a
srrganeu ut toaantetedccnr seiise eur ni
 xpndg psafl ooemlusof nba pauosina esnb
ge du  tbfe  spuoeuesen o s um ldsted  w
eto rs l nhuc caexr bsoptwcrrnaennrasary
e  maldneg nep nmaid isie ko ctedh necaa
esoeisi u ifran  rgirrts ntipuneccnvftrp
gui oeriwraisc og vsepharn latotts aenra
eenylorobneyrem nwtefrasdeoeet ot  osdsr
abia e i iwrcneaaiaeeu lie oihotgdicntdi
euugmjsdfcamazndei e yoagaserxatrultoaio
tamdfesgtitc xseuegs  fene thatfueo l ut
ocn sdrtn mai aerwmimoss te  oceorrit el
netbu wymsrfobelltemetrisioao uri  l ce
deaa ee e aadrgcoln cnto semroi  ofdnanu
aeaunrmvonirieaxapicnaioxaoromeviiuaeoou
 oaodtb hpretdarie n e recei etunsrsedal
ejht n jy ees tnr gsegr s  e jhb ayegup
ohids bi g iesiogs rytimtorrsab pnirwlc
ieuereaklieapeatlan sdeeg e lasedaob  be
rihbegaisvdtrprnatservaraco na imtcgplna
denrdnnelymisenimi gnfw bssalupcnansu et
itsrwnbeclwfmstasg craaim ei  atrifvpr
ubksogxernu auletinieo krte cgmltiliioir
atnhndcutigiasuir ntsaiauem usiireg idms
yniis ssle aisicsngqseazdifiertercaauvoc
ds prcatnoiaafsiopiratdrrmksnfidakr  gon
p ngaoolyeolg nep oae dnsnln srfcontsrve
boges massscgss arsobod ierseh rnivtagsp
nlstadhndnroieecntc slhoucbrcouo uohtiis
ltainnpif nfrn tinrdoi ninsanteu n   aeb
oun htoioaftupedsmowtmeatanyi sltnh ftto
a emgrasancass oelrefddy alacinsut n s
kgttnltednrmea t yhug welentn tu fsneeah
yia bilgwybnisgfrmidlh t rssnaiultgagk a
  iaeeorega sdbhc otadiresdagcipcuet rde
tygui artnsot le wtes etrracm pde oev e
cvrpsabemddamylpeiscdmktpnnolbsesardlwro
rnirmestiwntlrfresosedlvshydrsrrucnntr a
nans hinslmoxenfeolo cxeeneosgrphantiuyg
m dans llnrtlav ensptun acfaev s gtesfad
litl gonungirgk pioeutvinsstgintpsmbrdsu
altpjretooode rtnseeyepdrotllxric s rice
aikaunnskdoh agtnl cuegoacwhnsx esrurgg
ef drant  rsaaeymreleiiessmniesdoeeroeer
eereozurmoicueeegtcolbeioteodocrsnaeaatt
 h cre g  snsihssatlunisi odeelcpminoeba
oisstnirhpmnaybaertcnenhdnondsunaaprlipr
vetou egriemerpicacb  ygmiaw rrrocnisecm
ibs tara  neeiaqlbbtsgegcs sooeoeuel ten
blrkqaiacortqmn ien ylrrrnecieircs qeind
en s e ieu cnaiscikuirocnr hlnpfjooimohs
dctlehtr ntlgpddeoipmog elllrnncnkgcseeu
o  aaet henyaue mbntgeeselsws   mmawnwve
lns e xoorail yn  eesnee uctaud nrasenha
swydiecacaefolsenmttnsoer ohmahttpt radc
yvltaxin pgrauluktystkmot mrf aluuiepl
b sea usksoim hr idhtttd e owrn cnferevc
lstsibaocesfsmbejsdaellmepmbdedoffdbrtmq
axou nlnae ise gn esse  ihbstgsfmeteestf
yeaasra oopaeaildkiynteteidilnuenec vral
msylcdecsy  lkgr  icdkxrmie strle fei sz
 rdae gde al ngswsc soaru  tlsrtg durfne
 rrpodl i asg  essvuo aeaaheenaloe  geru
grus nbrls eqme ydioradhsoolmdiouoggnssv
 tfirotrkdnnnrtmwenan   abs cfcigscmpsed
 a soteiicdero nsaeuisrmisntau iirammlyi
anroiim tsiiaarrhoyaimdo oera dblogysmr

Solved:

lacerated deliberateness canvas gould scold sexually piggyback obey agrimony moe
seventy except fixates warble shrubbery instrumenting beveling convolute hairs j
tarring aptness homotopy misted unkindness frustrations marketing latitudinary h
superhumanly redbud bends atomics sprawls piggy oiling djakarta estop reads plat
insomnia delaware fruition auger hooded terramycin statuesqueness adjourns boca
brazed leghorn agnes seethed roentgen sen conjuring goa wrangled extremes hidden
ambuscade tribunals winced heap boxing fixates impostor rainstorm iberia billet
overturn protestingly pairings grieved protruded insulate ascertain tinkling c j
committees bock sat muncie drab lorelei honk fretfully block dense howell swishy
endowing annuls veins machining sandy reproducers neve flooding supportingly ye
sidings afterword thrived wrecks furman maintaining cone programs groaner mba ne
fractionally fisticuff ferromagnet wilsonian modifiable fathom accreditations ye
simulated grammars corporacies squads atalanta marriage ceq designates plexiglas
meyers propels apex ballooners impudently froze angst islamabad saud creases ku
baleful godmother scenes keep wheelings bystander kidnappings basilar caving get
experienced laryngeal mendacious devise animadvert coequal tithe surtout offer n
jaeger moments manuel instance systemwide ownerships plodding cracking legers mr
spits wallow girt extramarital administer petitioning berkeley writes ransoms b
discontinuity desegregate accretions cysteine thyroglobulin chomsky evans living
accosted speechless mixture bellowing lacerated adequately cautiousness products
endless comforters berenices fourteens insane odiousness nyu gambit yeasty lodge
lambda informative stressful dynamo forwent dynamites gentler doorkeep dutch keg
likeliest galatia fortiori hydride awakened could vandenberg wisdom phoenix axer
motivation spider epistemology shake rusher carbonizing strokers cordage meters
exposure bedim saints tritium distributed ranger indiscoverable interrogate ames
panther salem eschewing special oaths penumbra consigns winchester cons conrail
moneymake lome mob cottons ballooners smocks stressful sidewinder met refreshes
brood complexion straightforwardly patients separations wichita shrilly arose we
doldrum rarer winthrop magic chemically dancers angel outlining elf lawlessness
emboss county reagan unauthorized gauss suffixed tiresomeness cohn extravagant j
description fans staunch journalism prejudicial denture quixotic patrons briar h
override scott differentiators collection distribute folder superfluities pull b
fissured intercommunicating outputting managerial precedences conjuncted phloem
fiance honk nineteen coproduct monica sparks unconsciousness furious stagnate ma
durango fag effector notation highlands parceling magnetic reservoirs voting fay
baden end converge alva machining insurers mutiny battled quantities alberta ewe
relativeness propels formants configurable propos rubs diverge tampered swigging
toward cased reels actualities estop facings animadvert trigger golding fluke wu
mort meanness venturer dyadic abstinent phoenix resolve bangladesh acrobacy rsvp
quotas auburn crafty pacifism favorite grandiose buchenwald phelps leaded gauze

Code

def build_trie(words):
    root = {}
    for word in words:
        node = root
        for c in word:
            if c in node:
                node1 = node[c]
            else:
                node1 = node[c] = {}
            node = node1
    return root

def search_origins(root, strips):
    n_rows = len(strips[0])
    n_cols = len(strips)
    ordered = [None] * n_cols
    heads = [root] * n_rows
    used = set()

    def get_next(node, c):
        if c == ' ':
            return root
        return node.get(c, None)

    def search(col_id, heads):
        if col_id == n_cols:
            yield transpose(ordered)
            return
        for i in range(n_cols):
            if i in used:
                continue
            heads1 = [get_next(head, c) for c, head in zip(strips[i].lower(), heads)]
            if any(x is None for x in heads1):
                continue
            used.add(i)
            ordered[col_id] = strips[i]
            yield from search(col_id + 1, heads1)
            used.remove(i)
    yield from search(0, heads)

def transpose(cols):
    return '\n'.join(map(''.join, zip(*cols)))

def parse():
    m = int(input())
    n = int(input())
    strips = []
    for i in range(m):
        strip = input()
        if strip[0] == '"':
            strip = strip[1:1 + n]
        strips.append(strip)
    n_words = input()
    if n_words:
        words = [input() for _ in range(int(n_words))]
    else:
        dict_path = input()
        words = list(map(str.rstrip, open(dict_path)))
    return words, strips

def main():
    words, strips = parse()
    words = list(map(str.lower, words))
    # print(words, strips)
    root = build_trie(words)
    for i, result in enumerate(search_origins(root, strips)):
        print('#{}{}'.format(i, '-' * 80))
        print(result)
        # Uncomment next line if you want only one result
        # break

if __name__ == '__main__':
    main()


48 bytes
How about...
#include<cstdlib>
main(){system("tr \\  +|bc");}

...not using C++?

The call to system runs commands on your shell (<cstdlib> declares system).
tr \\  + executes the command tr, translating spaces to + (so the input34 45 becomes 34+45).
| pipes tr's STDOUT into bc's STDIN.
bc performs equations in STDIN and prints the result to STDOUT.


Jelly, 6 bytes in Jelly's codepage

½ÆRḟÆf

Try it online!

Explanation:

½ÆRḟÆf
 ÆR    All primes less than or equal to
½      the square root of the input
   ḟ   but with the following removed:
    Æf All prime factors of {the input, by default}


Duplicates in "n × hamming weight of n" sequence

JavaScript (V8),  72 71 70  69 bytes
A full program that prints the sequence forever.

for(n=1;c=2;c||print(n))for(d=++n;d--;)c>>=n==(h=n=>n&&h(n&n-1)+d)(d)

Try it online!
Commented
for(                   // infinite outer loop:
  n = 1;               //   start with n = 1
  c = 2;               //   before each iteration: initialize c to 2
  c || print(n)        //   after each iteration: print n if c = 0
)                      //
  for(                 //   inner loop:
    d = ++n;           //     increment n and start with d = n
    d--;               //     stop when d = 0 / decrement d
  )                    //
    c >>=              //     right-shift d by 1 position if ...
      n == (           //       ... n is equal to ...
        h = n =>       //       ... the result of the recursive function h
          n &&         //       which adds d as many times as there are
          h(n & n - 1) //       bits set in d, using n & n - 1 to clear
          + d          //       the least significant bit at each iteration
      )(d)             //

Note
We decrement \$d\$ right away in the inner loop, which means that we never consider the case where the divisor of \$n\$ is \$n\$ itself. But that would only work if there's a single 1 in the binary representation of \$n\$, which means that \$n\$ is a power of \$2\$ and all its divisors have a single 1 in their binary representation as well. Therefore, \$n=1\times n\$ is the only possible solution and \$n\$ does not belong to the sequence.


Haskell, 82 73 bytes

r=read.reverse.show
f 1=0
f a=1+(minimum$f(a-1):[f$r a|r a<a,mod a 10>0])

Try it online!

Simplest recursion method.

-9 bytes thanks to Christian Sievers


Sort a number's divisors by prime factorization

05AB1E, 6 bytes
Code:
ÑÒí{€P

Explanation:
Ñ       # Get the divisors of input.
 Ò      # Factorize each.
  í     # Reverse each.
   {    # Sort the array.
    €P  # Product each.

Uses the CP-1252 encoding. Try it online!.