PHP - 197 bytes

The function works by analysing each line, in the reverse order and one after the other, and maintaining an array of the used variables.

If there is an equal character = in the line, it's an assignment.

It the variable is used, the assignment is useful, and the line is printed, but the variable isn't considered used any more.
Otherwise, do nothing.

Otherwise, the line is an expression. We split the line after each space, and add each symbol to the list of used variables. Numbers (1, 2, …) and operators (+, -, …) will be added too, but since they aren't valid variables names, it's not a problem. The line is then of course printed.

function($c){$u=[];foreach(array_reverse(split('
',$c))as$l){if($p=strpos($l,'=')){if(!isset($u[$x=substr($l,0,$p-1)]))continue;
unset($u[$x]);}else$u+=array_flip(split(' ',$l));$f="
$l$f";}echo$f;}

Here is the ungolfed version:

function removeDeadCode($code)
{
    $usedVariables = [];
    $finalCode = '';

    foreach (array_reverse(explode("\n", $code)) as $line)
    {
        if ($equalPosition = strpos($line, '='))
        {
            $variable = substr($line, 0, $equalPosition - 1);
            if (isset($usedVariables[$variable]))
            {
                $finalCode = "\n" . $line . $finalCode;
                unset($usedVariables[$variable]);
            }
        }
        else
        {
            $usedVariables += array_flip(explode(' ', $line));
            $finalCode = "\n" . $line . $finalCode;
        }
    }

    echo $finalCode;
}


God is real . . . unless declared integer

FORTRAN IV (Compiled with gfortran -ffixed-form), 309 291 290 280 398 393 392 334 237 231 bytes + Bonus imaginary Internet points

This should now be a proper FORTRAN IV program, with no anachronisms!

	REALS(200)
	DATAG,R,H,A/1HG,1HR,1H-,1H(/
	READ 9,S
    9	FORMAT(200A1)
	DO1 I=1,200
	C=S(I)
	IF(C.NE.A)GOTO2
	T=S(I-1)
	GOTO1
    2	IF(C.LT.G.AND.S(I+1).EQ.H.AND.S(I+2).GE.G.OR.C.EQ.G)GOTO8
    1	CONTINUE
	T=R
    8	PRINT 9,T
	END

Try it online!

Here's the same code embedded in a loop that runs through the entire test suite.  I don't think this can be done with TIO's header and footer.

18 bytes off thanks to @JonathanAllan, who pointed out that one IF statement wasn't needed.

1 more byte off by eliminating a stray space between CHARACTER and S at the top.

And 10 more bytes by rearranging the spaghetti code a bit.

Added 118 bytes to put it in proper FORTRAN IV fixed-column punch-card formatting. (This is for historical accuracy -- it isn't necessary for proper functioning under gfortran.)

Shaved off 5 more bytes: Cleaned up the GOTOs a bit, and changed the treatment of characters so it's actually correct for FORTRAN IV.

1 more byte off from removing an unneeded space in the DATA statement.

58 bytes off by streamlining the flow of control through the various IF statements.

97 more bytes off by: (1) eliminating variable P; and (2) replacing the spaces required at the beginning of a line with a tab character, which I found is allowed, according to an old FORTRAN IV manual. (I was thinking of punch card machines, which, as I recall, didn't have a horizontal tab, but I forgot about teletype machines, which did have a tab key.)

Thanks to @Dingus for 6 more bytes (from removing the B in the DATA statement which was no longer needed after P was eliminated).

I've limited myself to FORTRAN IV constructs here.  This should now be a correct FORTRAN IV program, without such things as the CHARACTER data type and quote-delimited strings, which were only introduced later.

Characters in FORTRAN IV needed to be entered as Hollerith constants, and they could be stored in variables of type REAL (and probably other types sometimes too, but there was no CHARACTER type originally).  (As I recall, a real could hold 5 ASCII characters from what we now call a string.  I think they were padded with spaces if there were fewer than 5 characters in a grouping.  The single characters I use are each stored as a real, padded with extra space characters in the real.)

Input is on stdin, on one line, just like the OP's test cases.

Output is on stdout.

FORTRAN IV was my introduction to computer programming -- it was the first programming language I ever learned.  When I was a boy, I read through my dad's textbooks when he took a class in it at NYU, which was required by his musicology graduate program.  Computer programming (as well as FORTRAN itself) has changed quite a bit since then :) .


Once you know, that a is free of zero values, using nnz(a) spares you 2 chars compared to numel(a).
Prefer a(a==0) to a(find(a==0)).
~t is shorter than t==0 , and even ~~t is shorter than t!=0.
0*(1:n) is shorter than zeros(1,n)
Generally, || and && , unlike many other operators, scalarize the result when the first argument is a scalar. For matrices, only non-empty matrices without elements equal to zero have the logical value of true.

Hence, we can do 0||m instead of all(all(m)) for any matrix.

Try with 0||[1 1;1 0] and 0||[1 1;1 1] to convince yourself.
When you are using a builtin a number of times, do a function handle to spare characters eg. f=@find . For short function names at least 3 occurrences justify this, for long ones - even with two occurrences.
When a function is a single statement, prefer f=@(n)dosomething(n) notation to function r=f(n)r=dosomething(n);end one.
Unfortunately, global variables have to be declared both in global scope and in each function using them. But there is an exception: anonymous @(n)... functions "see" all variables from the scope where they are called from.
It's possible to do f(a=0,b=0) instead of a=0;b=0;f(a,b).
This seems undocumented feature, but the order of evaluation is from left to right (checked at v. 3.8.1), you can do zeros(a=n,b=a*a) to both create a n x n^2 matrix and store it's row and column number in a and b variables.
The operator precedence table is your friend. Don't do b=(a==0) since b=a==0 is the same.


Solving less-than inequalities with positive integers

Pyth, 39 bytes

V>1f.A<MxMLTN.pS{s=Nm%2cd).zVNjd[H\==hZ

Try it online: Demonstration

Brute-forces through all possible permutations (and interpret them as sortings), check if they match the inequalities, and assign them the values 1, 2, ...., n.

Explanation

f.A<MxMLTN.pS{s=Nm%2cd).z
                 m     .z  map each input line d to:
                    cd)       split d by spaces
                  %2          and remove the second element
               =N          save this list of pairs to N
              s            combine these pairs to a big list of variable names
             {             set (remove duplicates)
          .pS              generate all permutations
f                          filter for permutations T, which satisfy:
     xMLTN                    replace each variable in N by their index in T
 .A<M                         check if each pair is ascending

V>1...VNjd[H\==hZ          implicit: Z = 0
 >1                        remove all but the last filtered permutation (if any)
V                          for each permutation N in ^ (runs zero times or once):
      VN                      for each variable H in N:
          [                      generate a list containing:
           H                        H
            \=                      "="
              =hZ                   Z incremented by 1 (and update Z)
        jd                       join this list by spaces and print


SageMath, 3 bytes

5 bytes saved thanks to @Mego

fcp

Try it online!

Takes a Matrix as input.

fcp stands for factorization of the characteristic polynomial,

which is shorter than the normal builtin charpoly.


Python 3, 121 bytes

lambda z,a='ABCDEFGHIKLMNOPQ',r='RSTUVWXYZ':int(z[1:])if z[2:]else[t+u for t in['',*r+a]for u in a+r if t<=u].index(z)-15

Try it online!

Explanation

The list comprehension [t+u for t in['',*r+a]for u in a+r if t<=u] evaluates to these strings:

t='':   A  B  C  D  E  F  G  H  I  K  L  M  N  O  P  Q  R  S  T  U  V  W  X  Y  Z
t='R':                                                 RR RS RT RU RV RW RX RY RZ
t='S':                                                    SS ST SU SV SW SX SY SZ
t='T':                                                       TT TU TV TW TX TY SZ
t='U':                                                          UU UV UW UX UY SZ
t='V':                                                             VV VW VX VY VZ
t='W':                                                                WW WX WY WZ
t='X':                                                                   XX XY XZ
t='Y':                                                                      YY YZ
t='Z':                                                                         ZZ
t='A': AA AB AC AD AE AF AG AH AI AK AL AM AN AO AP AQ AR AS AT AU AV AW AX AY AZ
t='B':    BB BC BD BE BF BG BH BI BK BL BM BN BO BP BQ BR BS BT BU BV BW BX BY BZ
...
...
...
t='Q':                                              QQ QR QS QT QU QV QW QX QY QZ

If there are any characters past the first two (z[2:]) then the result is int(z[1:]). Otherwise (i.e. if there are only one or two characters) we look the string up in the list we created and subtract 15 from the index.


Convert a string representation of a number to int[] in C#

28 bytes

You can make your last approach a bit shorter by replacing the '0' by 48. You can also strip all unnecessary spaces and use 1-char variable names (for example, number -> n):

n.Select(i=>i-48).ToArray();


All ASCII characters with a given bit count

8088 assembly, IBM PC DOS, 35 30 29 bytes
Machine code:
be81 00ad 8afc b330 b108 d0c8 12dd e2fa 3afb 7504 b40e cd10 fec0 79ea c3

Listing:
BE 0081     MOV  SI, 081H   ; SI = memory address of command line string
AD          LODSW           ; AL = start ASCII value (init to 20H from space on cmd line)
8A FC       MOV  BH, AH     ; BH = target number of bits (in ASCII)
        CHR_LOOP:
B3 30       MOV  BL, '0'    ; BL = counter of bits, reset to ASCII zero
B1 08       MOV  CL, 8      ; loop through 8 bits of AL
        BIT_LOOP:
D0 C8       ROL  AL, 1      ; rotate LSB of AL into CF
12 DD       ADC  BL, CH     ; add CF to BL (CH is always 0)
E2 FA       LOOP BIT_LOOP   ; loop to next bit
3A FB       CMP  BH, BL     ; is current char the target number of bits?
75 04       JNE  NO_DISP    ; if not, do not display
B4 0E       MOV  AH, 0EH    ; BIOS write char to screen function
CD 10       INT  10H        ; display ASCII char in AL (current char in loop)
        NO_DISP:
FE C0       INC  AL         ; increment char to next ASCII value
79 EA       JNS  CHR_LOOP   ; if char <= 127, keep looping
C3          RET             ; return to DOS

Standalone PC DOS executable program, input number from command line.  Output is displayed to console window.

Download and test ABCT.COM (AsciiBitCounT).


find the pattern in this number sequence of 1's and 0's

Jelly, 11 10 bytes

Saved 1 byte thanks to @Dennis

ȷḶ×⁽q£:ȷ5Ḃ

Try it online!

How?

I first noticed that the pattern alternates between runs of length 4 and length 3, skipping the length-4 step every few runs. This led me to look for a number which could be divided into the current index, then taken mod 2 and floored—i.e. retrieving the least significant bit—to give the bit at that index in the series. After much trial and error, I found that 3.41845 does exactly that, but multiplying by its approximate reciprocal (.29253) is a byte shorter.

ȷḶ×⁽q£:ȷ5Ḃ    Main link. Arguments: none
ȷ             Yield 1e3, i.e. 1000.
 Ḷ            Lowered range; yield [0, 1, 2, ..., 999].
  ×⁽q£        Multiply each item by 29253.
      :ȷ5     Floor-divide each item by 1e5, i.e. 100000.
         Ḃ    Take each item mod 2.


PHP, 141 bytes

for($r=[];$i<$l=strlen($a=$argn);$i++)for($t=1;$t;$t*=$t<$l)in_array($s=substr($a,$i,$t),$r)|strpos($a,$s)<$i?$t++:$r[]=$s.$t="";print_r($r);

Try it online!


Dyalog APL, 9 7 5 bytes

⌽⊤⍨∘⌽

This is a dyadic function train that expects seconds and lengths as left and right arguments. It is equivalent to the following, train-less function:

{⌽⍺⊤⍨⌽⍵}

Verify all test cases at once on TryAPL.

How it works

    ⌽ Reverse the right argument...
   ∘    and...
 ⊤⍨     perform mixed base encoding on the left argument with those bases.
⌽     Reverse the order of the result.


C (gcc), 99 98 96 bytes

Saved a byte thanks to ceilingcat; golfing 19683 to L'䳣'.
Saved two bytes; golfing 108609 to L''.

M,a,l,b,o;L(g,e){for(o=b=L'䳣',l=0;o/=2.4;b/=3)M=g/b,g%=b,a=e/b,e%=b,l+=b*(L''>>M+6*a+M&3);g=l;}

Try it online!


Generate number in reverse polish notation

Score 199503, Java solution

import java.util.HashMap;
import java.util.HashSet;

public class RPN {

    public static void main(String[] args) {
        // Loop to calculate total over all 10001 numbers as defined in puzzle
        int total = 0;
        System.out.println("n\tscore\trpn");
        for (int k = 0; k <= 10000; k++) {
            final String rpn = findRPN(k);
            final int scr = calcScore(rpn);
            System.out.println(k + "\t" + scr + "\t" + rpn);
            total += scr;
        }
        System.out.println("TOTAL: " + total);
    }

    // simple scoring calculator for a given rpn representation (ignores 10% bonus)
    private static int calcScore(String rpn) {
        int score = 0;
        for (char ch : rpn.toCharArray()) {
            if (Character.isDigit(ch)) {
                score += ch - '0';
            } else {
                score++;
            }
        }
        return score;
    }

    // hashmap caching intermediate results and all results for 0<=n<=10000
    final static int max = 6000000;
    final static HashMap<Integer, String> rpns = new HashMap<Integer, String>();

    // maximum score expected for numbers 0<=n<=10000
    final static int maxScore = 26;

    private static void preCalculate() {
        // hashmap which contains all numbers with a given score
        final HashMap<Integer, HashSet<Integer>> perScore = new HashMap<Integer, HashSet<Integer>>();

        // numbers are build by combining those with lower score
        for (int sc = 1; sc <= maxScore; sc++) {
            final HashSet<Integer> currentScore = new HashSet<Integer>();
            perScore.put(sc, currentScore);

            // 1-9 can be reached directly by pushing
            if (sc < 10 && !rpns.containsKey(sc)) {
                rpns.put(sc, Integer.toString(sc));
                currentScore.add(sc);
            }

            if (sc > 2) {
                // score is increased by 2 if appending "d+" or "d*" to an existing rpn
                for (int n : perScore.get(sc - 2)) {
                    String rpn_n = rpns.get(n);
                    consider(n * 2, currentScore, rpn_n, "d+");
                    consider(n * (long)n, currentScore, rpn_n, "d*");
                }
            }

            // another possibility to get score sc is to take two operands
            // with scores sc1 and sc2 and add another operator
            // with the requirement that sc1 + sc2 + 1 = sc
            for (int sc2 = 1; sc2 <= sc - 2; sc2++) {
                int sc1 = sc - sc2 - 1;
                HashSet<Integer> l1 = perScore.get(sc1);
                HashSet<Integer> l2 = perScore.get(sc2);

                // try all combinations of operators from list 1 and list 2
                // with each operator + - * / and %
                for (int n : l1) {
                    String rpn_n = rpns.get(n);
                    for (int m : l2) {
                        String prefix = rpn_n + rpns.get(m);

                        // Commutative operators - only need to consider them once
                        if (n < m) {
                            consider(n + m, currentScore, prefix, "+");
                            consider(n * (long)m, currentScore, prefix, "*");
                        }

                        // Non-commutative operators.
                        consider(n - m, currentScore, prefix, "-");
                        // div and mod only possible if m!=0
                        if (m != 0) {
                            consider(n / m, currentScore, prefix, "/");
                            consider(n % m, currentScore, prefix, "%");
                        }
                    }
                }
            }
        }
    }

    private static void consider(long value, HashSet<Integer> currentScore, String prefix, String suffix) {
        if (value < -max || value > max) return;
        Integer r = Integer.valueOf((int)value);
        if (!rpns.containsKey(r)) {
            rpns.put(r, prefix + suffix);
            currentScore.add(r);
        }
    }

    private static String findRPN(int number) {
        if (rpns.isEmpty()) {
            preCalculate();
        }

        // if number is negative try 1(-n+1)-
        if (number < 0) {
            return "1" + findRPN(-number + 1) + "-";
        }

        // if number not in precalculated list try number/2
        if (!rpns.containsKey(number)) {
            if (number % 2 == 0) {
                return findRPN(number / 2) + "d+";
            } else {
                return findRPN(number / 2) + "d+1+";
            }
        }

        // otherwise use cached result
        return rpns.get(number);
    }
}

The solution is pretty much optimized to get a good score within the defined range of numbers (i.e. 0 to 10000). It sacrifices non-optimal solutions outside the range for (hopefully) optimal representations within. Nevertheless it will still work for other numbers too.

I think the score given by that solution is very close to optimal although I'm not able to prove it.

Output:

n   score   rpn
0   3   11-
1   1   1
2   2   2
3   3   3
4   4   4
5   5   5
6   5   3d+
7   7   7
8   6   4d+
9   5   3d*
10  7   5d+
11  8   3d*2+
12  7   3d+d+
...
9990    19  5d+d*d*3d*-1-
9991    17  5d+d*d*3d*-
9992    18  5d*d+d*2-d+d+
9993    19  5d+d*d*3d+-1-
9994    17  5d+d*d*3d+-
9995    17  5d+d*d*5-
9996    16  5d+d*d*4-
9997    15  5d+d*d*3-
9998    14  5d+d*d*2-
9999    13  5d+d*d*1-
10000   11  5d+d*d*
TOTAL: 199503


Counting cycles in a folding and squashing process

CJam, 34 bytes

q~2b_,2%,\+{__,2//~\W%.\_W$=!}g;],

Nothing fancy, it just applies the map until we get back to the input, and print the number of iterations that took.

Test it here.


Python 2, 34 bytes

lambda l:map(sum,zip(l+[0],[0]+l))

Try it online!
37 bytes

lambda l:map(int.__add__,l+[0],[0]+l)

Try it online!
Python 2, 38 bytes

p=0
for x in input()+[0]:print x+p;p=x

Try it online!
Python 3.8 (pre-release), 37 bytes

lambda l,p=0:[p+(p:=x)for x in l]+[1]

Try it online!


Haskell, 178 171 bytes

import Data.List
f x=[c,c&&and[(m%n)%o==m%(n%o)|m<-b,n<-b,o<-b],x==t,all(elem b)[x,t],b==[i%i|i<-b]]where c=all(l>)(id=<<x);b=[0..l-1];a%b=x!!a!!b;l=length x;t=transpose x

Returns a list with five booleans, which are in order closure, associativity, commutativity, identity and idempotence.

Usage example: f [[1, 0, 0],[0, 1, 0],[0, 0, 1]] -> [True,False,True,False,False].

How it works:

f x=[
  c,                         -- closure (see below)
  c&&and[(m%n)%o==m%(n%o)|   -- assoc: make sure it's closed, then check the
          m<-b,n<-b,o<-b],   --        assoc rule for all possible combinations
  x==t,                      -- comm: x must equal it's transposition
  all(elem b)[x,t],          -- identity: b must be a row and a column
  b==[i%i|i<-b]              -- idemp: element at (i,i) must equal i
  ]
  where                      -- some helper functions
  c=all(l>)(id=<<x);         -- closure: all elements of the input must be < l
  b=[0..l-1];                -- a list with the numbers from 0 to l-1
  a%b=x!!a!!b;               -- % is an access function for index (a,b)
  l=length x;                -- l is the number of rows of the input matrix
  t=transpose x

Edit @xnor found some bytes to save. Thanks!


Construct n-gons with a ruler and compass

Mathematica, 2 3 4 polygons, 759 bytes

S=Solve;n=Norm;A=Circle;L=Line;c={#,Norm[#-#2]}&{a_,b_List}~p~{c_,d_List}:=a+l*b/.#&@@S[a+l*b==c+m*d,{l,m}]{a_,b_List}~p~{c_,r_}:=a+l*b/.S[n[c-a-l*b]==r,l]{c_,r_}~p~{d_,q_}:={l,m}/.S[n[c-{l,m}]==r&&n[d-{l,m}]==q,{l,m}]q={0,0};r={1,0};a=q~c~r;b=r~c~q;Graphics@Switch[Input[],3,{s=#&@@p[a,b];A@@@{a,b},Red,L@{q,r,s,q}},4,{k={q,r};{d,e}=a~p~b;j={d,e-d};d=k~p~j~c~q;{e,f}=j~p~d;A@@@{a,b,d},L/@Accumulate/@{k,j},Red,L@{q,e,r,f,q}},6,{d={q,r};e=#&@@d~p~a;f=e~c~q;{g,h}=a~p~f;{i,j}=a~p~b;A@@@{a,b,f},L@{#-2#2,#+2#2}&@@d,Red,L@{r,i,g,e,h,j,r}},8,{k={q,r};{d,e}=a~p~b;j={d,e-d};d=k~p~j~c~q;{e,f}=j~p~d;g=e~c~q;h=q~c~e;i=r~c~e;{o,s}=g~p~h;{t,u}=g~p~i;o={o,2s-2o};s={t,2u-2t};{t,u}=o~p~d;{v,w}=s~p~d;A@@@{a,b,d,g,h,i},L/@Accumulate/@{k,j,o,s},Red,L@{q,t,e,v,r,u,f,w,q}}]

Random bullet points:

Input is provided via prompt.
I'm currently supporting inputs 3, 4, 6, 8.
From your options, I chose the following plotting styles:

Full circles.
Lines from endpoint to endpoint, unless a relevant intersection lies outside, in which case I'll hardcode the extent.
No points.
Workings are black, polygons are red - not for aesthetic but for golfing reasons.

There's some serious code duplication between the polygons. I think at some point I'll just do a single construction for all of them, enumerating all lines and points and circles along the way, and then just reduce the Switch to select the relevant circles and lines for each construction. That way I could reuse a lot of primitives between them.
The code contains a lot of boilerplate functions which determine all the relevant intersections, and create circles from two points.
With that in place, I will be adding more polygons in the future.

Here is the ungolfed code:

S = Solve;
n = Norm;
A = Circle;
L = Line;
c = {#, Norm[# - #2]} &
{a_, b_List}~p~{c_, d_List} :=
 a + l*b /. # & @@ S[a + l*b == c + m*d, {l, m}]
{a_, b_List}~p~{c_, r_} := a + l*b /. S[n[c - a - l*b] == r, l]
{c_, r_}~p~{d_, q_} := {l, m} /.
  S[n[c - {l, m}] == r && n[d - {l, m}] == q, {l, m}]
q = {0, 0};
r = {1, 0};
a = q~c~r;
b = r~c~q;
Graphics@Switch[Input[],
  3,
  {
   s = # & @@ p[a, b];
   A @@@ {a, b},
   Red,
   L@{q, r, s, q}
   },
  4,
  {
   k = {q, r};
   {d, e} = a~p~b;
   j = {d, e - d};
   d = k~p~j~c~q;
   {e, f} = j~p~d;
   A @@@ {a, b, d},
   L /@ Accumulate /@ {k, j},
   Red,
   L@{q, e, r, f, q}
   },
  6,
  {
   d = {q, r};
   e = # & @@ d~p~a;
   f = e~c~q;
   {g, h} = a~p~f;
   {i, j} = a~p~b;
   A @@@ {a, b, f},
   L@{# - 2 #2, # + 2 #2} & @@ d,
   Red,
   L@{r, i, g, e, h, j, r}
   },
  8,
  {
   k = {q, r};
   {d, e} = a~p~b;
   j = {d, e - d};
   d = k~p~j~c~q;
   {e, f} = j~p~d;
   g = e~c~q;
   h = q~c~e;
   i = r~c~e;
   {o, s} = g~p~h;
   {t, u} = g~p~i;
   o = {o, 2 s - 2 o};
   s = {t, 2 u - 2 t};
   {t, u} = o~p~d;
   {v, w} = s~p~d;
   A @@@ {a, b, d, g, h, i},
   L /@ Accumulate /@ {k, j, o, s},
   Red,
   L@{q, t, e, v, r, u, f, w, q}
   }
  ]

And here are the outputs:


Calculate the square of an integer with restrictions

CJam, puts on his glasses
q~33c

(*_*)

(*_")>⌐■-■

(⌐■_■)

"]sG>4%,)

Input via STDIN
Try the code here
Note that * in the code is not used as multiplying, but as a join operator
Also note that the cool part of the code is not just string, half of it is actually the code involved in finding the square. So.. DEAL WITH IT
This will help you in dealing with it:
q~33c                    "Read the number and put ASCII character 33 on stack with it"
(                        "Decrease it to get ASCII code 32 character, which is a space";
 *_                      "Repeat the space input number times and make another copy";
   *                     "Put that many spaces in between each space. Now we have";
    )                    "n*n spaces string. We take out the last space out of it";
(                        "Decrement the space to get ASCII 31 character";
 *                       "Fill the n*n - 1 spaces with that to get 2*n*n - 3";
  _                      "string. Then copy it again.";
   ")>⌐■-■               "Put the sun glasses in";
(⌐■_■)                   "Wear the sun glasses. Be cool.";
"]s                      "Add everything to a single string of 4*n*n - 6 + 16"
   G>                    "length. Remove first 16 characters";
     4%                  "Take every 4th character from that string to get n*n - 1"
       ,)                "length string. Take length and increment to get n*n";


Python 2, 375 360 345 343 bytes

from itertools import*;P=product
def f(S,M):(l,t),(r,b)=S;(L,T),(R,B)=M;u,v,x,y=(L>=r)+(l<L),(T>=b)+(t<T),(R>=r)+(l<R),(B>=b)+(t<B);return[S]if v==y!=1or u==x!=1else[list(p(p(*zip(*(S+M))),repeat=2))[[43,197,6,199,9,231,142,229,53,189,134,181][int(i,36)]]for i in '38,491,258,2058,8,4B,28,208,7,41,27,461,,4,2,4A'.split(',')[u+2*v+4*x+8*y-12]]

Try it online!

EDITS: -15 from suggestions from @notjagan; another -15 by re-encoding the array of solution rectangles to int36 format and a short lookup table; another -2 by replacing product with p as per @musicman.

A function that takes two rectangles, each rect being a tuple of ((left,top), (right,bottom)); returns a list of the resulting rectangles.

The basic strategy:

     |     |
 0,0 | 1,0 | 2,0
-----A-----+-----
     |     |
 0,1 | 1,1 | 2,1
-----+-----B-----
     |     |
 0,2 | 1,2 | 2,2
     |     |

In the above diagram, the points A and B are the upper left and lower right, respectively, of the 'Source' rectangle (the first rect).

We find the placement of each of the the upper left (u,v) and lower right (x,y) of the 'Mask' rectangle in that grid.

If both these points are in the first or last column; or first or last row; then there is no overlap; and we can return just the Source rect.

Otherwise, there are 16 cases remaining; for example, the OP's first example is the case we can label (1,1),(2,2). Each case can be mapped to a set of resulting rectangles whose corners are always coordinates with horizontal values in either Source rectangles left,right, or the Mask rectangles left,right; and similarly for the vertical values, the Source's top,bottom or the masks.

For example, for the (1,1),(2,2) case, the rectangles would be ((l,t),(T,r)) and ((l,T),(R,b)), where l,t,r,b and L,T,R,B are the left, top, right and bottom of the Source and Mask rectangles, respectively.

So we can create a lookup table that maps the coordinates to the set of all such possible combinations (which is what the product(product(*zip(*))) bit is about) to a set of rectangles that should be provided for each of the cases (which, after some golfy-decompression, is what the rest of the list stuff is about).


Ruby, 250
s=gets
e=7-"FBOSN C".index(s[0])/2+(s[1]==?l?3:0)
x=s.reverse!.to_i
e+="Frl".index(s[2])?x:0
t="trigonal "
puts [["linear",b="bent",b],[t+"planar",t+p="pyramidal","T-shaped"],["tetr"+h="ahedral","seesaw"],[t+"bi"+p,"square "+p],["oct"+h]][x-2][e/2-x]

Note that with the rules as they are, AX2E3 and AX4E2 are not possible with the given elements, so they are not supported. All test cases passed.
with comments
s=gets                                     #get input with newline attached
e=7-"FBOSN C".index(s[0])/2+(s[1]==?l?3:0) #calculate the number of electrons (not lone pairs) from A. Note the addition required to differentiate C and Cl.
x=s.reverse!.to_i                          #reverse the input string so the number is at the beginning (after the newline) and evaluate the string as a number to get X.
e+="Frl".index(s[2])?x:0                   #if the character after the number is in "Frl" we have a halogen so increment number of electrons accordingly.
t="trigonal "                              #as "trigonal " goes at the beginning of the string, we cannot define it on the fly, it is defined as a constant here.
                                           #array of outputs below. note the subscripts at the end: x-2 to put it in the range 0..4 and e/2-x to convert e into the actual number of lone pairs.
puts [["linear",b="bent",b],[t+"planar",t+p="pyramidal","T-shaped"],["tetr"+h="ahedral","seesaw"],[t+"bi"+p,"square "+p],["oct"+h]][x-2][e/2-x]


CJam, 20 14 bytes
qN/_z{S-}#f>N*

Algorithm:

We first split the input on newlines and take a copy (qN/_)
Then the smallest column with non space character is calculated by transposing the newline separated array and then simply looking for the index of the first non-all-space row (z{S-}#)
Then we simply remove that many characters away from each line (f>)
Finally, we join by newline again (N*)

Code Expansion
qN/               e# Read the entire input and split it on newline
   _z             e# Take a copy and transpose rows with columns.
                  e# Now we would have a bunch of all space rows. These rows are the ones
                  e# we want to remove (in form of columns)
     {  }#        e# Get the index of the first item from the transposed array that returns
                  e# true for this block
      S-          e# From each part, remove spaces. If the part is all-space, it will return
                  e# an empty string, which is false in CJam. We finally will get the index
                  e# of the first non-all-space row (or column)
          f>      e# We take that index and remove that many characters from starting of each
                  e# row of the initial newline separated input
            N*    e# Join the array back using newlines and automatically print the result

Try it online here


Let's abbreviate those numbers! Now reverse?

PHP, 234 224 213 201 205 bytes
for(;$x=$argv[++$n];){$y=str_replace(",","",$x)/1e3;for($i=0;$y>999;$i++)$y=($y|0)/1e3;echo(A<$c=substr($x,strlen($x)-1))?number_format($x*[k=>1e3,m=>1e6,b=>1e9][$c]):($i?($y*10|0)/10:$y).kmb[$i]," ";}

6 bytes saved by insertusernamehere, 4 bytes inspired by that.

takes input from command line arguments, prints results space-separated with a trailing separator
expects lower case abbreviation
run with -r

-2 bytes if underscore as separator is ok: Replace " " with _.
-1 byte if correct rounding is ok: Replace ($y*10|0)/10 with round($y,1).
-17 bytes for PHP 7.1: Replace substr($x,strlen($x)-1) with $x[-1].

80 (63) bytes for expanding one argument only:
<?=number_format(($x=$argv[1])*[K=>1e3,M=>1e6,B=>1e9][substr($x,strlen($x)-1)]);

save to file, then execute (or replace <?= with echo +space and run with -r.


Excel, 153 149 Bytes

=IF(OR(A1<17,A1>99,AND(A1>19,A1<70)),A1,IF(A1<20,"10+"&A1-10,IF(A1<80,"60","4*20")&IF(A1=80,,IF(MOD(A1,20)>16,"+10+"&MOD(A1,20)-10,"+"&MOD(A1,20)))))

I'm sure this could be better, I struggled to find an efficient way to account for #80.

edit: Consolidated the 'Normal' cases better to save 4 bytes.  #80 still sucks.

Can't find a specific answer on here, not sure the rules of code-golf tbh.  Can I use multiple cells in Excel, and add the byte count of each?

ie. For an input in cell A1

A2: 11 Bytes

=MOD(A1,20)

A3 (result): 125 Bytes

=IF(OR(A1<17,A1>99,AND(A1>19,A1<70)),A1,IF(A1<20,"10+"&A1-10,IF(A1<80,"60","4*20")&IF(A1=80,,IF(A2>16,"+10+"&A2-10,"+"&A2))))

For a total of 136?


Funciton, 1222 bytes

Apart from numeric literals, there are two ways I can produce a value (any value at all) in Funciton: stdin and lambda expressions. Stdin is a single box while a full lambda expression requires more syntax, so I’m going with stdin. However, while stdin could be anything, all of the following work regardless of what input is provided.

All of the library functions used here existed before the challenge was posted.

0 (40 bytes in UTF-16)

╔╗┌┐
║╟┤└┼┬┐
╚╝└─┘└┘

This uses the raw syntax for less-than. A value is never less than itself, so the result of this is 0.

1 (52 bytes in UTF-16)

╔╗┌─╖┌─╖
║╟┤⌑╟┤ɕ╟
╚╝╘═╝╘═╝

⌑ returns a lazy sequence containing a single element and ɕ counts the number of elements. (The lazy sequence is lazy enough that this snippet doesn’t actually evaluate stdin at all!)

2 (70 bytes in UTF-16)

╔╗┌─╖┌─╖┌─╖
║╟┤⌑╟┤ʂ╟┤ɕ╟
╚╝╘═╝╘═╝╘═╝

= 2¹. ʂ generates all subsequences of a sequence, and thus turns a sequence of n elements into one with 2ⁿ.

3 (88 bytes in UTF-16)

╔╗┌─╖┌─╖┌─╖┌─╖
║╟┤⌑╟┤ʂ╟┤ɕ╟┤♯╟
╚╝╘═╝╘═╝╘═╝╘═╝

= 2 + 1. ♯ increments a value by 1.

4 (88 bytes in UTF-16)

╔╗┌─╖┌─╖┌─╖┌─╖
║╟┤⌑╟┤ʂ╟┤ʂ╟┤ɕ╟
╚╝╘═╝╘═╝╘═╝╘═╝

= 2².

5 (106 bytes in UTF-16)

╔╗┌─╖┌─╖┌─╖┌─╖┌─╖
║╟┤⌑╟┤ʂ╟┤ʂ╟┤ɕ╟┤♯╟
╚╝╘═╝╘═╝╘═╝╘═╝╘═╝

= 4 + 1.

6 (106 bytes in UTF-16)

╔╗┌─╖┌─╖┌─╖┌─╖┌─╖
║╟┤⌑╟┤ʂ╟┤ɕ╟┤♯╟┤!╟
╚╝╘═╝╘═╝╘═╝╘═╝╘═╝

= 3 factorial.

7 (110 bytes in UTF-16)

┌───┐┌─╖┌─╖┌─╖╔╗
│┌─╖├┤ɕ╟┤ʂ╟┤⌑╟╢║
└┤A╟┘╘═╝╘═╝╘═╝╚╝
 ╘╤╝

= A(2, 2) (Ackermann function).

8 (118 bytes in UTF-16)

┌────┐┌─╖┌─╖┌─╖╔╗
│┌──╖├┤ɕ╟┤ʂ╟┤⌑╟╢║
└┤<<╟┘╘═╝╘═╝╘═╝╚╝
 ╘╤═╝

= 2 << 2 (shift-left).

9 (128 bytes in UTF-16)

┌───┐┌─╖┌─╖┌─╖┌─╖╔╗
│┌─╖├┤♯╟┤ɕ╟┤ʂ╟┤⌑╟╢║
└┤×╟┘╘═╝╘═╝╘═╝╘═╝╚╝
 ╘╤╝

= 3 × 3.

10 (146 bytes in UTF-16)

┌───┐┌─╖┌─╖┌─╖┌─╖┌─╖╔╗
│┌─╖├┤♯╟┤ɕ╟┤ʂ╟┤ʂ╟┤⌑╟╢║
└┤+╟┘╘═╝╘═╝╘═╝╘═╝╘═╝╚╝
 ╘╤╝

= 5 + 5.

42 (170 bytes in UTF-16)

┌──────┐┌─╖┌─╖┌─╖┌─╖┌─╖╔╗
│┌─╖┌─╖├┤!╟┤♯╟┤ɕ╟┤ʂ╟┤⌑╟╢║
└┤♯╟┤×╟┘╘═╝╘═╝╘═╝╘═╝╘═╝╚╝
 ╘═╝╘╤╝

= 6 × (6 + 1).


Vim, 85, 76, 66, 52 keystrokes/bytes
When I first looked at this challenge, I thought "This is perfect for vim!" And then when I tried it everything went wrong. Here it is, in all of it's messy hacky glory:
:se ve=all|s/ /\r\r\r/g
qqGo<esc>?\<.\S
lDjP@qq@qG?.
jdG

Try it online, thanks to the (mostly) backwards compatible V interpreter.
Explanation:
At first I thought I could do this beautifully simple 37 byte version:
:se ve=all
qq:g/\S\S/norm ^lDjP
@qq@q

Unfortunately, it's not that simple. Let's take it line by line:
:se ve=all

This enables a feature called 'virtual editing'. It allows the cursor to move to columns that don't exist yet. This answer would be basically impossible without it.
Now we need to separate out the words onto different lines. So we'll replace each space with 3 newlines. Since this is an ex command we can run it simultaneously with our last ex command :se ve=all by seperating the two with a bar.
|s/ /\r\r\r/g

Now the buffer looks like this:
Programming

Puzzles

and

code-golf

Here's where the fun begins. We set up the traditional recursive macro with: qq, and then call this:
G               " Move to the last line
 o<esc>         " Append an extra newline

?               " Search backwards for
 \<.            " Any character at the beginning of a word
    \S          " Followed by a non-space character
l               " Move one character to the right
 D              " Delete eveything until the end of this line
  j             " Move down one line
   P            " Paste what we just deleted

Then we finish the recursive macro with @qq@q. At this point, we have all of the diagonals, we just need to do a little clean up.
G                   " Move to the last line
 ?.                 " Search backwards for any character
j                   " Move down one line
 dG                 " Delete until the end of the buffer


JavaScript (ES6), 83 bytes
s=>s.replace(s=/(^|[ṅcCjJñkKgG])[aeiou]/g,(_,c)=>o=(s+s).search(c)%10+o,o='')&&o

Try it online!
How?
We use the following regular expression to match either the beginning of the string or one of the Kaadi consonants, followed by a vowel:
/(^|[ṅcCjJñkKgG])[aeiou]/g

For each match in the input string, we invoke the following callback function that takes the content c of the capturing group as parameter:
(_, c) => o = (s + s).search(c) % 10 + o

We find the value of the consonant by looking for its position in the regular expression (coerced to a string by adding it to itself).
The consonants are ordered in such a way that their value is equal to their position modulo 10:
string   : /  (  ^  |  [  ṅ  c  C  j  J  ñ  k  K  g  G  ]  )  [  a  e  i  o  u  ]  /  g
position : 0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 ...
modulo 10: -  -  -  -  -  5  6  7  8  9  0  1  2  3  4  -  ...

When we match the beginning of the string instead of a consonant, c is an empty string whose position in the regular expression is 0 -- which, conveniently, is the expected result in that case.
Finally, we insert this digit at the beginning of the output string o.


How to find the item in a list whose f(item) is the smallest?

Use key property of min

As @vaultah said, use min(l,key=f). min(l,key=f) takes the minimum of f(i) for i in l.

It is also possible to apply this to max, and sorted. For example, max(l,key=f) is the maximum of f(i) for i in l. For sorted, the usage would be: sorted(l,key=f).


Charcoal, 99 91 bytes

Ａ⁻⁹¹ＮθＡ¹³η:(Ｗθ«Ａ⌊⟦θη⟧ζＡ⁻θζθＡ⁻η¹ηＦζ«↑⁴↖.\↑²←|=↓³←↙¹↓.Ｐ⁶↓²Ｐ⁶↓¹Ｐ______←| »¿θ«Ｍ⁹↑Ｍ³→×=⁻×⁸ζ³↑Ｍ⁴←

Try it online! Link is to verbose version of code. Actually the real version is only 83 70 bytes:

Ｆ¹⁵Ｆι⊞υκ:(Ｆ⁻⁹¹Ｎ«Ｆ¬⊟υ«Ｍ³±⁹×=⁺⁵×⁸⊟υ↑Ｍ⁴←»↑⁴↖.\↑²←|=↓³←↙¹↓.Ｐ⁶↓²Ｐ⁶↓¹Ｐ×_⁶←|←

Explanation:

Ｆ¹⁵Ｆι⊞υκ

Populate an array providing information as to where the shelves go and how long they are.

:(

Print an unhappy face, although this will be immediately overwritten by the first bottle of beer (if any).

Ｆ⁻⁹¹Ｎ«

Loop through the remaining bottles of beer.

   Ｆ¬⊟υ«

Check to see whether a shelf needs to be drawn.

        Ｍ³±⁹×=⁺⁵×⁸⊟υ↑Ｍ⁴←»

Print the shelf and position ready to draw the next bottle above it.

   ↑⁴↖.\↑²←|=↓³←↙¹↓.Ｐ⁶↓²Ｐ⁶↓¹Ｐ×_⁶←|←

Draw a bottle and position ready to draw another bottle.


Standardize the Samples (Compute the z-Score)

R, 51 45 38 37 bytes

Thanks to Giuseppe and J.Doe!

function(x)scale(x)/(1-1/sum(x|1))^.5

Try it online!


Can I make that shape with blocks, slabs, and stairs?

Python - 525 491 478 430 bytes

r=range
def t(s):
 m=s.find("\n")+1
 for q in r(4):
  try:
   for i in r(-q%2,m-1,2):
    for j in r(-q/2,len(s)/m,2):
     k,g=j*m+i,""
     b=[k,k+1,k+m,k+m+1]
     for z in b:g+=a(s,z)
     for z in b:
      if a(s,z)!="d":s=s[:z]+`dict(dddd=0,zzdd=3,ddzz=2,zzzd=7,zzdz=6,zdzz=5,dzzz=4,zzzz=1)[g]`+s[z+1:]
   return s
  except:d
def a(v,i):
 try:
  if v[i]!="\n":return v[i]
  return "d"
 except:return "d"

Explanation: This is my first code golf, so it might not be optimal, but here's how it works. The function t(s) gives the result for the string passed in. First, it finds the number of columns, then goes through the four possible distinct translations by 1 (none, left, up, up-left) and tries to solve it for each one. It looks at each 2x2 block and maps it to a valid block number, given by a dictionary, and changes the zeros to the number.

If it finds one not in the dictionary, it abandons that specific offset and starts over with the next one. If it goes through all 4 offsets without finding a valid solution, it ends without outputting anything. a(v, i) allows for the default value outside the string, and ignores newline characters. Although it may end up with partial solutions through the duration of the run, it will always override them with the final correct one if it exists.

Edit: A different mapping of characters is used: . -> d, 0 -> z, all other numbers go to themselves. This applies to both input and output.


Husk, 9 bytes
Λ≡½hÖ▼Ẋz-

Try it online! (Version with formatting header to allow pasting testcases: Try it online!)
Explanation
If we compute differences from each binary sequence to the next with an element-by-element subtraction, we will get a series of results each containing a single -1/+1 on the flipped bit and a 0 on all other bits. In order for this Gray code to be Beckett, the subsequence of -1 lists must be identical to the subsequence of +1 lists (except for the sign).
As noted by Unrelated String we don't need to check the last element against the first, since it will always consist of a single 1 turning into a 0.
 Λ≡½hÖ▼Ẋz-    Input: list of binary sequences
       Ẋ      For each pair of adjacent sequences:
        z-       subtract the first from the second element by element
     Ö▼       Sort by the minimum (in place): all the -1 sequences move to the beginning
    h         Discard the last (would match the final sequence turning into the first)
   ½          Group the sequences into two lists of equal length
                (the first will contain the -1s, the second the +1s)
 Λ            Check that the two elements
  ≡           Have the same distribution of zeros/nonzeros


Javascript - 140 132

k=1,s=", ",t=" o'clock",x="";while(k<11)x+=k+++s+k+++s+k+++t+s+k+++t+" rock,\n";alert(x+"We're gonna rock around the clock tonight.")

The fact, that 11 is made out of two 1's let me pass the rules I guess.

Explanation

The k+++s is equal to (k++)+s, so it adds k first to x, then increments k and then it adds s to x. This process will be done three times before it adds the last sentence.


Oasis, 5 bytes

Code

cd+2V

Extended version

cd+211

Explanation

1 = a(0)
1 = a(1)
2 = a(2)

a(n) = cd+
       c      # Calculate a(n - 2)
        d     # Calculate a(n - 3)
         +    # Add them up

Try it online!


Haskell, 36 35 bytes
{-{--}--}main=putStr"Hello, world!"

Try it online!
Test sloc
Since sloc is regex based it is a very good guess to think it cannot identify nested comments.  And if we take a look we see that indeed it cannot.  If we nest two comments as so:
{-{--}-}

sloc identifies one line of source and one line of comment.  Based on these observations my best guess is that the regex it is using is
(\{-((?!-\}).)*-\}|--[^\n]*)

If we pop this into a regex engine we will see it matches the nested comment as so:
      code
      ^^
{-{--}-}
^^^^^^
comment

Ok so we broke it, however this has the opposite of the intended effect.  We want sloc to think our code is a comment rather than our comment is code.  So we add a "line comment marker" to the part of the comment sloc thinks is code, so that sloc thinks a line comment is being started.
{-{--}--}

So to sloc there are two comments the block comment {-{--} and the line comment --} but to haskell which actually parses comments, it is all one block comment.
So then we just add our code after.  Sloc thinks this is still a comment and Haskell knows it is not.


Python 2 with SWI Prolog ('typical' install), on Windows, 595 565 bytes.
import sys,subprocess as w;o='left right top bottom centerX centerY width height'
g={k:v for k,v in [l.strip().split() for l in sys.stdin.readlines()]};s='L,R,T,B,C,D,W,H';
open('t','w').write(
":-use_module(library(clpfd)).\nr(%s):-L#=R-2*(R-C),L#=R-W,L#=C-W//2,B#=T-2*(T-D),B#=T-H,B#=D-H//2,%s."%
(s,','.join('writeln(%s)'%x for x in s.split(','))));r='\n'.join([a+' '+b for (
a,b) in zip(o.split(),w.check_output("swipl -q -f t -t r(%s)."%(','.join(g.get(
x,x[0].replace('centerY','d').upper()) for x in o.split()))).split('\r\n'))])
print '!' if '_' in r else r

e.g. with a text file for input, containing:
right 14
centerX 10
top 40
height 20

it does this:
D:\>type rectin.txt|c:\python27\python.exe d:\rect.py
left 6
right 14
top 40
bottom 20
centerX 10
centerY 30
width 8
height 20

And in the error condition if the contents of the stdin file are not enough to calculate the other values, it does this:
D:\>type rectin.txt|c:\python27\python.exe d:\rect.py
!

NB. It relies on swipl.exe being in the PATH
Explanation
I started writing in Python, got bored of expressing all the possible combinations of relationship (each one can be derived from three different combinations). I thought "must be a job for Prolog". So I installed a Prolog, headed for a tutorial, and got something that just about works. It's this:
:-use_module(library(clpfd)).

r(L,R,T,B,C,D,W,H):-
    L#=R-2*(R-C),
    L#=R-W,
    L#=C-W//2,
    B#=T-2*(T-D),
    B#=T-H,
    B#=D-H//2,

    writeln(L),
    writeln(R),
    writeln(T),
    writeln(B),
    writeln(C),
    writeln(D),
    writeln(W),
    writeln(H).

It uses the clpfd library (part of the 'typical install' requirement), which provides 'declarative integer arithmetic'. This gives the big advantage that I only need to define Left in terms of (Right and CenterX), (Right and Width), (CenterX and Width). From that, it can derive Right, Center and Width. (Same with the vertical set Top/Bottom/CenterY/Height).
This also means I don't have to check which specific values are provided; I give all the available values and placeholders for the rest, and it either calculates the answers, or outputs some unknown variable placeholders.
Being extremely novice at Prolog, handling STDIN was too much for me right now, so I wrapped it with Python. I don't have an ungolfed version of the Python, but it's not doing anything too amazing; it reads STDIN into a dictionary of {measurement:value} pairs, then puts them in the preset order the Prolog code is expecting, merged with the uppercase first letter of the unknowns.
(There's an annoyance where all the measurements are unique by first letter, except centerX and centerY, so it replaces centerY with D).
Then it writes the Prolog script out to a file, shells out to Prolog to run it and read the result, parses the number output and pairs them up with the measurements in order.
Then checks if any of the outputs were uncomputable and throws an error (!), otherwise prints the result.


Shortest a -> b -> (a -> b) function in Haskell

Your example can be shrunk by getting rid of the anonymous function on the right-hand side:

f a b x = snd ([a,x],b)

This works because the type a -> b -> a -> b is equivalent to a -> b -> (a -> b) in Haskell.


Retina, 55 38 bytes

i`^(([elp])|[^ghos]|(?<-2>.))*
$.&$*_<

Try it online! (The first line just allows running several test cases at once.)

Explanation

The problem is essentially to find the longest prefix that doesn't have an unmatched closing parenthesis. Except that we can use either e, l or p in place of ( and either g, h, o or s in place of ).

Hence, this solution is almost a textbook example of balancing groups. I won't go into too much detail about how they work, as this code is essentially the same as the standard example you can read up on in my SO answer on balancing groups.

The entire program is therefore a single regex substitution. The i activates case-insensitivity. Then we either match a pellet with [elp] and increment the depth counter (in the form of the capture stack of group 2), or we match something that isn't a ghost with [ghos] or we match a ghost with . and decrement the depth counter by popping from stack 2. Of course, in principle this allows matching a pellet with the [^ghos] section or a non-ghost with the . section, but thanks to greedy matching and the way the regex is backtracked, these possibilities are never attempted by the regex engine.

The substitution then uses two Retina specific features: $* repeats the character to its right as many times as specified by the token on its left. That token is $.& which is the length of the entire match. This just means that we replace each character in the match with a _. And then we also append a < to those underscores. The part of the input that isn't eaten simply remains unaffected by the substitution.


K5, 53 45 bytes

{{,/(b+a&~b:x*&\a:9=y){$[x;x#" ";y]}'y}[x]'y}

In action:

  {{,/(b+a&~b:x*&\a:9=y){$[x;x#" ";y]}'y}[x]'y}[4;(,"a";"\t\tb\tc";,"d")]
(,"a"
 "        b c"
 ,"d")

I just want the record to show that this question is morally reprehensible.


PowerShell, 111 104 bytes

$z=$args;1..4|%{($z=-join($z-split'\B'|group|%{for($c,$n=$_.Count,$_.Name;$c-gt9;$c-=9){"9$n"}"$c$n"}))}

Try it online!


Perl, 333

$_=<>;$c{$&}++while/./g;@c=sort{$c{$b}<=>$c{$a}}keys%c;$d{$&.$1}++while/.(?=(.))/g;sub f{my$x=shift;if(my$c=pop@$x){for(grep!$_[$_],0..7){my@y = @_;$y[$_]=$c;f([@$x],@y)}}else{for(0..7){$z=$_[$_];$c+=$d{$z.$_}+$d{$_.$z}for@{$a[$_]}}$c<$m?($m=$c,@n=@_):1}}while(@c){$m= ~0;f[splice@c,0,8];push@{$a[$_]},$n[$_]for 0..7}print@$_,$/for@a

Here's an attempt to optimize for rule #2. After my comment, above, and in lieu of answers taking that rule into account (cf. high question rating), I thought that I owe some effort here...

Solutions that don't optimize for rule #2 can produce output very far from optimal. I checked long natural English text ("Alice in Wonderland", actually), pre-processed (lower case letters only), and e.g. Perl script from OJW's answer, result being

2: ermx
3: tdfz
4: alp
5: oub
6: ick
7: nwv
8: hgj
9: syq

er alone ruins it, plus some other pairs should never have ended on the same key...

Btw, zxqjvkbpfmygwculdrshnioate are letters sorted, frequency ascending, from that text.

If we try to solve it easy way (hoping for -35 bonus, maybe) and place letters one by one, choosing available key by minimal pair-wise count, we can end with e.g.:

slbx
hdmz
nrf
iuj
ogv
awk
tcp
eyq

I don't post code for this (wrong) solution here. E.g., note, c is more frequent than w and is placed first. tc (ct) pairs are obviously less frequent than ac (ca) - 43+235 against 202+355. But then w ends up with a -- 598+88. We end with pairs aw and tc (964 total), though it would be better ac and tw (635 total). Etc..

So, next algorithm tries to check each 8 remaining (or 2, if last) most frequent letters against letters already on the keypad, and to place them so that pair-wise count is minimal.

$_=<>;                          # Read STDIN.
$c{$&}++while/./g;              # Count letters (%c hash).
@c=sort{$c{$b}<=>$c{$a}}keys%c; # Sort them by frequency, ascending
$d{$&.$1}++while/.(?=(.))/g;    # (@c array), and count pairs (%d hash).

                                # Next is recursive sub that does the job.
                                # Some CPAN module for permutations
                                # would probably do better...
                                # Arguments are reference to array of what's
                                # left un-placed of current 8-pack of letters,
sub f{                          # and 8 element list of placed letters
    my$x=shift;                 # (or undefs).
    if(my$c=pop@$x){            # Pop a letter from 8-pack (if anything left),
        for(grep!$_[$_],0..7){  # try placing it on each available key, and
            my@y = @_;          # call sub again passing updated arguments.
            $y[$_]=$c;
            f([@$x],@y)
        }
    }else{                      # If, OTOH, 8-pack is exhausted, find sum of
        for(0..7){              # pairs count of current permutation (@_) and
            $z=$_[$_];          # letters placed in previous rounds (8-packs).
                                # @a is "array of arrays" - note, we didn't
                                # have to initialize it. First "8-pack" will
                                # be placed on empty keypad "automatically".
                                # We re-use undefined (i.e. 0) $c.

            $c+=$d{$z.$_}+$d{$_.$z}for@{$a[$_]}
        }
        $c<$m                   # Is sum for current placement minimal?
            ?($m=$c,@n=@_)      # Then remember this minimum and placement.
            :1
    }
}

while(@c){
    $m= ~0;                         # Initialize "minimum" with large enough
    f[splice@c,0,8];                # number, then call sub with each 8-pack
                                    # (and empty list of placed letters
                                    # from current round). On return,
                                    # @n will have optimal arrangement.
    push@{$a[$_]},$n[$_]for 0..7    # Then place it permanently on keypad.
}
print@$_,$/for@a                    # Show us what you've done.

Result is:

sdfz
hlmx
nrv
iyp
ogk
acq
twb
euj

I don't like the ac pair (The Cat being one of the characters, after all), but, still that's optimal letter placement for English, if my code is not wrong. Not exactly 'golfing' effort, just some working solution, ugly or not.


The longest consecutive traversal possible (number of edges)

APL (Dyalog Unicode), 17 bytes

≢⍉↑⊆⍨∨/≠/∨⍀⎕a∘.=⎕

Try it online!


Python 3, 116 bytes

def f(a):
 l=len(a);t=[0]*l;d=[1]*l
 while 1:
  i=0;yield t
  while not-1<t[i]+d[i]<=a[i]:d[i]*=-1;i+=1
  t[i]+=d[i]

Try it online!

Thanks Mnemonic for -1 byte.

Generator function. (thanks Dennis for reminding me, I forgot the feature exists) If the output should be printed to stdout then use print(t,flush=1) for 9 additional bytes, or if Python is called with -u, print(t) suffices for +1 bytes.

Stops with an error (IndexError). If you want to call this function and then continue the program, you have to catch it.


Jelly, 7 bytes

ÆḞÆDÆḞS

Try it online!

Explanation:

ÆḞÆDÆḞS Main link (Arguments: z)
ÆḞ      zth Fibonacci number's
  ÆD                           divisors'
    ÆḞ                                   Fibonacci numbers'
      S                                                     sum


Jelly, 2 bytes

_S

Try it here!

Takes the entering currents in the first argument, and the leaving currents in the second argument. _ subtracts them pairwise, leaving the single element from the longer list as-is, and S sums the result.


APL, 62

{1=3⌷⍵:2⌷+\⍵⋄0=2⌷⍵:(⍵[3]⌊3)⌷⍵[1],0,1⋄∇⍵[1],(∇⍵-0 1 0),3⌷⍵-1}⎕

{...}⎕: Takes evaluated input (space-separated numbers evaluates to a numerical array) and apply function to it.

1=3⌷⍵:: If n equals 1...
2⌷+\⍵: Return sum of first 2 elements (x+y)...
⋄0=2⌷⍵:: Else if y equals 0...
(⍵[3]⌊3)⌷⍵[1],0,1: Create numerical array [x,0,1] and return index min(n,3)...
⋄∇⍵[1],(∇⍵-0 1 0),3⌷⍵-1: Else return ∇(x,∇(x,y-1,n),n-1). (∇ is self-reference)

I have got a "hyper-raiser" operator, which takes a function and return next hyperoperation

{⍺⍺/⊃⍴/⌽⍵}

For example, +{⍺⍺/⊃⍴/⌽⍵} would be the multiplication function and +{⍺⍺/⊃⍴/⌽⍵}5 3 outputs 15.

But can't get it to recurse. Maybe someone else can do it.


JavaScript (ES6),  56  52 bytes
Returns a Boolean value.

a=>![...a,1].some(x=>t>0/x?1:(t+=x-1)*x<0?t=0:0,t=0)

Try it online!
Commented
The accumulator \$t\$ is decremented whenever an empty slot is encountered. For each non-zero value \$x\$, we update \$t\$ to \$max(t+x-1,0)\$. The test fails if we reach a non-empty slot (or the end of the list) with \$t>0\$.
a =>               // a[] = input
  ![...a, 1]       // append a '1' at the end of a[] to force a last test
  .some(x =>       // for each value x in the updated array:
    t > 0 / x ?    //   if x = 0, this test is always falsy (0 / 0 -> NaN)
                   //   if x ≠ 0 and t is greater than 0:
      1            //     failed: yield 1
    :              //   else:
      (t += x - 1) //     add x - 1 to t
      * x < 0 ?    //     if t is negative and x ≠ 0:
        t = 0      //       we have accumulated more empty slots than
                   //       we can consume here: set t to 0
      :            //     else:
        0,         //       do nothing
    t = 0          //   start with t = 0
  )                // end of some(); return the opposite result


05AB1E, 36 34 33 31 bytes

Ć4ô¤¨s¨Ch2ôJDg8@i6∍„..ª}ðý"[ÿ]ÿ

Try it online!


Shortest Gomoku (5 in a row) implementation

Jelly, 54 bytes

Ḋ,Z,ŒD$ŒrFs2ḢƇ<5Ȧ
0x⁹s⁴-;N1¦Ṅ©+Ɠœị®Ḋ¤$¿ṪṬṭ0x$Ʋ¹NƭƊƊ$Ç¿

Try it online!

A full program that reads input on stdin. For each loop through it prints the current player (1 or -1) and the 16x16 grid. Moves are input on stdin as a Python array (e.g. [3,2]) with or without the surrounding square brackets. The only validation done is to make sure that the relevant cell is empty. When there are 5 (or more) in a row, the program ends and prints out the winner and final grid.

If checking for a valid move can be omitted, 10 bytes can be saved:

Jelly, 44 bytes

Ḋ,Z,ŒD$ŒrFs2ḢƇ<5Ȧ
0x⁹s⁴-;N1¦Ṅ+ƓṪṬṭ0x$¹Nƭ¤ƲÇ¿

Try it online!

Conversely, if the w/b designation in the spec is strict, that costs 15 bytes:

Jelly, 69 bytes

ị“wb ”Ḣ
Ḋ,Z,ŒD$ŒrFs2ḢƇ<5Ȧ
0x⁹s⁴-;N1¦Ñ;”>ṄṛƲ©+Ɠœị®Ḋ¤$¿ṪṬṭ0x$Ʋ¹NƭƊƊ$Ç¿Ñ

Try it online!


SQL (PostgreSQL flavour), 284 244 232 210 175 bytes

A HUGE Thank You to @manatwork for essentially the whole thing now.
A nice verbose language that still came in under the byte size of the flag, with a bit of a margin :)
Basically builds the half of the flag with using parameters.  This is cross joined with 1 and -1 giving us both halfs of the flag and a means to order it by negating the number of #'s in the row.
SELECT rpad(rpad(L,X,'X'),35,P)||R FROM(VALUES('|',12,' ','|'),('|',10,'-','+'),('|',9,' ','|'),('|',6,' ','|'),('+',1,'-','+'))F(L,X,P,R),(values(-1),(1))G(O)ORDER BY(12-X)*O

Formatted and commented
SELECT rpad(rpad(L,X,'X'),35,P)||R --Build each row from parameters
FROM(VALUES           -- Parameters for each row
    ('|',12,' ','|'), -- Start Char, Num of #, Pad Char, End Char
    ('|',10,'-','+'),
    ('|',9,' ','|'),
    ('|',6,' ','|'),
    ('+',1,'-','+')
    )F(L,X,P,R),
    (values(-1),(1))G(O) -- Cross join with order modifier
ORDER BY(12-X)*O -- Order by modified number of #


Writing 513 in a MathGolf program will push three separated digits (5;1;3), instead of the number 513 itself.
In MathGolf there are therefore quite a lot of 1-byte builtins for numbers: -3 through and including 38; 60; 64; 100; 128; 256; 512; 1000; 1024; 2048; 3600; 4096; 10000; 86400; 100000; 1000000; 10000000; 100000000.

However, for other numbers it can sometimes be tricky to find the shortest way to generate it, so here an overview of the integers in the range [1, 1000]:

NOTE: This is W.I.P. I will add more when I have some time. I was unable to make an evaluation program to check all possibilities (thus far), so these were done by hand.. I've also made it a community wiki, so if anyone else finds shorter alternatives or wants to continue with the numbers, feel free to edit it.
Of course many variations can be found for certain numbers, as can be seen here and here. So the list below contains just one of the shortest variations.

-3-0:   d, c, b, 0
1-10:   1, 2, 3, 4, 5, 6, 7, 8, 9, ♂
11-20:  A, B, C, D, E, ☻, F, G, H, I
22-30:  J, K, L, M, N, O, P, Q, R, S
31-40:  T, ♥, U, V, W, X, Y, Z, Z), Z⌠
41-50:  Dx, J∞, Vx, K∞, K∞), L∞, L∞), M∞, 7², N∞       TODO: 2-byters for 45,47
51-60:  Ex, O∞, Wx, P∞, ♂f, Q∞, ╟╫, R∞, ╟(, ╟
61-70:  ☻x, T∞, Xx, ♦, ♦), U∞, U∞), V∞, V∞), W∞        TODO: 2-byters for 67,69
71-80:  Fx, X∞, Yx, Y∞, Y∞), Z∞, Z∞), Z∞⌠, ♦E+, ♦F+    TODO: 2-byters for 75,77,78,79,80
81-90:  Gx, Qx, Zx, Zx), Zx⌠, ♦K+, ♦L+, R■, ♂f, ♦O+    TODO: 2-byters for 84,85,86,87,90
91-100: Hx, Rx, ♦R+, T■, ♦T+, ♦U+, ♦V+, ♀⌡, ♀(, ♀      TODO: 2-byters for 93,95,96,97
TODO: Continue through 1000

Here is a universal constant-generating method in MathGolf. Example (generating 513):

û☺☻$

This defines a two-character string and takes its ord code. The ord code of ☻ is 2, and the ord code of ☺ is 1. The ord code of this string is therefore 2*256+1=513.

Taking the ord code also works for single characters. (Constants generated by this method are likely to be unoptimal.) This one returns 2.

'☻$

Also works for string length 3 and so on...

ùUTS$
83*256*256+84*256+85=5461077


Find the min and max number of substitutions

JavaScript (ES10),  169 168  161 bytes

Saved 7 bytes thanks to @KevinCruijssen

Takes the strings as (s)(t). Returns [min, max].

s=>t=>[[...Array(d=(g=(k,m=s.length,n=m,c)=>m*n?1+Math.min(g(k,m,n-1),g(k,--m,n),g(k-=c=s[m]!=t[--n],m,n)-!c):k?1/0:m-~n)())].flatMap((_,i)=>g(i)-d?[]:j=i)[0],j]

Try it online! (fast test cases)

Try it online! (a longer test case which may time out if TIO is overloaded)

Commented

Helper function \$g\$

\$g\$ is a function that computes the standard Levenshtein distance when it's called with \$k\$ undefined, or the edit distance with exactly \$k\$ substitutions when it's called with \$k\ge0\$. An additional offset of \$+1\$ is added to the result in both cases.

NB: It is presented separately for readability but must be defined within the scope of the main function so that the source string \$s\$ and the target string \$t\$ are defined.

g = (                         // g is a recursive function taking:
  k,                          //   k = allowed number of substitutions, or undefined
  m = s.length,               //   m = 1st pointer, initialized to the length of s
  n = m,                      //   n = 2nd pointer, initialized to the length of s
  c                           //   c = substitution cost
) =>                          //       (needs to be defined in the local scope)
  m * n ?                     // if both m and n are greater than 0:
    1 +                       //   add 1 to the final result
    Math.min(                 //   add the minimum of:
      g(k, m, n - 1),         //     recursive call for insertion with (m, n - 1)
      g(k, --m, n),           //     recursive call for deletion with (m - 1, n)
      g(                      //     recursive call for substitution:
        k -=                  //       set c if s[m - 1] is not equal to t[n - 1]
          c = s[m] != t[--n], //       and decrement k if c is set
        m, n                  //       use (m - 1, n - 1)
      ) - !c                  //     subtract 1 from the result if c is not set
    )                         //   end of Math.min()
  :                           // else (leaf node):
    k ?                       //   if k is not equal to 0 or NaN:
      1 / 0                   //     return +Infinity
                              //     (to make sure that this branch is not chosen)
    :                         //   else:
      m - ~n                  //     return m + n + 1

Main function

s => t =>                     // s = source string, t = target string
  [                           // the final result is a pair:
    [                         //   build an array containing:
      ...Array(d = g()),      //     d entries, where d = Levenshtein distance (+1)
    ]                         //
    .flatMap((_, i) =>        //   for each entry at position i in there:
      g(i)                    //     if the edit distance (+1) with i substitutions
      - d ?                   //     is not equal to d:
        []                    //       reject this entry
      :                       //     else:
        j = i                 //       append it to the array and copy i to j
    )[0],                     //   end of flatMap(); return the 1st entry (minimum)
    j                         //   followed by the last entry (maximum)
  ]                           // end of result


An optimization challenge with strange coins

Score = 26/14 ~= 1.857

import java.util.*;

public class LembikWeighingOptimisation {

    public static void main(String[] args) {
        float best = 0;
        int opt = 1;
        for (int n = 6; n < 32; n+=2) {
            long start = System.nanoTime();
            System.out.format("%d\t", n);
            opt = optimise(n, n / 2 + 1);
            float score = n / (float)opt;
            System.out.format("%d\t%f", opt, score);
            if (score > best) {
                best = score;
                System.out.print('*');
            }
            System.out.format(" in %d seconds", (System.nanoTime() - start) / 1000000000);
            System.out.println();
        }
    }

    private static int optimise(int numCoins, int minN) {
        MaskRange.N = numCoins;
        Set<MaskRange> coinSets = new HashSet<MaskRange>();
        coinSets.add(new MaskRange(0, 0));

        int allCoins = (1 << numCoins) - 1;

        for (int n = minN; n < numCoins; n++) {
            for (int startCoins = 1; startCoins * 2 <= numCoins; startCoins++) {
                for (int mask = (1 << startCoins) - 1; mask < (1 << numCoins); ) {
                    // Quick-reject: in n turns, do we cover the entire set?
                    int qr = (1 << (n-1)) - 1;
                    for (int j = 0; j < n; j++) qr |= mask << j;
                    if ((qr & allCoins) == allCoins && canDistinguishInNTurns(mask, coinSets, n)) {
                        System.out.print("[" + Integer.toBinaryString(mask) + "] ");
                        return n;
                    }

                    // Gosper's hack to update
                    int c = mask & -mask;
                    int r = mask + c;
                    mask = (((r^mask) >>> 2) / c) | r;
                }
            }
        }

        return numCoins;
    }

    private static boolean canDistinguishInNTurns(int mask, Set<MaskRange> coinsets, int n) {
        if (n < 0) throw new IllegalArgumentException("n");
        int count = 0;
        for (MaskRange mr : coinsets) count += mr.size();
        if (count <= 1) return true;
        if (n == 0) return false;

        // Partition.
        Set<MaskRange>[] p = new Set[Integer.bitCount(mask) + 1];
        for (int i = 0; i < p.length; i++) p[i] = new HashSet<MaskRange>();
        for (MaskRange range : coinsets) range.partition(mask, p);

        for (int d = 0; d < 2; d++) {
            boolean ok = true;
            for (Set<MaskRange> s : p) {
                if (!canDistinguishInNTurns((mask << 1) + d, s, n - 1)) {
                    ok = false;
                    break;
                }
            }

            if (ok) return true;
        }

        return false;
    }

    static class MaskRange {
        public static int N;
        public final int mask, value;

        public MaskRange(int mask, int value) {
            this.mask = mask;
            this.value = value & mask;
            if (this.value != value) throw new IllegalArgumentException();
        }

        public int size() {
            return 1 << (N - Integer.bitCount(mask));
        }

        public void partition(int otherMask, Set<MaskRange>[] p) {
            otherMask &= (1 << N) - 1;

            int baseline = Integer.bitCount(value & otherMask);
            int variables = otherMask & ~mask;
            int union = mask | otherMask;
            partitionInner(value, union, variables, baseline, p);
        }

        private static void partitionInner(int v, int m, int var, int baseline, Set<MaskRange>[] p) {
            if (var == 0) {
                p[baseline].add(new MaskRange(m, v));
            }
            else {
                int lowest = var & (1 + ~var);
                partitionInner(v,          m, var & ~lowest, baseline, p);
                partitionInner(v | lowest, m, var & ~lowest, baseline + 1, p);
            }
        }

        @Override
        public String toString() {
            return String.format("(x & %x = %x)", mask, value);
        }
    }
}

Save as LembikWeighingOptimisation.java, compile as javac LembikWeighingOptimisation.java, run as java LembikWeighingOptimisation.

Many thanks to Mitch Schwartz for pointing out a bug in the first version of the quick-reject.

This uses some fairly basic techniques which I can't rigorously justify. It brute-forces, but only for starting weighing operations which use at most half of the coins: sequences which use more than half of the coins aren't directly transferable to the complementary weighings (because we don't know the total weight), but on a hand-wavy level there should be about the same amount of information. It also iterates through starting weighings in order of the number of coins involved, on the basis that that way it covers dispersed weighings (which hopefully give information about the top end relatively early) without first crawling through a bunch which start with a dense subset at the bottom end.

The MaskRange class is a massive improvement on the earlier version in terms of memory usage, and removes GC from being a bottleneck.

20      [11101001010] 11        1.818182* in 5364 seconds
22      [110110101000] 12       1.833333* in 33116 seconds
24      [1000011001001] 13      1.846154* in 12181 seconds
26      [100101001100000] 14    1.857143* in 73890 seconds


"Hello world!", repeating each character n times


Jelly, 18 13 bytes

pS€żị"¥pỤỤị⁵s

Takes number of rows, number of columns and a flat list as separate command-line arguments.

My code is almost identical to the one in the twin challenge. The only differences are an additional Ụ (which inverts the permutation of the indices) and an s (to split the output into a 2D array).

Try it online!


C++, 44014022 / 164607120

It is in C++, uses 1 GB of memory, and took about 45 seconds to find this first pair.  I'll update the time once it finds them all.
Code below.  It first finds all pairs that generate 4 zeros, then whittles those down by simple trial (see the check method).  It finds pairs that generate 4 zeros by generating two large arrays, one which contains the first 4 low-order bytes of the state1 generator, and the second which contains the negative of the first 4 low-order bytes of the state2 generator.  These arrays are then sorted and searched for a match, which corresponds to the overall generator outputting 4 zeros to start.
The arrays are too big to store in memory, so it does the work in batches sized to just fit in memory.
Looks like the complete run will take ~12 hours.
Edit: Improved the code so it only takes ~1 hour to get all possible seeds.  Now it generates the tables into 256 different files, one for each first byte of output.  We can then process each file independently so we don't have to regenerate data.
Edit: Turns out you can generate the 256 subtables individually instead of all at once, so no disk needed.  Running time down to ~15 minutes using 256MB.
#include <stdio.h>
#include <stdint.h>
#include <algorithm>
using namespace std;

#define M1 65539
#define N1 4294967087
#define M2 65537
#define N2 4294965887
#define MATCHES 7

// M^-1 mod N
#define M1_INV 3027952124
#define M2_INV 1949206866

int npairs = 0;

void check(uint32_t seed1, uint32_t seed2) {
  uint32_t s1 = seed1;
  uint32_t s2 = seed2;
  for (int i = 0; i < MATCHES; i++) {
    s1 = (uint64_t)s1 * M1 % N1;
    s2 = (uint64_t)s2 * M2 % N2;
    if (((s1 + s2) & 0xff) != 0) return;
  }
  printf("%d %u %u\n", npairs++, seed1, seed2);
}

struct Record {
  uint32_t signature; // 2nd through 5th generated bytes
  uint32_t seed;      // seed that generated them
};
// for sorting Records
bool operator<(const Record &a, const Record &b) {
  return a.signature < b.signature;
}

int main(int argc, char *argv[]) {
  Record *table1 = (Record*)malloc((N1/256+1)*sizeof(*table1));
  Record *table2 = (Record*)malloc((N2/256+1)*sizeof(*table2));

  for (int i = 0; i < 256; i++) {  // iterate over first byte
    printf("first byte %x\n", i);

    // generate signatures (bytes 2 through 5) for all states of generator 1
    // that generate i as the first byte.
    Record *r = table1;
    for (uint64_t k = i; k < N1; k += 256) {
      uint32_t sig = 0;
      uint32_t v = k;
      for (int j = 0; j < 4; j++) {
        v = (uint64_t)v * M1 % N1;
        sig = (sig << 8) + (v & 0xff);
      }
      r->signature = sig;
      r->seed = k;
      r++;
    }
    Record *endtable1 = r;

    // generate signatures (bytes 2 through 5) for all states of generator 2
    // that generate -i as the first byte.
    r = table2;
    for (uint64_t k = (-i & 0xff); k < N2; k += 256) {
      uint32_t sig = 0;
      uint32_t v = k;
      for (int j = 0; j < 4; j++) {
        v = (uint64_t)v * M2 % N2;
        sig = (sig << 8) + (-v & 0xff);
      }
      r->signature = sig;
      r->seed = k;
      r++;
    }
    Record *endtable2 = r;

    sort(table1, endtable1);
    sort(table2, endtable2);

    // iterate through looking for matches
    const Record *p1 = table1;
    const Record *p2 = table2;
    while (p1 < endtable1  && p2 < endtable2) {
      if (p1->signature < p2->signature) p1++;
      else if (p1->signature > p2->signature) p2++;
      else {
        check((uint64_t)p1->seed * M1_INV % N1, (uint64_t)p2->seed * M2_INV % N2);
        // NOTE: may skip some potential matches, if p1->signature==(p1+1)->signature or p2->signature==(p2+1)->signature
        p1++;
      }
    }
  }
}


Python 2, 27 bytes

f=lambda n:n and n/5+f(n/5)

The ending zeroes are limited by factors of 5. The number of multiples of 5 that are at most n is n/5 (with floor division), but this doesn't count the repeated factors in multiples of 25, 125, .... To get those, divide n by 5 and recurse.


Average number of strings with Levenshtein distance up to 3

GAP and the automata package

The average number is the number of pairs of words of length \$n\$ with Levenshtein distance up to three, divided by \$2^n\$.

It is not very difficult to construct an nondeterministic finite automaton over the alphabet of pairs of bits that accepts the word \$(a_1,b_1)(a_2,b_2)\dots(a_n,b_n)\$ iff the binary words \$a_1a_2\dots a_n\$ and \$b_1b_2\dots b_n\$ have Levenshtein distance up to three. My version uses 14 states. This automaton can be transformed into a minimal deterministic one, which has 39 states. From its transition function we can get a matrix that describes the number of ways we can get from one state to another. Now counting the number of ways we can get from the initial state to some accepting state is just a matter of multiplication.

The implicit recurrance could be simplified because some values are always equal, and it might be solved to give a closed formula, but it seems to be good enough as is.

LoadPackage("automata");

nfa := Automaton("nondet", 14, 4,
     [[[1,5,9],[2,7,11],3,4,[5,13],[7,13],[7,14],14,
       [9,13],[11,13],[11,14],14,13,14],
      [[2,5,10],[3,7,12],4,0,[7,14],[5,14],0,7,
       [10,14],[12,14],12,0,14,0],
      [[2,6,9],[3,8,11],4,0,[6,14],[8,14],8,0,
       [11,14],[9,14],0,11,14,0],
      [[1,6,10],[2,8,12],3,4,[8,13],[6,13],14,[8,14],
       [12,13],[10,13],14,[12,14],13,14] ],
     [1], [1..14] );

dfa := MinimalizedAut(nfa);

size := NumberStatesOfAutomaton(dfa);;

mat := NullMat(size, size);;
for row in TransitionMatrixOfAutomaton(dfa) do
  for i in [1..size] do
    mat[i][row[i]] := mat[i][row[i]]+1;
  od;
od;

init := 0 * [1..size];;
init[InitialStatesOfAutomaton(dfa)[1]] := 1;;

fin := 0 * [1..size];;
for i in FinalStatesOfAutomaton(dfa) do
  fin[i] := 1;
od;

f := function(n)
  local res, intpart, fraction;
  res := init * mat^n * fin / 2^n;
  intpart := Int(res);
  fraction := res-intpart;
  Print("n = ", n, ". Average = ", intpart);
  if fraction <> 0 then
    Print(" ",fraction);
  fi;
  Print(".\n");
end;

Try it online!

Put it in a file, start gap and read the file with a command like Read("l3.gap");, then try something like f(20); or for i in [0..100] do f(i); od;.

Here are some results:

n = 0. Average = 1.
n = 1. Average = 2.
n = 2. Average = 4.
n = 3. Average = 8.
n = 4. Average = 15 1/2.
n = 5. Average = 28 13/16.
n = 6. Average = 50 15/16.
n = 7. Average = 85 23/64.
n = 8. Average = 135 27/32.
n = 9. Average = 206 77/256.
n = 10. Average = 300 181/256.
n = 11. Average = 423 67/1024.
n = 12. Average = 577 99/256.
n = 13. Average = 767 2793/4096.
n = 14. Average = 997 3931/4096.
n = 15. Average = 1272 3711/16384.
n = 16. Average = 1594 3985/8192.
n = 17. Average = 1968 48645/65536.
n = 18. Average = 2398 65249/65536.
n = 19. Average = 2889 64891/262144.
n = 20. Average = 3443 16339/32768.
n = 30. Average = 13385 268434611/268435456.
n = 40. Average = 34128 68719475971/137438953472.
n = 50. Average = 69670 281474976708241/281474976710656.
n = 60. Average = 124013 36028797018963093/72057594037927936.
n = 70. Average = 201155 295147905179352821071/295147905179352825856.
n = 80. Average = 305098 75557863725914323416001/151115727451828646838272.
n = 90. Average = 439840 309485009821345068724773101/
309485009821345068724781056.
n = 100. Average = 609383 9903520314283042199192993177/
19807040628566084398385987584.
n = 1000. Average = 660694208
669692879491417075592765655662501131600878007315958504652343992731469406953085\
076558248986759809911329746670573470716765741965803557696277249036098418660925\
245910485926514436588817162816398196367372136384565404686473871329212422972447\
846496629816432160699779855408885478776864478289024177325353755091/
133938575898283415118553131132500226320175601463191700930468798546293881390617\
015311649797351961982265949334114694143353148393160711539255449807219683732185\
049182097185302887317763432563279639273474427276913080937294774265842484594489\
5692993259632864321399559710817770957553728956578048354650708508672.
n = 10000. Average = 666066942458
[fractional part removed]

Pari/GP, 51 bytes

All the eigenvalues of the matrix are integers (could I have known or expected that?), and I found this formula for \$n\ge 2\$:

f(n)=(40+6*n-4*n^2)/2^n-83/2+331/12*n-6*n^2+2/3*n^3

Try it online!


15 languages, 68 66 65 bytes / 15^3 = 0.019...

Retina, Starry, Prelude, ETA, Axo, Labyrinth, Hexagony, Foo, Brian & Chuck, Gol><>, evil, Whitespace, Fission, ><> and GolfScript.

After a massive rewrite, I managed to fit in four more languages. The code contains the few tabs for Whitespace. Since Stack Exchange converts them to spaces, I've represented them with \t below:

#I5aeeNTH{\?      \t\t + +3;n@"8"ea9
15}7'`--~!@<"31"LSOe.\t
 \teaww`

I think I'm done adding languages (although adding only one might save some bytes in what I already have). I wonder if it's golfable though... 65 bytes for 15 languages is quite a jump from 32 bytes for 11 languages, and I've now got at least one useless character in there to make Foo work..

Retina prints 1

Try it online.

Luckily, the first line is a valid regex. However that regex obviously doesn't match the empty input, so the first stage (consisting of the first two lines) doesn't do anything.

The third line is on its own, so it's treated as a Match stage which, by default, counts the number of matches. However, the ` is a separator which tells Retina that the part in front of it is a configuration string (it doesn't happen to know any of the options given there) and the part after it is the regex. So the regex is empty and Retina finds exactly one match.

Starry prints 2

Try it online.

Starry ignores everything except spaces and +*,'`.. Each command is one of those characters in conjunction with the spaces since the last of those characters. So let's remove all the extraneous code:

       + +'`. `

Seven spaces followed by + pushes a 2. One space followed by a + duplicates it. ' is a conditional jump. It pops the top of the stack, which is truthy (positive), so it jumps to the corresponding label (where labels are indicated by ` and "corresponding" means "with the same number of leading spaces"), which is the first `. . without spaces in front of it then prints the top of the stack as a number.

Prelude prints 3

Try it online.

This assumes the Python interpreter which uses numeric output. Let's remove all the no-ops:

# 5        ?         + +3    8   9
15 7  -- !   31

The first voice does a bunch of stuff, but nothing of it matters, because there is no ! to print any of the results. The second voice pushes a 1, then a 5, then a 7. We take the difference of the last two to get -2, and then subtract that from the 1 to get 3. ! prints it. The third voice has only no-ops.

ETA prints 4

Try it online.

ETA ignores everything except the characters ETAOINSH (in any case). So the code as seen by ETA is:

IaeeNTHneaSOeea

I tries to read input but can't, so it pushes -1. a pushes the current line number plus 1, which is 2. e is divmod, which replaces those with 0 and 1 (or -1, I don't actually know, but it doesn't matter). The next e replaces both of them with 0.

Now the interesting part. NTHne is a base-7 number literal. N and e are just the delimiters, and the three digits are THN. That is 54 (where T is digit 1, H is 0 and n is 5). a pushes 2 once more. S subtracts it, resulting in 52 and O outputs it as a character (4). Now e tries divmod again, but the stack contains two zeroes, so the program terminates with an error (but doesn't pollute STDOUT while doing so).

Axo prints 5

Try it online.

This language was pretty much single-handedly responsible for the rewrite. I couldn't have the } on the first line because it would block for input in Axo (see revision history for what I'm talking about). For Axo, only this part of the code is relevant:

#I5aeeNTH{\

Luckily, Axo also has implicit 0s at the bottom of its stack, because # pops the top of the stack (to check if the next instruction should be skipped or not). The letters are all no-ops. Then 5 pushes a 5, { prints it, \ terminates the program. Quite simple, really.

Labyrinth prints 6

Try it online.

I'm truncating the code a bit, because the right half is never reached, and I'm also using t in place of \t, so that the columns line up correctly:

#I5aeeNTH{\
15}7'`--~!@
 teaww`

Now that letters, spaces and tabs are walls in Labyrinth, so the accessible code actually looks like this:

# 5      {\
15}7'`--~!@
      `

The instruction pointer will automatically follow that path. # pushes the depth of the main stack (0) and 15 turns it into a 15. } moves it off to the auxiliary stack, and we're not going to use it any more. That conveniently makes the top of the stack zero, so that the IP does not turn left onto the 5. 7 turns the zero into a 7, ' is a no-op. The ` is unary negation, so we get -7. Now - subtracts the -7 from the implicit 0 underneath making it 7. This time, the IP does turn right to the `, which is unary negation, so we get 7 again. The IP hits a dead end a turns around. The - does the same thing as before, so we get 7 once more. As the top of the stack is now positive, the IP turns right. There's another - which gives -7 again.  Then ~ is bitwise NOT, which gives 6 and ! prints it. That's just the right moment to do so, because now the stack is empty again such that the IP won't turn left onto the { but instead continues straight ahead into the @ which terminates the program.

Hexagony prints 7

Try it online.

The unfolded code looks like this:

     # I 5 a e
    e N T H { \
   ? + + 3 ; n @
  " 8 " e a 9 1 5
 } 7 ' - - ~ ! @ <
  " 3 1 " L S O e
   . e a w w . .
    . . . . . .
     . . . . .

Normally, that would be a terrifying Hexagony program, but the characters actually in use are not too many. In fact they are pretty much the same as those used by Labyrinth and I think the way I differentiate between 5 and 6 is quite nice. :)

The top row can basically be ignored. # would normally switch to a different IP, but the current memory edge is 0, so it doesn't. The letters just set a fixed memory value, but we're not going to use it. After the end of the first row, control flow continues in the middle row (starting from the }, going right). The } moves to another memory edge. 7 sets that edge to 7. ' moves back to where we came from. - subtracts the memory edge we've just set to 7 from an unused memory edge (0), so we get -7. The next - does the same thing again, so it's a no-op. So far, quite similar to Labyrinth (apart from the memory layout). But now ~ is not bitwise NOT but unary negation in Hexagony. So this gives 7 instead of 6. !@, like in Labyrinth prints the value and terminates the program.

Foo prints 8

Try it online.

As we all know since The Programming Language Quiz printing things is quite trivial in Foo, even if most of the code is a random jumble of characters. None of the characters affect the output except the "8" which prints 8. Well, there is the "31" later on, but Foo terminates with an error at the end of the first line. I'm not exactly sure why that happens, but it requires that 3 (or any other digit) on the top row, which isn't used anywhere else.

Brian & Chuck prints 9

Try it online.

Let's do this thing again where we remove the third line (it's never parsed) and replace all irrelevant characters (i.e. no-ops, or cells that aren't read) with spaces:

         { ?         + +         9
  }   --   <        .

Just as a reminder, each line is a Brainfuck-like whose tape is the source code of the other program. Control flow starts on the first line (called Brian).

The { moves the tape head all the way to the left (where it already is), and ? hands control flow over to Chuck (the second line). There, } moves the tape head to the right until it finds a zero cell. That doesn't happen until the end of the program, so the tape head ends up one cell after the 9. - decrements that cell, but that's irrelevant. < moves the tape head onto the 9 and . prints it. Chuck runs out of program and terminates.

Gol><> prints 10

Tested here.

# is a mirror, so the IP immediately skips to the end of the first line (and goes left). The 9 can be ignored. a pushes 10, e pushes 14, "8" pushes the character code of 8, @ rotates the top three stack elements (pulling up the 10), such that n prints the 10 and ; terminates the program.

Thanks to Sp3000 for suggesting to use @ instead of ! (which saved a byte).

evil prints 11

Thanks to Sp3000 for sending me some brute-forced command-lists to generate single-digit numbers.

Try it online.

evil ignores everything except lower case letters so the code looks like this:

aeeneaeeaww

Also, n affects some state we don't care about so let's ignore that as well. Now a increments the register (which starts at 0), and e is evil's magic "weave" operation which permutes the bits in a particular way. aeeeaeea happens to yield the value 49 which is the character code of 1. ww prints it twice.

Whitespace prints 12

Try it online.

Okay, we know Whitespace only reads spaces, tabs and linefeeds, so let write the code as seen by Whitespace with STL:

SSSSSSTTSSLTLST

That's two commands:

SSSSSSTTSSL
TLST

The first one pushes the number 12. Specifically, SS starts a number literal. The next S is the sign bit (positive). Then everything up to the L is a binary representation of the number. There's a ton of leading zeroes, which we need for Starry, but they don't affect the number. Then the TTSSs is 12 in binary. Fun fact: if I added a 16th language, I could save a byte here, because Starry could use the four S in the binary represtation of 16. I doubt I will though...

The TLST just prints the top of the stack as a number. (TL marks the command as an I/O command, and ST is printing numbers.)

Fission prints 13

Try it online.

Fission only sees this part of the code:

           <"31"L

L starts control flow with a left-going atom. " toggles print mode, so that 31 just prints 13. Then the atom is captured in the wedge of the <, which terminates the program.

><> prints 14

Tested here.

Distinguishing between ><> and Gol><> isn't as easy as I thought, because Gol><> almost always does the same thing as ><> for commands that exist in both, and commands that only exist in Gol><> cause ><> to crash. However, @ rotates the other way round in ><>, such that it pushes down the 7 instead of pulling up the 10, and then the 14 gets printed instead of the 10.

GolfScript prints 15

Try it online.

This one is simplest: # comments out the first line. Then 15 pushes itself and } is a "super comment", which ignores the entire rest of the program. So the 15 is printed at the end of the program.


R, 99 characters

I know it is sort of cheating, but R is all about its packages and lubridate is so convenient for this kind of tasks!

f=function(x){library(lubridate);cat(show(as.period(interval(mdy("3/15/2012"),mdy(x)))),"until",x)}

Usage:

f("10/31/2017")
[1] 5 years, 7 months and 16 days
5 years, 7 months and 16 days  until 10/31/2017


Tile the chessboard with four-colored triominoes

JavaScript (ES6),  184 ... 171  163 bytes

Takes input as (x)(y), with \$0\leq x\leq7\$ and \$0\leq y\leq7\$. Outputs as a string with 3 colors (marked as \$0\$, \$1\$ and \$2\$).

h=>v=>(a=[...'3232132031021010'],a[5+(v&4|h>3)]^=3,a[v/2<<2|h/2]=v%2*2+h%2,g=x=>y&8?'':(x<8?x-h|y-v?a[y/2<<2|x/2]^y%2*2+x%2?(x^y)&2:1:' ':`
`)+g(-~x%9||!++y))(y=0)

Try it online!

Method

We work on a matrix of \$4\times4\$ triominoes:

$$\begin{pmatrix}
t_0&t_1&t_2&t_3\\
t_4&t_5&t_6&t_7\\
t_8&t_9&t_{10}&t_{11}\\
t_{12}&t_{13}&t_{14}&t_{15}
\end{pmatrix}$$

Each triomino is one of:

The initial configuration of the matrix is as follows:

$$\begin{pmatrix}
3&2&3&2\\
1&3&2&0\\
3&1&0&2\\
1&0&1&0
\end{pmatrix}$$

We alternate the first 2 colors just like we would on any chessboard, which gives:

The next steps are:

According to the quadrant in which the hole is located, we rotate one of the 4 center triominoes (\$t_5\$, \$t_6\$, \$t_9\$ or \$t_{10}\$) by 180°.
We rotate the triomino on which the hole is located (it may be the same triomino as in step #1), so that it does not cover the hole.
We fill the holes with the 3rd color (except the 'real' hole).

For instance, assuming that the hole is located at \$(3,0)\$, this gives:

And it that case, the final matrix is:

$$\begin{pmatrix}
3&\color{red}1&3&2\\
1&\color{red}0&2&0\\
3&1&0&2\\
1&0&1&0
\end{pmatrix}$$

Commented

h => v => (                       // (h, v) = hole coordinates
  a = [...'3232132031021010'],    // a[] = flat representation of the 4x4 matrix
  a[5 + (v & 4 | h > 3)] ^= 3,    // first rotation, achieved by XOR'ing with 3
  a[v / 2 << 2 | h / 2] =         // second rotation according to the
    v % 2 * 2 + h % 2,            // position of the hole within the triomino's square
  g = x =>                        // g is a recursive function that converts the 4x4
                                  // matrix into a 8x8 ASCII art
    y & 8 ?                       // if y = 8:
      ''                          //   stop recursion and return an empty string
    :                             // else:
      ( x < 8 ?                   //   if this is not the end of the row:
          x - h | y - v ?         //     if this is not the position of the hole:
            a[y / 2 << 2 | x / 2] //       if this part of the triomino located at this
            ^ y % 2 * 2 + x % 2 ? //       position is 'solid':
              (x ^ y) & 2         //         use either color #0 or color #2
            :                     //       else:
              1                   //         use color #1
          :                       //     else:
            ' '                   //       the hole is represented with a space
        :                         //   else:
          `\n`                    //     append a linefeed
      ) + g(-~x % 9 || !++y)      //   append the result of a recursive call
)(y = 0)                          // initial call to g with x = y = 0

Graphical output

Click on the picture to set the position of the hole.

f=
h=>v=>(a=[...'3232132031021010'],a[5+(v&4|h>3)]^=3,a[v/2<<2|h/2]=v%2*2+h%2,g=x=>y&8?'':(x<8?x-h|y-v?a[y/2<<2|x/2]^y%2*2+x%2?(x^y)&2:1:' ':`
`)+g(-~x%9||!++y))(y=0)

;(u = (x, y) => { for(out = '', a = f(x)(y).split('\n'), y = 0; y < 8; y++) for(x = 0; x < 8; x++) out += `<div class="b b${a[y][x] == ' ' ? 'H' : a[y][x]}"></div>`; o.innerHTML = out; })(0, 0); o.onclick = e => u(e.clientX >> 4, e.clientY >> 4)
body { margin: 0; padding: 0; }
#o { width: 128px; height: 128px; }
.b { float: left; width: 14px; height: 14px; border: solid 1px; }
.b0 { background-color: #44f; border-color: #66f #22d #22d #66f; }
.b1 { background-color: #652e65; border-color: #874f87 #430c43 #430c43 #874f87; }
.b2 { background-color: #ffc90e; border-color: #ffeb2f #dda70c #dda70c #ffeb2f; }
.bH { border-color: #000; }


Are there N consecutive occurrences of a number in a row/column in a matrix?

Husk, 9 bytes

≤▲mLṁgS+T

Takes a 2D array and a number, returns 0 for falsy instances and a positive number for truthy instances.
Try it online!

Explanation

Husk is a functional language, so the program is just a composition of several functions.

≤▲mLṁgS+T
        T  Transpose the array
      S+   and concatenate with original.
           We get a list of the rows and columns of the input array.
    ṁ      Map and concatenate
     g     grouping of equal consecutive elements.
           This gives all consecutive runs on rows and columns.
  mL       Map length over the runs,
 ▲         take the maximum of the results
≤          and see if it's at least the second input.


05AB1E, 10 9 7 bytes
-1 byte inspired by Jonathan Allans Jelly answer.
-2 bytes thanks to Kevin Cruijssen!
Input is a list of characters.
aγO0K.M

Try it online!
Commented:
aγO0K.M     implicit input       ["a","b"," ","c","d"," ","e","."]

a           is_alpha (vectorizes)[1, 1, 0, 0, 1, 1, 0, 1, 0]
 γ          split into chunks of equal elements
              [[1, 1], [0, 0], [1, 1], [0], [1], [0]]
  O         sum the lists        [2, 0, 2, 0, 1, 0]
   0K       remove 0's
     .M     mode                 2

            implicit output      2

a is implemented as Regex.match?(~r/^[a-zA-Z]+$/, to_string(x)), which should be equivalent to the challenge specification.
I feel like there has to be a shorter way to remove 0s from a list than ʒĀ}.


Wolfram Language (Mathematica), 30 bytes
(h=2/--√5;h^#-(1-h)^#)√.2&

Try it online!
Uses \$\frac{\sqrt 5+1}{2}=\frac{2}{\sqrt 5-1}\$. Mathematica's pre-increment/decrement operators still return the desired value when used on (non-variable) non-atoms.
The built-in Fibonacci is a continuous real function, the real part of the Binet formula: \$F_n=\frac{\phi^n-\cos(\pi n)\phi^{-n}}{\sqrt 5}\$.


Japt, v2.0a0, 7 bytes
r\v_²íf

Try it

Explanation
r           :Replace
 \v         :/[AEIOU]/gi
   _        :Pass each match through a function
    ²       :  Duplicate
     íf     :  Interleave "f"

Note: This solution was posted before the "bonus" of handling double vowels was made a requirement and before the (apparent) requirement that when repeating an uppercase vowel the second occurrence should be lowercased. I don't much feel like wasting time on a challenge whose spec is constantly changing and invalidating the solutions that have already been posted, nor do I feel I should be expected to sacrifice 90 rep by deleting a solution that was valid at the time of posting.


JavaScript (ES6) 77 66 64 60 bytes
(Saved some bytes thanks to @Johan Karlsson and @Arnauld).
s=>[...s].map(l=>s=~~s+2+'behknquxcfilorvysz'.search(l)/8)|s

f=

s=>[...s].map(l=>s=~~s+2+'behknquxcfilorvysz'.search(l)/8)|s

console.log(f(''));                 //0
console.log(f('water'));            //8
console.log(f('soap'));             //9
console.log(f('candela'));          //13
console.log(f('code golf'));        //20
console.log(f('king of the hill')); //33


dc, 4 bytes

Needs as input the binary blocks with no separator. This is allowed by the OP.

2i?P

Try it online!

Explanation: using the "abc" example as test case

2i? sets 2 as input radix, then reads the line (output radix is 10 by default). This converts the binary input to decimal: 011000010110001001100011 -> 6382179.
P is a special printing mode that assumes a base 256 number, using its "digits" as ASCII codes: 6382179 = (97 * 256 2) + (98 * 256 1) + (99 * 256 0) -> abc


Python 2, 53 52 bytes
Based on xnor's answer.
-1 byte thanks to dingledooper!

f=lambda l,t=0:-min([a<t or~f(l,b)for a,b in l]+[0])

Try it online!
This is a recursive function which takes 2 arguments:

l: a list of all offered meetings
t: the time our last meeting ended (initially 0)

The list comprehension iterates over all offered meetings (a, b).
If the meeting starts before our last meeting ended (a<t), a<t or ... evaluates to True, which is basically the same as 1 in Python.
Otherwise f(l,b) is called to see how much more meetings we can fit in if we take the current meeting. The bitwise inverted value of this gets into the list.
If a<t was false for any meeting (a, b) in the comprehension, min returns the smallest of all possible ~f(l,b) values. Then -min(...) returns -~f(l,b)==1+f(l,b) for some meeting.
Otherwise -min(...) is equal to 0.

47 bytes if we can assume that the input is not empty:

f=lambda l,t=0:1-min(a<t or-f(l,b)for a,b in l)

Try it online!


All you have to do is print the number 1! ...Twice

Java, 62 bytes

interface M{static void main(String[]a){System.out.print(1);}}

Try it online.
05AB1E, 62 bytes
\agXeYTVXι@nfgTg\Vιib\Wι`T\a₂Fge\aZNPT₃nFlfgX`!bhg!ce\ag₂$₃.pp

Uses the 05AB1E encoding, with the codepoints all decreased by 13:

interface M{static void main(String[]a){System.out.print(1);}} has the codepoints [105,110,116,101,114,102,97,99,101,32,77,123,115,116,97,116,105,99,32,118,111,105,100,32,109,97,105,110,40,83,116,114,105,110,103,91,93,97,41,123,83,121,115,116,101,109,46,111,117,116,46,112,114,105,110,116,40,49,41,59,125,125]
\agXeYTVXι@nfgTg\Vιib\Wι`T\a₂Fge\aZNPT₃nFlfgX`!bhg!ce\ag₂$₃.pp has the codepoints [92,97,103,88,101,89,84,86,88,19,64,110,102,103,84,103,92,86,19,105,98,92,87,19,96,84,92,97,27,70,103,101,92,97,90,78,80,84,28,110,70,108,102,103,88,96,33,98,104,103,33,99,101,92,97,103,27,36,28,46,112,112].

Try it online.
Explanation:
Java:

interface M{                   // Full program:
  static void main(String[]a){ //  Mandatory main-method:
    System.out.print(          //   Print without trailing newline:
      1);}}                    //    Print 1

05AB1E:

\                  # Discard the top of the stack (no-op, since it's already empty)
                   #  STACK: []
 a                 # Check if it only consists of letters (resulting in falsey/0
                   # for an empty string "", which is used implicitly without input)
                   #  STACK: [0]
  g                # Push and push its length, which is 1
                   #  STACK: [1]
   X               # Push variable `X`, which is 1 by default
                   #  STACK: [1,1]
    e              # Push the number of permutations n!/(n-r)! with both 1s, which is 1
                   #  STACK: [1]
     Y             # Push variable `Y`, which is 2 by default
                   #  STACK: [1,2]
      T            # Push builtin 10
                   #  STACK: [1,2,10]
       V           # Pop and store it in variable `Y`
                   #  STACK: [1,2]
        X          # Push variable `X` again, which is 1 by default
                   #  STACK: [1,2,1]
         ι         # Uninterleave using the 2 and 1, resulting in ["2"]
                   #  STACK: [1,["2"]]
          @        # Check whether 1 is >= ["2"], resulting in [0]
                   #  STACK: [[0]]
           n       # Square it
                   #  STACK: [[0]]
            f      # Get a list of all prime factors (none for 0), which results in []
                   #  STACK: [[[]]]
             g     # Pop and push its length
                   #  STACK: [1]
              T    # Push builtin 10
                   #  STACK: [1,10]
               g   # Pop and push its length
                   #  STACK: [1,2]
                \  # Discard it
                   #  STACK: [1]
                 V # Pop and store it in variable `Y`
                   #  STACK: []

From here on out I can't really explain it anymore, since it does things I wasn't expecting:
ι                  # Uninterleave (would take either one or two arguments, but since the
                   # stack is empty, it somehow remembered the 1 that was previously on
                   # the stack and results in ["1"] -
                   # A program `ι` without input would result in an error instead..)
                   #  STACK: [["1"]]
 i                 # If-statement, which will be entered if the top is 1;
                   # since it's ["1"] instead of 1, it won't enter
                   #  STACK: []
  b\Wι`T\a₂Fge\aZNPT₃nFlfgX`!bhg!ce\ag₂$₃.pp
                   #  No-ops within the if-statement
                   # It again somehow remembers the previous ["1"] that was on the stack,
                   # which is output implicitly as result