05AB1E, 15 14 13 bytes
Saved a byte thanks to Emigna! Code:
µNœvyJÂïÊP}_½

Explanation:
µ               # c = 0, when c is equal to the input, print N.
 N              # Push N, the iteration variable.
  œ             # Push all permutations of N.
   vyJ    }     # For each permutation...
      Â         #   Bifurcate, which is short for duplicate and reverse.
       ï        #   Convert the seconds one to int, removing leading zeros.
        Q       #   Check if they are not equal.
         P      #   Product of the stack.
           _    # Logical not.
            ½   # Pop a value, if 1 then increase c by 1.

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


JavaScript (ES6), 14 12 bytes

-2 bytes thanks to @Shaggy

f=_=>"f=_"+f

Testing snippet

s=`f=_=>"f=_"+f`;

for(i=10;i--;s=eval(s)())
  o.innerText+=s+"\n";


05AB1E, 9 7 bytes
žh4ã€‚»

Try it online.
Explanation:

žh       # Push builtin string "0123456789"
  4ã     # Get the cartesian product of 4: ["0000","0001",...,"9998","9999"]
    €    # Map each string to:
     ‚   #  Pair it with the (implicit) input-string
      »  # Join each inner list by spaces, and then all strings by newlines
         # (after which the result is output implicitly)


Python, 36 bytes
lambda s:" ".join(s.replace(" ",""))


CJam, 9 8 bytes

A: 1
B: 0
C:  r,(#0q

Try it online in the CJam interpreter.

How it works

(ABcode) e# Push the integer 10 ** len(Bcode).
<SP>     e# Noop. Separates (AB) and C for input reading.
r        e# Read the first whitespace-separated token from STDIN (ABinput).
,(       e# Push the string length minus 1: len(Binput)
#        e# Power operator: 10 ** len(Bcode) len(Binput) # ->
         e#   (10 ** len(Bcode)) ** len(Binput) = 10 ** (len(Bcode) * len(Binput))
0        e# Push an additional 0 to complete len(Bcode) * len(Binput) + 1 zeroes.
q        e# Read the remaining input (C).


Python 3 + numpy, 310 291 bytes

 -19 bytes thanks to ovs!

v=lambda c,x,y:sin(arctan2(*c[::-1])-x)>sin(y-x)
def f(a,r,w,x,b,s,y,z):
 d=linalg.norm(b-a)
 if abs(r-s)<d<r+s:e=(r*r-s*s+d*d)/2/d;g=a+e*(b-a)/d;t=(sqrt(r*r-e*e)*(b-a)/d*[1,-1])[::-1];return int(v(g+t-a,w,x)and v(g+t-b,y,z))+int(v(g-t-a,w,x)and v(g-t-b,y,z))-(t==0).all()
from numpy import*

Try it online!

This is a horrible answer.

Takes angles in radians.


Java
The method of generation is based off of the game Sugar, Sugar. In that game, sugar particles fall, traveling randomly left and right. In my program, Dust objects fall until they hit the ground. I collect data based on where they land; this is the bell curve:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.Stack;
import javax.imageio.ImageIO;

/**
 *
 * @author Quincunx
 */
public class ApproxBellCurve {

    public static final int NUM_DUST = 10_000_000;
    public static final int NUM_THREADS = Runtime.getRuntime().availableProcessors() - 1;
    public static final int LOOP_LIMIT = NUM_DUST / (NUM_THREADS + 1);

    public static void main(String[] args) {
        BufferedImage output = new BufferedImage(2049, 2049, BufferedImage.TYPE_INT_RGB);

        Stack<Thread> threads = new Stack();

        for (int i = 0; i < NUM_THREADS; i++) {
            threads.push(new Thread(new Duster()));
            threads.peek().start();
        }

        Dust d;
        Random r = new Random();
        for (int i = 0; i < LOOP_LIMIT + NUM_DUST - (LOOP_LIMIT * (NUM_THREADS + 1)); i++) {
            d = new Dust(r);
            while (!d.end) {
                d.step();
            }
            if ((i & 1024) == 0) {
                r = new Random();
            }
        }
        while (threads.size() > 0) {
            try {
                threads.pop().join();
            } catch (InterruptedException ex) {

            }
        }
        int maxy = 0;
        for (int x = 0; x < Dust.data.length; x++) {
            maxy = Dust.data[x] > maxy ? Dust.data[x] : maxy;
        }

        for (int x = 0; x < Dust.data.length; x++) {
            for (int y = 0; y < output.getHeight(); y++) {
                output.setRGB(x, y, (y >= output.getHeight() - (Dust.data[x] * output.getHeight() / maxy)) ? 6591981 : 16777215);
            }
        }
        try {
            ImageIO.write(output, "png", new File("Filepath"));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private static class Duster implements Runnable {

        @Override
        public void run() {
            Dust d;
            Random r = new Random();
            for (int i = 0; i < LOOP_LIMIT; i++) {
                d = new Dust(r);
                while (!d.end) {
                    d.step();
                }
                if ((i & 1024) == 0) {
                    r = new Random();
                }
            }
        }

    }

    private static class Dust {

        public static int[] data = new int[2049];

        static {
            for (int i = 0; i < data.length; i++) {
                data[i] = 0;
            }
        }

        private int[] location;
        private Random r;
        public boolean end;

        public Dust(Random rand) {
            location = new int[]{1024, 0};
            r = rand;
            end = false;
        }

        public void step() {
            if (end) {
                return;
            }
            if (location[1] >= 1024) {
                end = true;
                synchronized (data) {
                    data[location[0]] += 1;
                }
                return;
            }
            location[1] += 1;
            location[0] += r.nextInt(21) - 10;
        }
    }
}

Sample output (took 1 minute to create):

Because of the nature of the random number generation, it is possible to get an ArrayIndexOutOfBoundsException.
I used multithreading to speed up the process. The program determines the number of processors available and creates that many threads to run the simulations.
To obtain a finer image, NUM_DUST can be increased, but that would also lead to an increased risk of an ArrayIndexOutOfBoundsException.
Each thread creates a new Random after every 1024 Dust objects are simulated. When that code was removed, the image was more coarse.
rand.nextInt(21) - 10 is to widen the distribution. A change to rand.nextInt(3) - 1 would remove all chance of an ArrayIndexOutOfBoundsException.


Pyth, 14 bytes

V^SQEIqsNQj\,N

Try it online: Demonstration or Test Suite

Explanation:

V^SQEIqsNQj\,N   implicit: Q = first input number
  SQ             create the list [1, 2, ..., Q]
    E            read another number
 ^               cartesian product of the list
                 this creates all tuples of length E using the numbers in SQ
V                for each N in ^:
     IqsNQ          if sum(N) == Q:
          j\,N         join N by "," and print


Create Balanced BST from Sorted List of Integers

Ruby, 143

s=ARGV.size;r,q=[],[[0,s]];s.times{b,e=q.shift;k=Math::log2(e-b).to_i-1;m=(e-b+2)>(3<<k)?b+(2<<k)-1:e-(1<<k);r<<ARGV[m];q<<[b,m]<<[m+1,e]};p r

It is a (loosely) compressed version of the following code which basically does a BFS on the tree.

def l(n)
    k = Math::log2(n).to_i-1
    if n+2 > (3<<k) then
        (2<<k)-1
    else
        n-(1<<k)
    end
end

def bfs(tab)
  result = []
  queue = [[0,tab.size]]
  until queue.empty? do
    b,e = queue.shift
    m = b+l(e-b)
    result << tab[m]
    queue << [b,m] if b < m
    queue << [m+1,e] if m+1 < e
  end
  result
end

p bfs(ARGV)

Besides, because it's BFS, not DFS, a requirement of non-recursive solution is not significant, and it puts some languages at a disadvantage.

Edit: Fixed solution, thanks to @PeterTaylor for his comment!


Jelly, 13 bytes

ØQØDṭ,ṙ€¥⁸F€y

Try it online!

How it works

ØQØDṭ,ṙ€¥⁸F€y  Main link. Left argument: n (integer). Right argument: s (string)

ØQ             Qwerty; set the return value to
               ["QWERTYUIOP", "ASDFGHJKL", "ZXCVBNM"].
  ØD           Digits; yield "0123456789".
    ṭ          Tack, yielding ["QWERTYUIOP", "ASDFGHJKL", "ZXCVBNM", "0123456789"].
        ¥⁸     Call the two links to the left as a dyadic chain, with right
               argument n.
      ṙ€       Rotate each string in the array n units to the left.
     ,         Yield the pair of the unmodified and the rotated string array.
          F€   Flatten each, mapping, e.g., ["QWERTYUIOP", ..., "0123456789"] to
               "QWERTYUIOPASDFGHJKLZXCVBNM0123456789".
            y  Translate s according to the mapping we've built.


C (gcc),  157 153 143 139  135 bytes
Saved several bytes thanks to @AlexeyBurdin
Saved  4  8 more bytes thanks to @ceilingcat
Outputs with ANSI colors.

long p,a,s,c,L;f(n,d){for(a=0;c=a++-n;puts(""))for(;p=c<a;printf(c<0?" ":"\e[3%dm@@",L),s=++c<1?1:s*a/c-s)for(L=0;p*=d,L<7&s%p<1;L++);}

Try it online! (no colors on TIO)
Example output for \$f(40,2)\$

Formula
At row \$r\$ and column \$c-1\$, we have:
$$P_{r,c-1}={r\choose c-1}=\frac{r!}{(c-1)!(r-c+1)!}$$
On the same row and the next column \$c\$, we have:
$$\begin{align}P_{r,c}={r\choose c}&=\frac{r!}{c!(r-c)!}\\
&=\frac{r-c+1}{c}\times\frac{r!}{(c-1)!(r-c+1)!}\\
&=\frac{r-c+1}{c}\times P_{r,c-1}\\
&=\frac{r+1}{c}P_{r,c-1}-P_{r,c-1}\end{align}$$
which is translated as s = s * a / c - s in the C code (with \$a=r+1\$).
Commented
long p, a, s, c, L;               // declare a few 64-bit integers
f(n, d) {                         // n = number of rows, d = colorization parameter
  for(a = 0; a++ < n; puts(""))   // for a = 1 to n, with a linefeed added after each
    for(                          // iteration:
      c = a + ~n;                 //   for c = a - n - 1 to a - 1:
      p = c < a;                  //
      printf(                     //     update the output after each iteration:
        c < 0 ?                   //       if c is negative:
          " "                     //         just append a space
        :                         //       else:
          "\e[3%dm@@",            //         append the ANSI color code, followed by '@@'
        L                         //       set the 2nd digit of the color code
      ),                          //
      s = ++c < 1 ? 1             //     increment c; set s to 1 while c is less than 1
                  : s * a / c - s //     then, update s to s * a / c - s
    )                             //
      for(                        //       compute the color L:
        L = 0;                    //         start with L = 0
        p *= d,                   //         multiply p by d
        L < 7 & s % p < 1;        //         stop if L = 7 or p does not divide s
        L++                       //         increment L
      );                          //
}                                 //


Print the "even" permutations of symmetric group Sn in cyclic notation

Mathematica, 84 49 31 bytes

GroupElements@*AlternatingGroup

Composition of two functions. Outputs in the form {Cycles[{}], Cycles[{{a, b}}], Cycles[{{c, d}, {e, f}}], ...} representing (), (a b), (c d)(e f), ....


Haskell, 227 203 bytes

17 bytes saved thanks to Οurous

(%)=div
u x|odd x=x%2+1|1>0=x%2
[0,b]!l=[b]!l
[b,0]!l=[b]!l
t!l|elem t l=[dropWhile(/=t)l]
t@[a,b]!l|q<-l++[t]=[a%2,u a+b]!q++[u b+a,b%2]!q
f x|q<-[x%2,u x]![[x]]=[a|(a,b)<-zip q[0..],notElem a$take b q]

Try it online!


JavaScript (ES10),  81  80 bytes
Saved 1 byte thanks to @Shaggy
Expects -1 for a non-existing child node. Returns a string where each line contains all the nodes at this depth.

a=>(g=r=>a+a&&(r=r.map(x=>+x||a.shift()||-1))+`
`+g(r.flatMap(x=>[x=-!~x,x])))``

Try it online!


Ruby, 83 75 68 66 63 bytes

f=->m{m[b=c=i=0].map{(c=i;b-=1)while(r=m[b-2])&&r[i]>0;i+=1};c}

Defines a function f which takes the 2D array form as input.

   I'm starting at the bottom left, keeping track of maximum stick length (actually, minus that) and the corresponding column. In each column, if there are still 1s above the previous maximum stick length, I walk up the stick to the end and remember the new maximum length and column. That means that I'm iterating once along the columns and at most once along the rows (specifically I'm iterating as far as the maximum stick length), which is precisely O(m+n).


Ruby 1.9

Number of characters: 93

Assuming that all inputs are valid games, and that games always end in checkmates or stalemates (as per Noldorin's response in the comments), then we only need to check who played the last move and whether it was a checkmate or not.

Golfed code:

*a,b,c=$<.read.gsub(/{[^}]*}|;.*$/,"").split;puts c=~/#/?(b=~/[^.]\.$/?"1-0":"0-1"):"1/2-1/2"

Ungolfed code:

# read entire input
game = $<.read
# strip comments
game = game.gsub(/{[^}]*}|;.*$/,"")
# split the input and get the last two words
*rest, second, last = game.split
# check if the last move has a checkmate symbol
if last =~ /#/
# if so, then determine whether the last move is white or black based
# on the number of periods in the second-to-last word
  puts second =~ /[^.]\.$/ ? "1-0" : "0-1"
else
# if not, then it's a draw
  puts "1/2-1/2"
end


bfcat - encode a file as a brainf*** program

Brainfuck, 55 51 bytes

,[>+++[>+++++++<-]>[<++>>+++<-]<+<[>.<-]>+++.>>-.,]

Try it online!

Example output for hi (without the linefeeds):

+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++.>++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.>

Explanation

This moves across the tape while writing the program. The surrounding ,[...,] is a standard input loop. For each character, we use four cells:

[... x a b c ...]

where x is the cell we write the input to.

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

This part uses cell a to write a 21 into cell b via a standard multiplication of 3 and 7.

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

Now we use that 21 to write 42 into a and 63 into c by multiplying by 2 and 3 respectively. Then <+< moves back to cell x while turning the 42 into a 43 (the code point of +). Recap:

[... x 43 21 63 ...]

Now the main output loop:

[>.<-]

That is, while decrementing x we print one + each time.

>+++.

After we're done we reuse the + cell, by adding 3 to give ..

>>-.

Finally, we move to the 63, decrement it to 62 (>) and output that as well. The next iteration will use this cell as x.


C# Interactive Window
Open the C# Interactive Window (View > Other Windows > C# Interactive in Visual Studio 2015). I suppose not all IDEs will have this.
This approach executes C# in the Interactive Window in order to create a C# exe that prints the desired string without the author ever writing main. As a bonus, the exe's IL also does not contain main.
Run the following code in the Interactive Window
using System.Reflection;
using System.Reflection.Emit;
var appMeow = (dynamic)System.Type.GetType("System.AppDom" + "ain").GetProperty("CurrentDom" + "ain", BindingFlags.GetProperty | BindingFlags.Static | BindingFlags.Public).GetValue(null);
var asmName = new AssemblyName("MEOW");
var asmBuilder = appMeow.DefineDynamicAssembly(asmName, AssemblyBuilderAccess.RunAndSave);
var module = asmBuilder.DefineDynamicModule("MEOW", "MEOW.exe");
var typeBuilder = module.DefineType("Meow", TypeAttributes.Public);
var entryPoint = typeBuilder.DefineMethod("EntryPoint", MethodAttributes.Static | MethodAttributes.Public);
var il = entryPoint.GetILGenerator();
il.Emit(OpCodes.Ldstr, "Meow() is the meow method of C# programs!");
il.Emit(OpCodes.Ldstr, "eow");
il.Emit(OpCodes.Ldstr, "ain");
il.EmitCall(OpCodes.Call, typeof(string).GetMethod("Replace", new[] { typeof(string), typeof(string) }), null);
il.EmitCall(OpCodes.Call, typeof(Console).GetMethod("Write", new[] { typeof(string) }), null);
il.Emit(OpCodes.Ret);
var type = typeBuilder.CreateType();
asmBuilder.SetEntryPoint(type.GetMethods()[0]);
asmBuilder.Save("MEOW.exe");

Use Environmnent.CurrentDirectory to see where the exe was created. Run it to observe the desired output.

Resulting IL:


K - 29 Chars

Input is a filename passed as an argument, 29 chars not including filename.

`0:{5:x,-1+#(+/10_vs)\x}'.:'0:"file"

35 -> 31: Remove outside function.
31 -> 29: Remove parens.


Python 2, 59 bytes
print "  Hello, world!"[ 2::]
#rint "T w i s t e r !"[ ::2]

Twisted:
print "T weils,twerrd!"[ ::2]
#rint "  H l o   o l !"[ 2::]

Basically, puts the Twister! data in the odd indices of the string and then changes from removing the first two (padding) characters to removing every other character instead.


Use 16 colors while writing Hey! 4 times

Bash, 62

h=y!He
for i in {3,9}{0..7};do printf \\e[${i}m${h:i%4:1};done

Must be run from an actual script file.  If you want to try it from the command line, you'll need to escape the !, i.e. h=y\!He
Online.


Your Base to 1-2-3-Tribonacci to Binary back to Your Base

Javascript 117 111 bytes

Thanks to @theonlygusti for helping golf off 5 bytes

x=>{r=0;a=[1,2,3];i=1;while(a[++i]<x)a[i+1]=a[i]+a[i-1]+a[i-2];for(;x;i--)if(x>=a[i]){r+=1<<i;x-=a[i]}return r}

How It Works

First, the function generates all tribonacci numbers until it finds one greater than the input

a=[1,2,3];i=1;for(;a[++i]<x;)a[i+1]=a[i]+a[i-1]+a[i-2];

Next, it reverse searches the list of numbers. If a number is less than the input, it adds 2^(index of that number) to the return value and reduces the input by that number.

for(;x;i--)if(x>=a[i]){r+=1<<i;x-=a[i]}

Finally it returns the result.

Try it Online


Volts, Amps, Watts and Ohms: given two, calculate the other two

Ruby 171 bytes
Input as function argument. Output to stdout with trailing space (can be revised if necessary.)
->s{a,b,c,d=s.split.map{|z|[z[-1],z.to_f]}.sort.flatten
%w{EA9.EAAVAA.WVA GS;.A?#WWV.RRR}.map{|w|m=w[n=(a+c+?!).sum%10].ord;print (b**(m%9-4)*d**(m/9-5))**0.5,w[n+7],' '}}

Explanation
All formulas can be expressed in the form b**x*d**y where b & d are the two input values and x & y are powers. For golfing reasons the expression (b**x*d**y)**0.5 was finally preferred as it means x and y become integers in the range -4 to 4.
The following table shows the required expressions (inputs are assumed sorted alphabetically) and the encoded values for the powers. Where x and y are the doubled powers, they are encoded as (x+4)+(y+4)*9+9 or equivalently (x+4)+(y+5)*9. This puts all encodings in the printable ASCII range. Power operators are omitted from the formulas for brevity.
n is a kind of checksum made from the input unit symbols; it can take the values 0,1,2,4,5,6 (3 is not used.)
n     formula 1 formula 2      formula 1                formula 2
value                      powers x+4 y+4 encoding   powers x+4 y+4 encoding

0      A*R=V    A2*R=W       1 1    6 6   69 E        2 1     8 6   71 G
1    R-1*V=A  R-1*V2=W      -1 1    2 6   65 A       -1 2     2 8   83 S
2 R-.5*W.5=A R.5*W.5=V     -.5 .5   3 5   57 9       .5 .5    5 5   59 ;
3          .         .                       .                         .
4      A*V=W   A-1*V=R       1 1    6 6   69 E       -1 1     2 6   65 A
5    A-1*W=V   A-2*W=R      -1 1    2 6   65 A       -2 1     0 6   63 ?
6    V-1*W=A  V2*W-1=R      -1 1    2 6   65 A        2 -1    8 2   35 #

Ungolfed in test program
f=->s{
  a,b,c,d=s.split.map{|z|[z[-1],z.to_f]}.        #split the input into an array [[symbol1,value1],[symbol2,value2]]
  sort.flatten                                   #sort alphabetically by symbol and flatten to assign the 4 objects to different variables
  n=(a+c+?!).sum%10                              #sum the ascii codes of the symbols (plus that of ! for good value distribution) and take mod 10. gives a number 0..6 (3 is not used)
  %w{EA9.EAAVAA.WVA GS;.A?#WWV.RRR}.             #for each of the outputs, there is a 14 character string. 1st 7 characters encode powers, 2nd 7 characters are output symbol
  map{|w|                                        #iterate through the 2 outputs
    m=w[n].ord                                   #select one character according to value of n and convert to a number encoding the powers to raise the two inputs to
    print (b**(m%9-4)*d**(m/9-5))**0.5,w[n+7],' '#decode the powers, evaluate the expression and output, append the unit symbol and a space
  }
}

f["6W 3A"]
puts
f["12V 120R"]
puts
f["10A 10V"]
puts
f["8R 1800W"]
puts
f["6W 2V"]
puts
f["2A 3R"]
puts

Output
2.0V 0.6666666666666666R
0.1A 1.2W
100.0W 1.0R
15.0A 120.0V
3.0A 0.6666666666666666R
6.0V 12.0W


"Hello, World!" (Every other character, Part 2)

x86 machine code, 378 bytes

PROG.COM Download and run it in MS-DOS emulator, DOSBox for example.

B3 B4 B3 02 90 B3 B3 B4 02 B3 B4 B3 02 90 B3 B2
B3 48 90 B3 B3 B2 48 B3 B2 B3 48 90 B3 CD B3 21
90 B3 B3 CD 21 B3 CD B3 21 90 B3 B2 B3 65 90 B3
B3 B2 65 B3 B2 B3 65 90 B3 CD B3 21 90 B3 B3 CD
21 B3 CD B3 21 90 B3 B2 B3 6C 90 B3 B3 B2 6C B3
B2 B3 6C 90 B3 CD B3 21 90 B3 B3 CD 21 B3 CD B3
21 90 B3 CD B3 21 90 B3 B3 CD 21 B3 CD B3 21 90
B3 B2 B3 6F 90 B3 B3 B2 6F B3 B2 B3 6F 90 B3 CD
B3 21 90 B3 B3 CD 21 B3 CD B3 21 90 B3 B2 B3 2C
90 B3 B3 B2 2C B3 B2 B3 2C 90 B3 CD B3 21 90 B3
B3 CD 21 B3 CD B3 21 90 B3 B2 B3 20 90 B3 B3 B2
20 B3 B2 B3 20 90 B3 CD B3 21 90 B3 B3 CD 21 B3
CD B3 21 90 B3 B2 B3 77 90 B3 B3 B2 77 B3 B2 B3
77 90 B3 CD B3 21 90 B3 B3 CD 21 B3 CD B3 21 90
B3 B2 B3 6F 90 B3 B3 B2 6F B3 B2 B3 6F 90 B3 CD
B3 21 90 B3 B3 CD 21 B3 CD B3 21 90 B3 B2 B3 72
90 B3 B3 B2 72 B3 B2 B3 72 90 B3 CD B3 21 90 B3
B3 CD 21 B3 CD B3 21 90 B3 B2 B3 6C 90 B3 B3 B2
6C B3 B2 B3 6C 90 B3 CD B3 21 90 B3 B3 CD 21 B3
CD B3 21 90 B3 B2 B3 64 90 B3 B3 B2 64 B3 B2 B3
64 90 B3 CD B3 21 90 B3 B3 CD 21 B3 CD B3 21 90
B3 B2 B3 21 90 B3 B3 B2 21 B3 B2 B3 21 90 B3 CD
B3 21 90 B3 B3 CD 21 B3 CD B3 21 90 B3 CD B3 20
90 B3 B3 CD 20 B3 CD B3 20 90

Also you can download LEFT.COM and RIGHT.COM

How it works and how to run

See answer to part one

Magic

If you want to execute 0xAB opcode command with one parameter 0xCD, you write

Generator

Run code, get hex. Convert in to binary

cat prog.hex | xxd -r -p > PROG.COM

function byte2hex(byte){
 var ret=byte.toString(16).toUpperCase();
 return ret.length==1 ? "0"+ret : ret;
}

function str2hex(str){
 var ret = [];
 for(var i=0;i<str.length;i++){
  ret.push(byte2hex(str.charCodeAt(i)));
 }
 return ret;
}

function genCode(hexArr){
 var ret = [["B4","02"]];
 for(var i=0;i<hexArr.length;i++){
  if(hexArr[i]!=hexArr[i-1]){
   ret.push(["B2",hexArr[i]]);
  }
  ret.push(["CD","21"]);
 }
 ret.push(["CD","20"]);

 return ret;
}

function format(arr){
 var ret=[],tmp=[];
 for(var i=0;i<arr.length;i++){
  tmp.push(arr[i]);
  if(i%16==15 || i==arr.length-1){ret.push(tmp.join(" "));tmp=[];}
 }
 return ret.join("\n");
}

function magicCode(str,mode){
 var ret=[];
 var code=genCode(str2hex(str));

 for(var i=0;i<code.length;i++){
  var ab=code[i][0],cd=code[i][1],tmp;
  tmp=["B3",ab,"B3",cd,"90","B3","B3",ab,cd,"B3",ab,"B3",cd,"90"];
  for(var j=0;j<tmp.length;j++){
   if((mode&1 && j%2==0) || (mode&2 && j%2==1)){ret.push(tmp[j])}
  }

 }
 return ret;
}

const LEFT=1,RIGHT=2,ALL=3;

var str=prompt("string","Hello, world!");

var out = ["PROG.COM\n",format(magicCode(str,ALL)),"\n\nLEFT.COM\n",format(magicCode(str,LEFT)),"\n\nRIGHT.COM\n",format(magicCode(str,RIGHT))].join("\n");

document.write(out.replace(/\n/ig,"<br>"));


Python 2, 72 bytes

Takes input as a list of strings of the form "animalname T". The idea is it just uses each string as an identifier and should only print true if the string has not occurred in the list so far.

def f(l):k=map(str.lower,l);print[j not in k[:i]for i,j in enumerate(k)]

Try it here!


Python 3, 402 bytes

from itertools import*
from ast import*
from math import*
v,r=lambda x:'UnaryOp'not in dump(parse(x)),lambda s,a,b:s.replace(a,b)
def l(x,y):
    for s in product('L()e^-',repeat=x):
        f=r(r(r(''.join(s),'L','log('),')(',')*('),'^','**')
        g=r(f,'ee','e*e')
        while g!=f:f,g=g,r(g,'ee','e*e')
        try:
            if eval(g)==y and v(g):return g
        except:0
def b(v):
    i=1
    while 1:
        r=l(i,v)
        if r:return r
        i+=1

Example usage:

>>> b(1)
'log(e)'
>>> b(0)
'e-e'
>>> b(-3)
'e-log(e*e*e)-e'
>>> b(8)
'log(e*e)**log(e*e*e)'

Note that although the output format may not reflect it, the code properly counts all lengths according to the question's specifications.

This is a dumb bruteforce through all the possible lengths of strings. Then I use some replacements so that Python can evaluate it. If it's equal to what we want, I also check to exclude unary negative signs by checking the AST.

I'm not very good at golfing in Python, so here's the semi-ungolfed code if anybody wants to help!

from itertools import*
from ast import*
from math import*

def valid(ev):
    return 'UnaryOp' not in dump(parse(ev))

def to_eval(st):
    f = ''.join(st).replace('L', 'log(').replace(')(', ')*(').replace('^', '**')
    nf = f.replace('ee', 'e*e')
    while nf != f:
        f, nf = nf, nf.replace('ee', 'e*e')
    return nf

def try_length(length, val):
    for st in product('L()e^-', repeat=length):
        ev = to_eval(st)
        try:
            if eval(ev) == val and valid(ev):
                return st
        except:
            pass

def bruteforce(val):
    for i in range(11):
        res = try_length(i, val)
        if res:
            print(i, res)
            return res


Shorten an already short mathematical expression

Emotinomicon, 48 bytes / 13 characters

I do it, not because it is short, but because it is fun. Try it here. You'll have to copy+paste it into the textbox.

⏪✖➕⏩

Explanation:

  ⏪       ✖       ➕         ⏩   explanation
                                              take numeric input
    ⏪                                           open loop
                                              duplicate top of stack
                                              push pi
                ✖                               multiply top two elements on stack
                                              reverse stack
                                              pop N, push e^N
                            ➕                   add top two elements on stack
                                              take numeric input
                                              duplicate top of stack
                                              pop N, push N+1
                                            ⏩   close loop

Here is the program in its native environment, the mobile phone:


Update:

GGCD for given m and k is good defined.

This is table of GGCD tested for n up to 500000.

m/k      1       2       3       4       5       6       7       8       9      10
2        5       9      13      17      21      25      29      33      37      41
3        7     109      61     433     169     973     331    1729     547    2701
4       17      33      49      65      81      97     113     129     145    2093
5      341   52501  258751  810001       1  131371       1       1  501311 2846591
6       65     129     193     257   21507     385     449   22059     577     641
7     3683  235747       1       1      71  438299  940507   33461     757  110503
8     4369     513     769   13325    1281  149089  202609    2049  975937  617201
9   359233  232537  202927  470983  123019  708589  241117 5601589  398581   19783
10   62525  514299  183757  807517 1094187 16856405  97477    8193  377897 25919971

For m==2 or 4 it looks quite good :-)

It seems that if p_in_i is gcd for some n, where p_i is a prime, than every combination of products of p_i's with exponents <= n_i is also gcd for some n. E.g. for m=8,k=2, 3^3 and 19 are gcd of type p_in_i, also 57, 171 and 513 are gcd's.

Some theory background: If g = gcd(n) > 1 for some n, and d > 1 and d divide g (it can be d=g) than d divide gcd(n±d). It is easy to prove. That means:

If you find some g = gcd(n) > 1 for some n, than gcd(n±d) > 1. So, it is enough to jump for found prime number of steps while iterating n.
If prime p divide some gcd() than there is n <= p where p divide gcd(n). Prime p will 'appear' in gcd(n) for some n <= p.

These properties can speed up search, but still there is a question is GGCD good defined.


Haskell, 55 54 52 bytes

s n=[x|x<-[2,1.9999..],n>iterate(x**)1!!floor n]!!0

Usage:

> s 100
1.445600000000061

Thanks to @nimi for 1 byte!

Thanks to @xnor for 2!


Mathematica, 177 157 135 133 bytes
Colorize[f=BlockMap[⌊{l={0,1,0},1-l,l}#/4⌋~Total~2+#[[2,2]]~Mod~4&,#~ArrayPad~1,{3,3},1]&~FixedPoint~#&;k=Table[6,#,#];f[k-f@k]]&

Takes a number n. The output is the identity sandpile. 0 is black, 1 is light gray, 2 is magenta, and 3 is blue-gray.
Sadly, Mathematica does not have a builtin for this...
Uses the algorithm stated in Scott Corry and David Perkinson's paper.
Takes 91.7 seconds on my 5-year-old laptop to calculate the 50x50 identity sandpile. I am confident that a reasonable modern desktop computer is more than 50% faster. (I also have a way faster code at the end).
Explanation
f= ...

Define function f (the input is a sandpile matrix): a function that ...
BlockMap[ ... ]~FixedPoint~#&

... repeats the BlockMap operation until the output does not change. BlockMap operation: ...

#~ArrayPad~1

... pad the input array with one layer of 0 ...
{3,3},1

... partition it into 3x3 matrices, with offset 1 ...
⌊{l={0,1,0},1-l,l}#/4⌋~Total~2+#[[2,2]]~Mod~4&

... and for each partition, add the number of sand grains toppled onto the center cell and the center cell value mod 4.
i.e. the output of f is the stabilized version of the input.

k=Table[6,#,#]

Define k as an n by n array of 6s.
f[k-f@k]]

Compute f(k - f(k)).
Colorize[ ... ]

Apply colors to the result.
Faster version (142 bytes)
Colorize[r=RotateLeft;a=ArrayPad;f=a[b=#~a~1;b+r[g=⌊b/4⌋,s={0,1}]+g~r~-s+r[g,1-s]+r[g,s-1]-4g,-1]&~FixedPoint~#&;k=Table[6,#,#];f[k-f@k]]&

Same code, but uses built-in list rotation instead of BlockMap. Computes n=50 in 4.0 seconds on my laptop.


Python 49 45 18 22 15 14
( + 3 if string variables are considered)
print{a:0,b:1}[a]

The string should be hard coded at the two occurrences of a and one occurrence of b surrounded by quotes.
a and b should be pre-initialized to the strings.

Python shell, 9
( + 3 if string variables are considered)
{a:0,b:1}[a]

Output in shell
>>> a = 'string'
>>> b = 'string'
>>> {a:0,b:1}[a]
1
>>> a = 'string'
>>> b = 'stringgg'
>>> {a:0,b:1}[a]
0
>>> {'string':0,'string':1}['string']
1
>>> {'stringggg':0,'string':1}['stringggg']
0
>>>

Explanation
Creates a dict(hash table) with the key of first and second string.
If second string is the same, the value of first is replaced by that of second.
Finally, we print the value of first key.
EDIT: OP allowed 0/1 instead of False/True as well as using pre-initialized variables.


Python 3, 59 bytes, A162626, cracked
lambda n:n*(n+1)*(n+2)/3if 0<=n<=3else n*(n**2+5)/3#A162626

This is was supposed to be impossible, wasn't it?


Regex for Finding Non-Radioactive Elements


Whitespace, 311 150 77 68 65 46 41 38 bytes
-3 bytes thanks to Kevin Cruijssen
-27 bytes thanks to Ephphatha

&nbsp&nbsp
&nbsp&nbsp&nbsp	&nbsp	&nbsp
&nbsp
&nbsp&nbsp
&nbsp
	&nbsp
	&nbsp&nbsp

&nbsp&nbsp
&nbsp

Try it online!
A visible format
'\n  \n   \t \t \n \n  \n \t\n\t \t\t\t\n\t  \n\t\n  \n \n\n'

Explanation (s = space, t = tab, n = new line)
nssn     # label(NULL) - loop start
ssststsn # push 10 in the stack -> [10]
sns      # duplicate the top of the stack -> [10, 10]
sns      # duplicate the top of the stack -> [10, 10, 10]
tnts     # read a single char from input, pop the stack and store at that address -> [10, 10] [10:<char that was read>]
ttt      # pop the stack and put the value at that adress on stack -> [10,<char>] [10:<char>]
ntssn    # jump to label(0) - since label(0) is not defined, the interpreter jumps to the end of the program - if the top of the stack (char) is 0 -> [10] [10:<char>]
tnss     # pop the top of the stack and print as ascii -> [] [10:<char>]
nsnn     # go back to the label(NULL)


22222222... (65536 twos) = 2↑↑↑4
Before I begin, this is not the largest number expressible using 500 bytes of New Brainfuck.  It's simply where I gave up trying to wrap my head around how big the numbers were getting.  This answer only uses 93 bytes and is therefore not the largest number, but it's proof of concept that mind-bogglingly large numbers are possible.
+++[->++[->+>+<<]>>[-<<+>>]+<[->[-<<[->>>+>+<<<<]>>>>[-<<<<+>>>>]<<]>[-<+>]<<]>[-<+>]<<<]>>.

This is a modification of the exponentiation algorithm in Brainfuck.
This number is so large, it's almost impossible to describe in human terms.  It isn't sufficient to say "the number has this many digits" because it has more digits than particles in the universe.  In fact, the number of digits this number contains has more digits than the number of particles in the universe.
Let this number be x, and let f(0) = x.  Recursively define f(n) = floor[log10[f(n-1)]].  The first n which is smaller than 1 googol is over 10,000.
This answer is 93 bytes.
If we removed removed a single leading +, the result would be 65536 = 2222.  Removing another + gives us 4.  This means that if we add another +, we would get a number tower with 2↑↑↑4 twos, which would be 2↑↑↑5.  That answer would be 94 bytes.  If I were to add another 406 plus signs to this, we would get 2↑↑↑411, which is mind-bogglingly big.  Instead, if  I were to add yet another outer loop, I could probably get something close to 2↑↑↑↑380.  For the record, 2↑↑↑↑3 = 2↑↑↑4, and 2↑↑↑↑4 dwarfs 2↑↑↑4 much the same way that 2↑↑↑4 dwarfs 65536.  In fact, it may just be possible to actually get close to Graham's Number using 500 bytes of brainfuck.


Permutations such that no k+2 points fall on any polynomial of degree k

C#

using System;
using System.Diagnostics;
using BigInteger = System.Int32;

namespace Sandbox
{
    class PPCG160382
    {
        public static void Main(params string[] args)
        {
            if (args.Length != 0)
            {
                foreach (var arg in args) Console.WriteLine(CountValidPerms(int.Parse(arg)));
            }
            else
            {
                int[] smallValues = new int[] { 1, 1, 2, 4, 18, 48 };
                for (int n = 0; n < smallValues.Length; n++)
                {
                    var observed = CountValidPerms(n);
                    var expected = smallValues[n];
                    Console.WriteLine(observed == expected ? $"{n}: Ok" : $"{n}: expected {expected}, observed {observed}, error {observed - expected}");
                }
                for (int n = smallValues.Length; n < 13; n++)
                {
                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    Console.WriteLine($"{n}: {CountValidPerms(n)} in {sw.ElapsedMilliseconds}ms");
                }
            }
        }

        private static long CountValidPerms(int n)
        {
            // We work on the basis of exclusion by extrapolation.
            var unused = (1 << n) - 1;
            var excluded = new int[n];
            int[] perm = new int[n];

            // Symmetry exclusion: perm[0] < (n+1) / 2
            if (n > 1) excluded[0] = (1 << n) - (1 << ((n + 1) / 2));

            long count = 0;
            CountValidPerms(ref count, perm, 0, unused, excluded);
            return count;
        }

        private static void CountValidPerms(ref long count, int[] perm, int off, int unused, int[] excluded)
        {
            int n = perm.Length;
            if (off == n)
            {
                count += CountSymmetries(perm);
                return;
            }

            // Quick-aborts
            var completelyExcluded = excluded[off];
            for (int i = off + 1; i < n; i++)
            {
                if ((unused & ~excluded[i]) == 0) return;
                completelyExcluded &= excluded[i];
            }
            if ((unused & completelyExcluded) != 0) return;

            // Consider each unused non-excluded value as a candidate for perm[off]
            var candidates = unused & ~excluded[off];
            for (int val = 0; candidates > 0; val++, candidates >>= 1)
            {
                if ((candidates & 1) == 0) continue;

                perm[off] = val;

                var nextUnused = unused & ~(1 << val);

                var nextExcluded = (int[])excluded.Clone();
                // For each (non-trivial) subset of smaller indices, combine with off and extrapolate to off+1 ... excluded.Length-1
                if (off < n - 1 && off > 0)
                {
                    var points = new Point[off + 1];
                    var denoms = new BigInteger[off + 1];
                    points[0] = new Point { X = off, Y = perm[off] };
                    denoms[0] = 1;
                    ExtendExclusions(perm, off, 0, points, 1, denoms, nextExcluded);
                }

                // Symmetry exclusion: perm[0] < perm[-1] < n - 1 - perm[0]
                if (off == 0 && n > 1)
                {
                    nextExcluded[n - 1] |= (1 << n) - (2 << (n - 1 - val));
                    nextExcluded[n - 1] |= (2 << val) - 1;
                }

                CountValidPerms(ref count, perm, off + 1, nextUnused, nextExcluded);
            }
        }

        private static void ExtendExclusions(int[] perm, int off, int idx, Point[] points, int numPoints, BigInteger[] denoms, int[] excluded)
        {
            if (idx == off) return;

            // Subsets without
            ExtendExclusions(perm, off, idx + 1, points, numPoints, denoms, excluded);

            // Just add this to the subset
            points[numPoints] = new Point { X = idx, Y = perm[idx] };
            denoms = (BigInteger[])denoms.Clone();
            // Update invariant: denoms[s] = prod_{t != s} points[s].X - points[t].X
            denoms[numPoints] = 1;
            for (int s = 0; s < numPoints; s++)
            {
                denoms[s] *= points[s].X - points[numPoints].X;
                denoms[numPoints] *= points[numPoints].X - points[s].X;
            }
            numPoints++;

            for (int target = off + 1; target < excluded.Length; target++)
            {
                BigInteger prod = 1;
                for (int t = 0; t < numPoints; t++) prod *= target - points[t].X;

                Rational sum = new Rational(0, 1);
                for (int s = 0; s < numPoints; s++) sum += new Rational(prod / (target - points[s].X) * points[s].Y, denoms[s]);

                if (sum.Denom == 1 && sum.Num >= 0 && sum.Num < excluded.Length) excluded[target] |= 1 << (int)sum.Num;
            }

            // Subsets with
            ExtendExclusions(perm, off, idx + 1, points, numPoints, denoms, excluded);
        }

        private static int CountSymmetries(int[] perm)
        {
            if (perm.Length < 2) return 1;

            int cmp = 0;
            for (int i = 0, j = perm.Length - 1; i <= j; i++, j--)
            {
                cmp = perm.Length - 1 - perm[i] - perm[j];
                if (cmp != 0) break;
            }

            return cmp > 0 ? 4 : cmp == 0 ? 2 : 0;
        }

        public struct Point
        {
            public int X;
            public int Y;
        }

        public struct Rational
        {
            public Rational(BigInteger num, BigInteger denom)
            {
                if (denom == 0) throw new ArgumentOutOfRangeException(nameof(denom));

                if (denom < 0) { num = -num; denom = -denom; }

                var g = _Gcd(num, denom);
                Num = num / g;
                Denom = denom / g;
            }

            private static BigInteger _Gcd(BigInteger a, BigInteger b)
            {
                if (a < 0) a = -a;
                if (b < 0) b = -b;
                while (a != 0)
                {
                    var tmp = b % a;
                    b = a;
                    a = tmp;
                }
                return b;
            }

            public BigInteger Num;
            public BigInteger Denom;

            public static Rational operator +(Rational a, Rational b) => new Rational(a.Num * b.Denom + a.Denom * b.Num, a.Denom * b.Denom);
        }
    }
}

Takes values of n as command-line arguments, or if run without arguments times itself up to n=10. Compiling as "Release" in VS 2017 and running on an Intel Core i7-6700 I calculate n=9 in 1.2 seconds, and n=10 in 13.6 seconds. n=11 is just over 2 minutes.

FWIW:

n    a(n)
9    10408
10   45244
11   160248
12   762554


Mathematica 123 122 117 98 92 73 bytes

With 24 bytes saved thanks to LegionMammal978 and another 19 by alephalpha !

Surprisingly, in this table, multiple instances of any whole number n will have the same relative ordering in the spiral as they do in the table itself!
The first appearance of a number n lies at the very cell where that number appears first in the table (when one fills in the table row by row).  This means that the approach can disregard the spiral constraint altogether, for it has no bearing on the outcome.  (See explanation below.)

ReplacePart[t=1##&~Array~{#,#},Join@@(Rest[t~Position~#]&/@Union@@t)->0]&

Example

ReplacePart[t=1##&~Array~{#,#},Join@@(Rest[t~Position~#]&/@Union@@t)->0]&[10]

  {{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, {0, 0, 0, 0, 0, 12, 14, 16, 18,
    20}, {0, 0, 0, 0, 15, 0, 21, 24, 27, 30}, {0, 0, 0, 0, 0, 0, 28, 32,
     36, 40}, {0, 0, 0, 0, 25, 0, 35, 0, 45, 50}, {0, 0, 0, 0, 0, 0, 42,
     48, 54, 60}, {0, 0, 0, 0, 0, 0, 49, 56, 63, 70}, {0, 0, 0, 0, 0, 0,
     0, 64, 72, 80}, {0, 0, 0, 0, 0, 0, 0, 0, 81, 90}, {0, 0, 0, 0, 0,
    0, 0, 0, 0, 100}}

Grid[%]

Explanation

We exploit the fact that the spiral-order of the positions of any digit, n, is the same as the the order of row-col positions returned by the function, Positions!

The location of the first occurrence of each number (whether one orders by the spiral or by the table position) will be the first element returned by Position.  That first-occurrence cell will be left as it is. The remaining instances of the number are replaced by 0.

Let's look at how this works, examining for the case of n==18. The idea is to start with the multiplication table:

(t = Table[k Range@#, {k, #}] &[10]) // Grid

and locate the row-col positions of each number.  For example, 18 is located at
Row 2, Col 9 (the first instance); Row 3, Col 6; Row 6, Col 3; and Row 9, Col 2.
These have the respective spiral-order positions {44, 58, 68, 82}.

Position[t, 18]

  {{2, 9}, {3, 6}, {6, 3}, {9, 2}}

as the following table shows.

The final 3 instances of 18 need to be replaced by 0.  (We'll use a large bold blue zeros so they can be easily spotted.)

ReplacePart[%, {{3, 6}, {6, 3}, {9, 2}} -> Style[0, {Blue, Bold, 16}]]// Grid


Jelly, 12 bytes

Task 1

r

Try it online!

Task 2

r+þ0r$}

Try it online!

Task 3

r+þ0r$}
×þ

Try it online!

Task 4

r+þ0r$}
×þFṢ

Try it online!

How it works

Task 1

r is the dyadic range atom and does exactly what the task asks for.

Task 2

A dyadic chain that begins with three dyadic links is a fork; the outmost links get evaluated first, then the middle link is called with the results to both sides as arguments.

r behaves as before, yielding [n, …, m].
0r$} is a quicklink (or quickquicklink, if you will).

The quick $ (monadich chain) consumes the links 0 (yield 0) and r (dyadic range) and turns them into a monadic chain. When called with argument k, this will yield [0, …, k].

The quick } (right argument) takes the quicklink created by $ and turns it into a dyadic link that calls 0r$ with 0r$}'s right argument.

0r$} will be called with left argument n and right argument m, so 0r$ is alled with argument m and yields [0, …, m].
+þ is another quicklink. þ (table) will call + (addition) for every element in its left argument and any element in its right argument, grouping the results for each right argument into a single row.

+þ will be called with left argument [n, …, m] and right argument [0, …, m], yielding the desired table.

Task 3

Every line in a Jelly program defines a different link. The last one is the main link and, like C's main function, is the only link that is executed by default. The remaining links can be called from the main link, but we won't do this here.

As before, þ (table) will call × (addition) for every element in its left argument and any element in its right argument, grouping the results for each right argument into a single row.

Since both arguments to ×þ are integers, þ casts them to ranges, transforming the arguments n and m into [1, …, n] and [1, …, m].

Task 4

×þ works as before. The following links are monadic, making them atops, i.e., they are applied on top of the previous ones.

After executing ×þ, F flattens the resulting 2D array, and Ṣ sorts the resulting 1D array.


MATL, 24 23 bytes
xx:"tt3Y6Z+1Gm<8M2Gmb*+

Inputs are:

Array with birth rule
Array with survival rule
Number of generations
Matrix with initial cell configuration, using ; as row separator.

Try it online! Or see test cases: 1, 2.
For a few bytes more you can see the evolution in ASCII art.
Explanation
xx      % Take two inputs implicitly: birth and survival rules. Delete them
        % (but they get copied into clipboard G)
:"      % Take third input implicitly: number of generations. Loop that many times
  tt    %   Duplicate twice. This implicitly takes the initial cell configuration
        %   as input the first time. In subsequent iterations it uses the cell
        %   configuration from the previous iteration
  3Y6   %   Push Moore neighbourhood: [1 1 1; 1 0 1; 1 1 1]
  Z+    %   2D convolution, maintaining size
  1G    %   Push first input from clipboard G: birth rule
  m     %   Ismember: gives true for cells that fulfill the birth rule
  <     %   Less than (element-wise): a cell is born if it fulfills the birth rule
        %   *and* was dead
  8M    %   Push result of convolution again, from clipboard M
  2G    %   Push second input from clipboard G: survival rule
  m     %   Ismember: gives true for cells that fulfill the survival rule
  b     %   Bubble up the starting cell configuration
  *     %   Multiply (element-wise): a cell survives if it fulfills the survival
        %   rule *and* was alive
  +     %   Add: a cell is alive if it has been born or has survived, and those
        %   are exclusive cases. This produces the new cell configuration
        % Implicit end loop. Implicit display


27 24 bytes

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

Spent a whole day basically writing up a brute forcer and watching the results come in. Now I can get back to doing some actual work... Another day of brute forcing later...

Try it online!

The component ++[<++[++<]>>>+] initialises the tape to

[130, 0, 0, 0, 91, 59, 0]
                       ^

which is just perfect for what we need!


Distance solution:
Python 3, 52 Bytes

return max(min(abs(l-c)for l in s)for c in range(n))

Try it online!
Index solution (added after my first two comments):

Python 3, 59 bytes

return max((min(abs(l-c)for l in s),c)for c in range(n))[1]

Try it online!

Edit: Switched back to Distance solution,
Thanks to Jonathan Allan for -1 Byte


Ruby - 95 77 characters

a=[]
gets.split.each{|b|a<<(b=~/\d/?b.to_f: (j,k=a.pop 2;j.send b,k))}
p a[0]

Takes input on stdin.

Testing code

[
  "-4 5 +",
  "5 2 /",
  "5 2.5 /",
  "5 1 2 + 4 * 3 - +",
  "4 2 5 * + 1 3 2 * + /",
  "12 8 3 * 6 / - 2 + -20.5 "
].each do |test|
  puts "[#{test}] gives #{`echo '#{test}' | ruby golf-polish.rb`}"
end

gives

[-4 5 +] gives 1.0
[5 2 /] gives 2.5
[5 2.5 /] gives 2.0
[5 1 2 + 4 * 3 - +] gives 14.0
[4 2 5 * + 1 3 2 * + /] gives 2.0
[12 8 3 * 6 / - 2 + -20.5 ] gives 10.0

Unlike the C version this returns the last valid result if there are extra numbers appended to the input it seems.


Java 8, 167 154 152 bytes

s->{int l=s.length,r[]=new int[l],i=0,n,k;for(;i<l;r[i++]=n)n:for(n=0;;){for(k=++n;k-->0;)if(i+k<l&i+k>=n&&s[i+k]!=s[i-n+k])continue n;break;}return r;}

-2 bytes thanks to @ceilingcat.
Try it online.
Explanation:
s->{                          // Method with char-array parameter and int-array return-type
  int l=s.length,             //  Length of the input-array
      r[]=new int[l],         //  Result-array of the same size
      i=0,n,k;                //  Integers `i`, `n`, and `k` as defined in the challenge
  for(;i<l;                   //  Loop `i` in the range [0, `l`):
      r[i++]=n)               //    After every iteration: Add `n` to the array
    n:for(n=0;;){             //   Inner loop `n` from 0 upwards indefinitely
      for(k=++n;k-->0;)       //    Inner loop `k` in the range [`n`, 0]:
                              //    (by first increasing `n` by 1 with `++n`)
        if(i+k<l&i+k>=n)      //     If `i+k` and `i-n+k` are both within bounds,
           &&s[i+k]!=s[i-n+k])//     and if `s[i+k]` is not equal to `s[i-n+k]`:
          continue n;         //      Continue loop `n`
                              //    If we haven't encountered the `continue n` in loop `k`:
      break;}                 //     Break loop `n`
  return r;}                  //  Return the result


Can my favourite team still become Football Champion?

Haskell (Lambdabot), 84 bytes

Thanks to @bartavelle for saving me a byte.

Without Lambdabot, add 20 bytes for import Control.Lens plus a newline.

The function takes its arguments in the same order as described in the OP, 0-indexed. Its second argument (the list of remaining matchups) is a flat list of indexes (e.g. [1,2,4,1] corresponds to [(Team 1 vs Team 2), (Team 4 vs Team 1)]).

The rules are a little vague as to whether or not this is allowed. If it isn't allowed, the function can take input in the format provided by the examples – a list of tuples. In that case, add 2 bytes to this solution's score, due to replacing a:b:r with (a,b):r.

(!)=(+~).element
(t?(a:b:r))s=any(t?r)[a!3$s,b!3$s,b!1$a!1$s]
(t?_)s=s!!t==maximum s

Explanation:

The first line defines an infix function ! of three variables, of type (!) :: Int -> Int -> [Int] -> [Int], which increments the value at a given index in a list. Since, oftentimes, code is easier to understand than words (and since Haskell syntax can be weird), here's a Python translation:

def add(index, amount, items):
    items[index] += amount
    return items

The second line defines another infix function ?, also of three variables (the challenge input). I'll rewrite it more readably here:

(t ? a:b:r) s = any (t ? r) [a ! 3 $ s, b ! 3 $ s, (b ! 1 $ a) ! 1 $ s]
(t ? _) s = (s !! t) == maximum s

This is a recursive implementation of exhaustive search. It recurs over the list of remaining games, branching on the three possible outcomes, and then, once the list is empty, checking whether or not our team has the maximum number of points. Again in (non-idiomatic) Python, this is:

def can_still_win(standings, games_left, our_team):
    if games_left == []:
        return standings[our_team] == max(standings)
    team1, team2, other_games = games_left[0], games_left[1], games_left[2:]
    team1Wins, team2Wins, tie = standings.copy(), standings.copy(), standings.copy()
    team1Wins[team1] += 3
    team2Wins[team2] += 3
    tie[team1] += 1
    tie[team2] += 1
    return (can_still_win(team1Wins, other_games, our_team)
            or can_still_win(team2Wins, other_games, our_team)
            or can_still_win(tie, other_games, our_team))

Try it online!

*Sadly, TiO doesn't support Lens, so this link won't actually run.


Build a solver for the cow and chicken problem

Mathematica 359 314
About 200 characters went into determining which condition applies.
f@{a_, b_, c_, d_, i_, l_} :=
 Module[{s, t, z = "invalid problem", y = IntegerQ},
  t@n_ := y@n \[And] (n > 0);
  p@n_ := n \[Element] Rationals \[And] n > 0;
  q@n_ := n \[Element] Reals;
  w = Flatten@Quiet@Solve[{d*x + b*k == l, c*x + a*k == i}, {k, x}];
  s = {k, x} /. w;
  Which[w == {}, {5, z},
   Length[w] != 2, {6, z},
   True, If[And @@ (t /@ s), {1, s},
    Which[
     And @@ (p /@ s), {2, z},
     And @@ (y /@ s), {3, z},
     And @@ (q /@ s), {4, z},
     3 == 3, {7, z}]]]]

f[{1, 4, 1, 2, 24, 68}]
f[{7, 14, 9, 6, 25, 18}]
f[{1, 4, 1, 2, 24, 67}]
f[{1, 4, 1, 2, 24, 36}]
f[{1, 4, 1, 2, 24, 97}]
f[{2, 4, 1, 2, 24, 68}]
f[{2, 4, 1, 2, 24, 48}]
f[{1, 4, 1, 2, -23, (3 + I)^2/(5 - I)}]
f[{6, 9, 4, 6, 10, 15}]

{1, {10, 14}}
{2, "invalid problem"}
{2, "invalid problem"}
{3, "invalid problem"}
{4, "invalid problem"}
{5, "invalid problem"}
{6, "invalid problem"}
{7, "invalid problem"}
{6, "invalid problem"}

How it works
The  equations d*x+b*k==land c*x+a*k==i express the constraints in the general cow and chickens problem,where

a is "the number of heads per cow"
b is "the number of legs per cow"
c is "the number of heads per chicken"
d is "the number of legs per chicken"
i is "the number of  heads"
l is "the number of legs"
k is "the number of cows"
x is "the number of chickens".

Solve returns the real - valued solutions, if any exist, for the cows and chickens, as a list of 2 substitution rules, e.g.
{k->10, x-> 14}
If no solutions exist, an empty list is returned.
If the data cannot be processed, Solve will return a different number of elements.
The tests are performed in the following order.

If there are 0 solutions, condition 5 is satisfied

If the list of "solution"s has anything other than 2 elements, then condition 6 is satisfied .

If there are 2 solutions, then

if function t yields True, the solution is a pair of non-negative integers, and condition 1 is satisfied.
if function p yields True, the solution is a pair of  non negative rationals and condition 2 is satisfied.
if function q yields True, the solution is a pair of  non negative rationals and condition 3 is satisfied.
if function y yields True, the solution is a pair of  integers and condition 4 is satisfied.
Otherwise, condition 7 is satisfied.

Minor Variant of f
g@{a_, b_, c_, d_, i_, l_} :=
 Module[{s, t, z = "invalid problem", y = IntegerQ},
  t@n_ := y@n \[And] (n > 0);
  p@n_ := n \[Element] Rationals \[And] n > 0;
  q@n_ := n \[Element] Reals;
  w = Flatten@Quiet@Solve[{d*x + b*k == l, c*x + a*k == i}, {k, x}];
  s = {k, x} /. w;
  Which[w == {}, {5, z, w}, Length[w] != 2, {6, z, w}, True,
   If[And @@ (t /@ s), {1, s, w},
    Which[And @@ (p /@ s), {2, z, w}, And @@ (y /@ s), {3, z, w},
     And @@ (q /@ s), {4, z, w}, 3 == 3, {7, z, w}]]]]

g is f` with the additional property that it returns the output of Solve.
g[{1, 4, 1, 2, 24, 68}]
g[{7, 14, 9, 6, 25, 18}]
g[{1, 4, 1, 2, 24, 67}]
g[{1, 4, 1, 2, 24, 36}]
g[{1, 4, 1, 2, 24, 97}]
g[{2, 4, 1, 2, 24, 68}]
g[{2, 4, 1, 2, 24, 48}]
g[{1, 4, 1, 2, -23, (3 + I)^2/(5 - I)}]
g[{6, 9, 4, 6, 10, 15}]

{1, {10, 14}, {k -> 10, x -> 14}}
{2, "invalid problem", {k -> 1/7, x -> 8/3}}
{2, "invalid problem", {k -> 19/2, x -> 29/2}}
{3, "invalid problem", {k -> -6, x -> 30}}
{4, "invalid problem", {k -> 49/2, x -> -(1/2)}}
{5, "invalid problem", {}}
{6, "invalid problem", {x -> 24 - 2 k}}
{7, "invalid problem", {k -> 615/26 + (19 I)/26, x -> -(1213/26) - (19 I)/26}}
{6, "invalid problem", {x -> 5/2 - (3 k)/2}}

Problems falling under condition 6 have multiple solutions, as evidence by the equations.  The problem that falls under condition 5 returns an empty set (no solutions).
Note: element and and are single characters in Mathematica.


Brachylog, 8 bytes
ṫ{~cịᵐ}ᵘ

Convert to string ṫ and get all unique {…}ᵘ reverse concatenations ~c mapped to integers ịᵐ (to remove leading zeros).
Try it online!


APL (Dyalog Unicode), 15 bytesSBCS

1|(-,.5∘-,+⍨)?0

Try it online!

A full program that generates three floating-point numbers \$ X,Y,Z \$.

The distribution

Uses the same method as Luis Mendo's MATL answer, which in turn is from this Math.SE answer. The Math.SE answer presents the following random variables:

$$
X = \text{uniform random value in } (0,1) \\
Y = \begin{cases} X + \frac12, \quad X < \frac12 \\
X - \frac12, \quad X \geq \frac12 \end{cases} \\
Z = \frac32 - (X + Y)
$$

I found that this is equivalent to

$$
X = \text{uniform random value in } (0,1) \\
Y = \{ X + 1/2 \}, Z = \{-2X\}
$$

which, in turn, has the same distribution with

$$
r = \text{uniform random value in } (0,1) \\
X = \{ -r \}, Y = \{ 1/2 - r \}, Z = \{ 2r \}
$$

where the notation \$ \{ x \} \$ means the positive fractional part of \$ x \$.

How the code works

1|(-,.5∘-,+⍨)?0
             ?0  ⍝ r←Generate a random number from (0,1)
  ( ,    ,  )    ⍝ Create a 3-element array from r:
   -             ⍝ -r
     .5∘-        ⍝ 0.5 - r
          +⍨     ⍝ r + r (= 2r)
1|               ⍝ Extract positive fractional part from each number

Test script

⍝ Take 10000 samples of X, Y, Z's
data←f¨⍳10000

⍝ Tests that X+Y+Z = 1.5 in all cases
∧/1.5=+/¨data

⍝ Shows the distribution of X,Y,Z in 10 bins
{(⊂∘⍋⌷⊢)↓,∘≢⌸⍵}¨⌊10×↓⍉↑data
                    ↓⍉↑data  ⍝ Reform the data into X's, Y's, and Z's
                ⌊10×         ⍝ Classify into 10 bins
{             }¨     ⍝ For each of X's, Y's, or Z's,
        ↓,∘≢⌸⍵       ⍝ Gather the list of (bin, count)
 (⊂∘⍋⌷⊢)             ⍝ Sort the bins

⍝ Example result
X:  0 1012  1 1016  2 993   3 1025  4 1002  5 969   6 1002  7 977  8 1049  9 955
Y:  0 969   1 1002  2 977   3 1049  4 955   5 1012  6 1016  7 993  8 1025  9 1002
Z:  0 1013  1 944   2 1022  3 1052  4 990   5 980   6 1039  7 979  8 959   9 1022

Alternative method, 21 bytesSBCS

(3*9),3⊥¨3|(⍳3)+⊂?9/3

Try it online!

This one uses the OP's formulation from the same Math.SE question:

Generate a uniform random number \$ X \$ from \$ (0, 1) \$.
Take its ternary digits \$ X = 0.X_1 X_2 X_3 \cdots \$ and generate ternary digits of \$ Y \$ and \$ Z \$:

$$
Y_i = (X_i + 1) \% 3 \\
Z_i = (X_i + 2) \% 3
$$

Then the resulting numbers \$ X,Y,Z \$ are uniform in range \$ (0, 1) \$, and their sum is

$$
\frac3{3^1} + \frac3{3^2} + \frac3{3^3} + \cdots = \frac32
$$

Theoretically it requires infinite number of digits; the code approximates the scheme with just 9 digits, which makes \$ X+Y+Z=1.499923792 \$. I'm not exactly sure if it meets the OP's spec though.

How the code works

(3*9),3⊥¨3|(⍳3)+⊂?9/3
                 ?9/3  ⍝ Generate 9 ternary digits
         3|(⍳3)+⊂      ⍝ Ternary digits for X,Y,Z
      3⊥¨  ⍝ Convert each list of digits to numerator for the fraction
(3*9),     ⍝ Prepend the denominator


GolfScript, 14 12 characters
' '-n%zip$n*

Input must be given on STDIN, the character for coins can be any non-whitespace characters. Try here. Thanks to Peter for pointing out a two character reduction.


Construct a pentagon avoiding compass use

2 circles, 13 lines, 17 points

Try it on GeoGebra

Let circle(A, B) intersect circle(B, A) at C and D.
Let AB intersect circle(A, B) again at E.
Let AB intersect circle(B, A) again at F.
Let AD intersect circle(A, B) again at G.
Let AD intersect CF at H.
Let BG intersect DF at I.
Let HI intersect circle(A, B) at J and K.
Let BG intersect EJ at L.
Let BJ intersect EG at M.
Let BG intersect EK at N.
Let BK intersect EG at O.
Let LM intersect circle(A, B) at P and S.
Let NO intersect circle(A, B) at Q and R.

Then EPQRS is a regular pentagon.

Why it works

Let BE intersect GJ at T, and let BE intersect GK at U.  The complete quadrilateral BEGJ shows that T is the polar of LM, which is the intersection of the tangents at P and S.  Similarly, the complete quadrilateral BEGK shows that U is the polar of NO, which is the intersection of the tangents at Q and R.

Let FG intersect HI at V.  The diagonals DV and GI of the complete quadrilateral DGVI intersect FH at harmonic conjugates with respect to F and H; since the first is at ∞, the second is the midpoint C of FH, which is to say that C, D, V are collinear.

Let CG intersect HI at W.

Now for the fun part.  Line FUBAT is perspective about G to line VKIHJ, which is perspective about D to circle CKDGJ, which is perspective about C to line HKVWJ, which is perspective about G to line AUF∞T.  Composing these four perspecitivities yields a projectivity FUBAT ⌅ AUF∞T.  Since a one-dimensional projectivity is determined by three points, T and U are determined as the two fixed points of FBA ⌅ AF∞.

Assigning coordinates with A = 0, B = −1, F = −2, this projectivity is defined by x ↦ 4/x + 2, and its fixed points T = 1 + √5 = sec(2π/5) and U = 1 − √5 = −sec(2π/10), exactly as required to make EPQRS a regular pentagon.


Jelly, 9 bytes
fØẠŒlÞ$ƑƇ

Try it online!
-3 bytes thanks to Nick Kennedy
fØẠŒlÞ$ƑƇ  Main Link
        Ƈ  Keep elements that are
       Ƒ   Invariant when
.[][.]$    Last two links combined, but [ØẠ][ŒlÞ] is an LCC, so it takes another
f          Filtered to keep
 ØẠ        Alphabetical characters
     Þ     And sorted by
   Œl      Lowercase

Basically, "keep elements that are invariant when you filter out non-alphabetical characters and sort alphabetically". Jelly's sort is stable.


explode('&',http_build_query($a))

33 bytes


Python 2, 124  118 116

t=eval(input().replace("\x3A","."))
print["Bread","Warm Bread","Toasty","Burnt","Brulee"][sum([t>3.3,t>2,t>1,t>.3])]

Try it online!

-6 with thanks to @tsh and also thanks for tho TIO test cases.

-2 with a couple of cool tips from @BlackOwlKai

Throws a ValueError for invalid inputs that cannot be converted to a float. For numbers less than 0 it returns "Bread" because it is still bread. Guess if we are really strict on ensuring that the input is a valid time it could be done but for me the interesting bit was how to avoid the : in Python.


JavaScript ES6, 22 bytes

a=>b=>(0|a/30)+":"+b/6

Try it online (all browsers work)


php --> asp --> html --> xhtml .......
 Hello

Infinite languages


Programming Less-Than, Greater-Than and Equal-To functions using Restricted Source

Integers and round-to-zero integer division
// 1 if x >= y, 0 otherwise
GE(x, y) = (x - y + 1) / (abs(x - y) + 1)
LE(x, y) = GE(y, x)
E(x, y) = GE(x, y) * LE(x, y)
L(x, y) = LE(x, y) - E(x, y) = 1 - GE(x, y)
G(x, y) = GE(x, y) - E(x, y) = 1 - LE(x, y)

If x - y is negative, x - y + 1 has smaller magnitude than abs(x - y) + 1, so the division rounds to 0.
If x - y is zero or higher, x - y + 1 is the same as abs(x - y) + 1, so the result is 1.
Integers and floored integer division
GE(x, y) = (x - y + abs(x - y) + 1) / (abs(x - y) * 2 + 1)

If x - y is negative, the numerator is fixed at 1, but the denominator is at least 3. Therefore the result is zero.
If x - y is zero or positive, the numerator and the denominator are the same, so the result is 1.
Floating-point numbers
MarcMush pointed out a possible use of eps, the smallest representable number greater than 0. GE can be implemented for floating-point numbers using it:
GE(x, y) = (max(x - y, -eps) + eps)/(abs(x - y) + eps)

I haven't found any way without eps or the floor function. (If floor is available, flooring the second solution works for floats.) tsh pointed out that we can't get a (true) discontinuous function from a bunch of continuous functions, so I'm pretty sure it is impossible without eps or an additional built-in that provides discontinuity.
Assuming an IEEE floating-point representation, the solution above is expected to give exact results (exactly 0 or exactly 1) for all non-NaN, non-infinite floating-point values of x and y.


C,129
f(){int i,n,m,r,s,t;for(i=26;i--;i<25&&printf("%c%c","URFDLB"[s%6],"'2"[r%3])){for(n=m,t=1;t;t=m*n==9)m=(r=rand()%15)/3+1;s+=m;}}

The inner loop generates a value of m in the range 1..5 which when added to s and taken modulo 6, ensures that no two consecutive moves are on the same side of the cube. The old value of m is stored in n and the test m*n==9 ensures that the value m=3 is never generated twice in a row (so opposite faces cannot be picked twice in a row; note the order of faces in the string.)
The least significant part of r is used to decide which suffix (', 2 or null) to use, taking advantage of the null character at the end of "'2".
The outer loop runs 26 times. The first time, U can never be picked, so printf is suppressed for the first iteration.
Ungolfed code in test program
The ungolfed code puts a space between each move for clarity (the golfed code does not, in order to save one byte.) Additionally the golfed code saves a semicolon by relocating the printf within the for bracket.
f(){
  int i,n,m,r,s,t;
  for(i=26;i--;){
    for(n=m,t=1;t;t=m*n==9)m=(r=rand()%15)/3+1;
    s+=m;
    i<25&&printf("%c%c ","URFDLB"[s%6],"'2"[r%3]);
  }
}

main(){
  int j;
  srand(time(0));
  for(j=0;j<5;j++)f(), puts("");
}

Typical output
U' B D2 B' R' L F' D2 B D2 B2 R' B2 U D2 F' R U R' L B' L R2 B2 F'
U B U B F L2 D2 B' U' L B L R' D B U' D R D' B' F2 D' B D R
L D F2 B2 R' U F B' D2 L U R' L' U2 F' R F D U2 B L' B' U L2 F'
R2 B' F2 R2 L2 F' U2 L U' B' F R' D' F2 D F' L2 U2 R' D' B2 D F R2 L'
U2 F2 B2 D' F D F R L2 U' B D2 L' R D R F2 R' F2 U2 D R' D2 L F2


Use + instead of toString

As one might expect, String overloads the + operator for string concatenation, like so.

print("Hel" + "lo")

However, checking the docs tells us that it accepts Any?, not just String. As stated:

  Returns a string obtained by concatenating this string with the string representation of the given other object.

In other words, String + anything makes sure to call .toString() on the right hand side before concatenating. This allows us to shorten it.toString() to ""+it, a massive 8 byte savings at best and 6 bytes at worst.

Use fold instead of joinToString

Related to the above, if you're calling map and then joinToString, you can shorten that by using fold instead.

list.map{it.repeat(3)}.joinToString("")
list.fold(""){a,v->a+v.repeat(3)}


Doors doors doors, c'mon down to the door store!

JavaScript, 4380 characters, 65(?) points

ASCII? Check. HTML? Check. Is a door? Check. Openable door? Check. Interactive? Check. Fancy? Double doors with properly positioned hinges, I hope that counts. Animated? Check. Under 100 characters? Ha. Not using facilities intended for drawing? Check.

Live demo. (Note: In my testing with Firefox, clicking the doors more than once doesn't work — for some reason the event handler doesn't fire again and I'm baffled as to why; pointing out what I did wrong would be welcome. Though, you might want to run this in Chrome anyway for decent JS performance.)

<title>Door</title>

Click doors to open or close.

When closed, the doors look like this:


05AB1E, 59 bytes

-1 byte thanks to Kevin Cruijssen

žVDu«1ú`žhÀ“~!@#$%^&*()_+ `ÿ-=ÿ<>?ÿ:"ÿ{}|ÿ,./ÿ;'ÿ[]\“#vy¦y‡

Try it online!


JavaScript (ES6) 234 246

Longer than I expected ...

Run snippet to test (in Firefox)

// Golfed

F=t=>t.split('\n').map((r,j,t)=>(
  [...r].map((c,i)=>(
    f=c==r[i+2]&c==u[i+1]&c==v[i]&c==v[i+2],
    c!='x'&c!='X'?z+=f
    :(++z,f?k[j+[,i]]=k[2+j+[,i]]=k[1+j+[,i+1]]=k[j+[,i+2]]=k[2+j+[,i+2]]=1:0)
  )),v=u,u=r),
k={},u=v=z=0)&&z-Object.keys(k).length

// Ungolfed

U=t=>{
  var k={}, u=0,v=0,z=0, t=t.split('\n')
  t.forEach((r,j)=> {
    [...r].forEach((c,i)=> {
      x = c=='x'|c=='X' // is any X
      f = c==r[i+2] & c==u[i+1] & c==v[i] & c==v[i+2] // is in a formation
      if (x)
      {
        ++z
        if (f)
        { // remember the position of X involved in a formation, avoid counting duplicates more tha once
          k[j+[,i]]=k[2+j+[,i]]=k[1+j+[,i+1]]=k[j+[,i+2]]=k[2+j+[,i+2]]=1
        }
      }
      else
      {
        z+=f
      }
    })
    v=u,u=r
  })
  return z-Object.keys(k).length
}

// TEST

Out=s=>OUT.innerHTML=OUT.innerHTML + s;

['a','a a\n a\na a','x xxx\n X x\nx xxx', 'x-x+x+X++\n-x-x+x++asd\nx-x+x+X+'
,'########\n#####\n########','a-a-a\n0a0a\na-a-axXxX\n0a0a\na-a-a'
,'a c efghi\nab defgh\na c e ghij\nabcd fgh\nabc e g'
,'/\\/\\/\\/\\/\\/\\/\\\n\\/\\/\\/\\/\\/\\/\\/\n#####x-x+x+X++\n#####-x-x+x++###XX\n#####x-x+x+X+\n/\\/\\/\\/\\/\\/\\/\\\n\\/\\/\\/\\/\\/\\/\\/'
,'xxxxxxxxxx\nxxxxxxxXX\nxxxxxxxxxx\nxxxxxxxxxx\nxxxxxxxxxx\nxxxxxxxx']
.forEach(t=>Out(t+'\n'+F(t)+'\n\n'))
b { color: #00f }


Python 2, 43 bytes

lambda s,*l:eval('s'+'.replace(*l)'*len(s))

Try it online!

Evaluates a string of the form

s.replace(*l).replace(*l).replace(*l) ...

To reach a fixed point if one exists, it suffices to do replacements equal to the length of the original string.


Sort scrambled two-dimensional array filled with numbers by swapping adjacent numbers

Mathematica, not golfed

towards[a_,b_]:={a,a+If[#==0,{0,Sign@Last[b-a]},{#,0}]&@Sign@First[b-a]};
f[m_]:=Block[{m2=Map[QuotientRemainder[#-1,10]+1&,m,{2}]},
  Rule@@@Apply[10(#1-1)+#2&,#,{2}]&@
    Reap[Table[
      m2=NestWhile[
        Function[{x},x/.(Sow[#];Thread[#->Reverse@#])&[x[[##]]&@@@towards[First@Position[x,i,{2}],i]]]
        ,m2,#~Extract~i!=i&];
      ,{i,Reverse/@Tuples[Range[10],2]}];][[2,1]]]

Explanation:

The algorithm is similar to "bubble sort". These 100 numbers are put into correct order one by one, 1, 11, 21, ..., 91; 2, ..., 92; ...; 10, ..., 100. They are first move up/down to the correct rows, and then move left to the correct columns.

Function towards gives the two position to swap. For example, if {5,2} is moving to {1,1}, towards[{5,2},{1,1}] gives {{5,2},{5,1}} (move up); and  towards[{5,1},{1,1}] gives {{5,1},{4,1}} (move left).

Results:

For the test case, the total number of swaps is 558. The first few swaps are,

{1->76,1->34,1->35,1->88,1->41,11->16,11->69,11->46, ...

For a random configuration, the total number of swaps is 558.5 ± 28.3 (1σ).


Python - 248 243 230 227 191

Slightly messy but it basically prints the cube line by line(using a string buffer).

t=v=h=input()/2
s,p,b,f,n=" +|/\n"
l=p+"-"*t*4+p;S=s*4*t;k=s*h;K=b+S+b
r=s*t+s+l+n
while t:r+=s*t+f+S+f+s*(h-t)+b+n;t-=1
r+=l+k+b+n+(K+k+b+n)*(v-1)+K+k+p+n
while v:v-=1;r+=K+s*v+f+n
print r+l

Thanks to @marcog, for pointing out the first line, @ThomasO for pointing out the second line and to @Juan for making me realise I can combine lines.


Program that outputs a program that outputs a program ... that outputs "Hello!"

Golfscript 39 14

~'Hello!'{`}@*

Example:

Assuming that n=4 and our program is P, these are the steps:

Run P with parameter 4. The output is "\"\\\"\\\\\\\"Hello!\\\\\\\"\\\"\"" (P1)
Running P1 outputs "\"\\\"Hello!\\\"\"" (P2)
Running P2 outputs "\"Hello!\"" (P3)
Running P3 outputs "Hello!"(P4)
Running P4 outputs Hello!. If you don't trust me, follow this link ☺.


Bash + GNU utilities, 37

tr , \\n|date -f- +%s|dc -e??-86400/p

tr replaces the comma with a newline.  date reads the newline separated dates and outputs the number of seconds since the Unix epoch that the passed-in date represents.  These numbers are then put on the dc stack.  Then its a simple matter of subtraction and divide by (24*60*60).  In this case, dc stack-based RPN arithmetic evaluation is better than bc or bash $( ), mostly because the subraction-before-division needs no parentheses.

Input via STDIN:

$ echo 2015-12-3,2015-12-1 | ./longago.sh
2
$ echo 2015-12-3,2014-12-1 | ./longago.sh
367
$ echo 2015-12-3,2013-12-3 | ./longago.sh
730
$


Mathematica: 68
Graphics@Raster@Reverse[List@@Hue[#/100]~ColorConvert~"RGB"&/@#&/@o]

Still figuring out the extra.


05AB1E, 15 bytes
„-|v€Åγ˜y¢Iø}Š+

Try it online!
Commented:
„-|              # push string literal "-|"
   v        }    # iterate over this string
    €Åγ          #   run-length encode each line of the input / transposed input
                 #   this pushes the chunk elements and the chunk lengths
       ˜         #   flatten the list
        y¢       #   count the chunks of the current character
          Iø     #   push the transposed input to the stack for the second iteration
             Š   # triple-swap: move the transposed input to bottom
              +  # sum both counts


JavaScript (Node.js), 49 bytes

a=>!a.some((p,i)=>a.some((q,j)=>q>p&a[j+=j>i]<p))

Try it online!

Using the fact that for array \$a_0 ... a_{n-1}\$, \$a\$ is the pre-order traversal of some BST iff \$ \forall 0\le i<j<n; a_i<a_{j-1} \implies a_i<a_j \$ holds.

Thanks to Arnauld, save 1 byte.


CJam, 14 bytes

q:X{mr_X.=:|}g

Try it online!

Keeps shuffling the input until it's a derangement.

Explanation

q:X   e# Read input and store it in X.
{     e# While the condition at the end of the loop is truthy...
  mr  e#   Shuffle the string.
  _X  e#   Duplicate it and push the input.
  .=  e#   Element-wise equality check.
  :|  e#   Reduce OR over the list, gives something truthy if any character
      e#   remained in its original position.
}g


JavaScript (ES6), 101 99 bytes

Takes input as 2 arrays. Returns a string.

f=(a,b,j=0,s='')=>a.map((v,i)=>(s+=i*j?' ':s&&'][',s+=b[j]+v,j=++j%b.length))|j?f(a,b,j,s):`[${s}]`

How it works

We iterate on the first array a with a pointer i while updating another pointer j into the second array b. The sums a[i] + b[j] are appended to the output string s. A separator is inserted each time i == 0 or j == 0. We repeat this process until j is back exactly at the beginning of b at the end of an iteration.

Note: When the | operator is applied, a.map(...) is coerced to either NaN (if a contains more than one element) or the current value of j (if a contains exactly one element). Therefore, a.map(...)|j == j in all cases and is safe to use here.

Test cases

f=(a,b,j=0,s='')=>a.map((v,i)=>(s+=i*j?' ':s&&'][',s+=b[j]+v,j=++j%b.length))|j?f(a,b,j,s):`[${s}]`

console.log(f([1], [4]));
console.log(f([1,2,-3,-4], [15]));
console.log(f([0,-4], [2,1,0,-3]));
console.log(f([0,3,2,2,8,4], [7,8,7,2]));
console.log(f([18,17,16], [-1,-2,-3,-4]));
console.log(f([18,17,16,15], [-1,-2,-3,-4]));
console.log(f([1,1,1,1,1], [6,5,6,5,6,5,6,2,1]));
console.log(f([1,1,1,1,1,1], [6,5,6,5,6,5,6,2,1]));
console.log(f([1,1,1,1,1,1,1], [6,5,6,5,6,5,6,2,1]));


Rotate An Integer Array with an O(n) algorithm

C (104)
void reverse(int* a, int* b)
{
    while (--b > a) {
        *b ^= *a;
        *a ^= *b;
        *b ^= *a;
        ++a;
    }
}

void rotate(int *arr, int s_arr, int by)
{
    reverse(arr, arr+s_arr);
    reverse(arr, arr+by);
    reverse(arr+by, arr+s_arr);
}

Minified:
v(int*a,int*b){while(--b>a){*b^=*a;*a^=*b;*b^=*a++;}}r(int*a,int s,int y){v(a,a+s);v(a,a+y);v(a+y,a+s);}


CJam, L = 1482, N = 114, score 0.114

'C:L"arbon"  L'h+:L;"Gold"L'u+:L;"Iron"L'c+:L;"Lead"L'k+:L;"Neon"LS+:L;"Argon"L'N+:L"ickel"L'o+:L;"Zinc""Coppe"L'r+:L"Silve"L'r+:LL'i+:L;"Tin" "Boron"      "Radon"      "Barium"     "Cerium"     "Cesium"     "Cobalt"     "Curium"     "Erbium"     "Helium"     "Indium"     "Iodine"     "Osmium"     "Oxygen"     "Radium"     "Sodium"     "Sulfur"     "Arsenic"    "Bismuth"    "Bohrium"    "Bromine"    "Cadmium"    "Calcium"    "Dubnium"    "Fermium"    "Gallium"    "Hafnium"    "Hassium"    "Holmium"    "Iridium"    "Krypton"    "Lithium"    "Mercury"    "Niobium"    "Rhenium"    "Rhodium"    "Silicon"    "Terbium"    "Thorium"    "Thulium"    "Uranium"    "Yttrium"    "Actinium"   "Aluminum"   "Antimony"   "Astatine"   "Chlorine"   "Chromium"   "Europium"   "Fluorine"   "Francium"   "Hydrogen"   "Lutetium"   "Nihonium"   "Nitrogen"   "Nobelium"   "Platinum"   "Polonium"   "Rubidium"   "Samarium"   "Scandium"   "Selenium"   "Tantalum"   "Thallium"   "Titanium"   "Tungsten"   "Vanadium"   "Americium"  "Berkelium"  "Beryllium"  "Flerovium"  "Germanium"  "Lanthanum"  "Magnesium"  "Manganese"  "Moscovium"  "Neodymium"  "Neptunium"  "Oganesson"  "Palladium"  "Plutonium"  "Potassium"  "Ruthenium"  "Strontium"  "Tellurium"  "Ytterbium"  "Zirconium"  "Dysprosium" "Gadolinium" "Lawrencium" "Meitnerium" "Molybdenum" "Phosphorus" "Promethium" "Seaborgium" "Technetium" "Tennessine" "Californium""Copernicium""Einsteinium""Livermorium""Mendelevium""Roentgenium"]L's+"Xenon"?

Try it online!

Each program is 13 bytes long. Here they are split up into individual lines:

'C:L"arbon"
L'h+:L;"Gold"
L'u+:L;"Iron"
L'c+:L;"Lead"
L'k+:L;"Neon"
LS+:L;"Argon"
L'N+:L"ickel"
L'o+:L;"Zinc"
"Coppe"L'r+:L
"Silve"L'r+:L
L'i+:L;"Tin"
"Boron"
"Radon"
"Barium"
"Cerium"
"Cesium"
"Cobalt"
"Curium"
"Erbium"
"Helium"
"Indium"
"Iodine"
"Osmium"
"Oxygen"
"Radium"
"Sodium"
"Sulfur"
"Arsenic"
"Bismuth"
"Bohrium"
"Bromine"
"Cadmium"
"Calcium"
"Dubnium"
"Fermium"
"Gallium"
"Hafnium"
"Hassium"
"Holmium"
"Iridium"
"Krypton"
"Lithium"
"Mercury"
"Niobium"
"Rhenium"
"Rhodium"
"Silicon"
"Terbium"
"Thorium"
"Thulium"
"Uranium"
"Yttrium"
"Actinium"
"Aluminum"
"Antimony"
"Astatine"
"Chlorine"
"Chromium"
"Europium"
"Fluorine"
"Francium"
"Hydrogen"
"Lutetium"
"Nihonium"
"Nitrogen"
"Nobelium"
"Platinum"
"Polonium"
"Rubidium"
"Samarium"
"Scandium"
"Selenium"
"Tantalum"
"Thallium"
"Titanium"
"Tungsten"
"Vanadium"
"Americium"
"Berkelium"
"Beryllium"
"Flerovium"
"Germanium"
"Lanthanum"
"Magnesium"
"Manganese"
"Moscovium"
"Neodymium"
"Neptunium"
"Oganesson"
"Palladium"
"Plutonium"
"Potassium"
"Ruthenium"
"Strontium"
"Tellurium"
"Ytterbium"
"Zirconium"
"Dysprosium"
"Gadolinium"
"Lawrencium"
"Meitnerium"
"Molybdenum"
"Phosphorus"
"Promethium"
"Seaborgium"
"Technetium"
"Tennessine"
"Californium"
"Copernicium"
"Einsteinium"
"Livermorium"
"Mendelevium"
"Roentgenium"
]L's+"Xenon"?

The missing elements are Darmstadtium, Praseodymium, Protactinium and Rutherfordium which are 12 or 13 characters long which means I can't print them in 13 characters each.

The idea is that the first few programs, which prints the elements with short names use their extraneous characters to build the string Chuck Norri in the variable L, which does not affect the output when used on their own. The final program then checks if anything is already on the stack, and uses it to choose between L (plus s) and Xenon.

A few additional bytes are saved by using the character we just added to L as part of the element name, specifically for Carbon, Nickel, Copper and Silver.


Mathematica, 126 122 121 89 bytes

Image[1-Thread@IntegerDigits[l=Round[(#+3#~Mod~2)^2/48]&/@Range@##,2,⌈2~Log~Max@l⌉]]&

This defines an unnamed function taking the two integers as parameters and displaying the image on screen. It plots each square as a single pixel, but if you like you can actually zoom in.

I'm now using an explicit formula given in the OEIS article (first one in the Mathematica section, thanks to David Carraher for pointing that out). It's also blazingly fast now.

Here is the indented code with a few comments:

Image[1-Thread@IntegerDigits[   (* 3. Convert each number to padded binary, transpose
                                      invert colours, and render as Image. *)
    l = Round[
      (#+3#~Mod~2)^2/48
    ] & /@ Range@##,            (* 1. Turn input into a range and get the Alcuin
                                      number for each element. *)
    2,
    ⌈2~Log~Max@l⌉               (* 2. Determine the maximum number of binary digits. *)
]] &

Here is the output for 0, 600:


cQuents, 4 bytes (Cracked)

"::$

Try it online!

Here are eight (n=8) cases:

1 1
2 12
3 123
4 1234
5 12345
6 123456
7 1234567
8 12345678

Code explanation:

"      Stringify sequence (join on "", remove it and see what happens)
 ::    Given input n, output all items in the sequence up to and including n
   $   Each item in the sequence equals the index

So the sequence is 1,2,3,4,5 ..., it is joined on "" so it becomes 12345 ..., and :: means that it prints up to the input.


C++ 158 chars
#include<iostream>
#include<iomanip>
int main(){double p=0;for(long long l=1;l>0;l+=2){p+=(double)4/l;l+=2;p-=(double)4/l;}std::cout<<std::setprecision(30)<<p;}

Simply calculates pi by brute force until my computer can't store the number to divide 4 by.
I got to 3.1415926535792384 before I killed it. The highlighted part is what is off; it should have been 3.1415926535897932.  Eventually, it would have got there.


C 550 503

#define L putchar('\n');
c,b,i,j,m[]={0xe9d72e,0x10fd25,0x9ace29,0x556b5,0x4fd184,0x16ad6bd,0x156ae,0xc5e10,0x556aa,0x756a8,0,0,0,0,0,0,0,0xfa51e0,0xaad7e0,0x118c5c0,0xe8c7e0,0x15ad7e0,0x14a53e0,0x16ac5c0,0x1f213e0,0xf8000,0x1e08440,0x11513e0,0x1087e0,0x1f4111f,0x1f223e0,0xe8c62e,0x8a53e0,0xd9462e,0x5d29f,0x12ad6a9,0x1087e10,0xf043e,0x18304d8,0x1c1f07c,0xd909b,0xf14bd,0xcd6b3};main(){for(;;){c=getchar();c=c<48?11:c>90?c-80:c-48;b=0;for(i=0;i<5;i++){for(j=0;j<5;j++)putchar(m[c]&(1<<b++)?35:32);L}L}}

(Incorporated BrainSteel's tips and optimized a bit more)

Here's the non-obfuscated code:

#include <stdio.h>

int map[]
={
    // 0 - 9
    0xe9d72e, 0x10fd25, 0x9ace29, 0x556b5, 0x4fd184, 0x16ad6bd, 0x156ae,     0xc5e10, 0x556aa, 0x756a8,
    // Other stuff
    0,0,0,0,0,0,0,
    // A - Z
    0xfa51e0, 0xaad7e0, 0x118c5c0, 0xe8c7e0, 0x15ad7e0, 0x14a53e0, 0x16ac5c0, 0x1f213e0, 0xf8000, 0x1e08440, 0x11513e0, 0x1087e0, 0x1f4111f, 0x1f223e0, 0xe8c62e, 0x8a53e0, 0xd9462e, 0x5d29f, 0x12ad6a9, 0x1087e10, 0xf043e, 0x18304d8, 0x1c1f07c, 0xd909b, 0xf14bd, 0xcd6b3
};

int main()
{
    for(;;)
    {
        int c = getchar();
        c = c < '0' ? 11 : c > 'Z' ? c - ('0' + 'a' - 'A') : c - '0';
        int bit = 0;
        for(int i=0; i<5; i++)
        {
            for(int j=0; j<5; j++)
                putchar(map[c] & (1 << bit++) ? '#' : ' ');
            putchar('\n');
        }
        putchar('\n');
    }
}

I've encoded the characters the following way: I wrote a C "script" that takes a 5x5 area of characters from STDIN, changes "space" to 0 and anything else to 1, rotates the whole area by 90 degrees and finally puts every cell of the area in one bit of a 32-bit integer (the hex numbers in 'map').
That's how the "script" looks like:

#include <stdio.h>

int main()
{
    int array[5][5];
    for(int i=0; i<5; i++)
    {
        for(int j=0; j<5; j++)
            array[j][i] = (getchar() != ' ');
        getchar();
    }
    int res = 0;
    int bit = 0;
    for(int j=0; j<5; j++)
    {
        for(int i=0; i<5; i++)
            res = res | (array[j][4-i] << bit++);
    }
    printf("0x%x\n", res);
    return 0;
}

I am pretty sure there are FAR smaller programs possible (for example in Perl or Ruby), but this is the best I can come up with right know.


Mathematica, 17 bytes
ReIm[(#+#2I)^#3]&

Try it online!
-8 bytes from alephalpha
but........
rules have changed......
so
Mathematica, 5 bytes
Power


Determine if a number is divisible by 13 (without using 13 itself)

Java (score 60.8 59.2)

void t(int n){System.out.print(Math.cos(.483321946706122*n)>.9?"yes":"no");}

Score: (76 - 2 whitespace) chars * 0.8 = 59.2


JavaScript (ES6), 79 bytes

0-indexed.

f=(n,a=[L=1])=>a[n]||f(n-L,[...a.map((v,i)=>k=(x=v)+~~a[i-1-i%2]),L++&1?k:2*x])

Demo

f=(n,a=[L=1])=>a[n]||f(n-L,[...a.map((v,i)=>k=(x=v)+~~a[i-1-i%2]),L++&1?k:2*x])

console.log([...Array(79).keys()].map(n => f(n)).join(', '))

How?

f = (                       // f = recursive function taking:
  n,                        //   n = target index
  a = [L = 1]               //   a[] = current row, L = length of current row
) =>                        //
  a[n] ||                   // if a[n] exists, stop recursion and return it
  f(                        // otherwise, do a recursive call to f() with:
    n - L,                  //   n minus the length of the current row
    [                       //   an array consisting of:
      ...a.map((v, i) =>    //     replace each entry v at position i in a[] with:
        k =                 //       a new entry k defined as:
        (x = v) +           //       v +
        ~~a[i - 1 - i % 2]  //       either the last or penultimate entry
      ),                    //     end of map()
      L++ & 1 ?             //     increment L; if L was odd:
        k                   //       append the last updated entry
      :                     //     else:
        2 * x               //       append twice the last original entry
    ]                       //   end of array update
  )                         // end of recursive call

This algorithm directly generates the sorted rows of Pascal's Triangle. It updates n according to the length of the previous row until a[n] exists. For instance, 6 iterations are required for n = 19:

 L | n  | a[]
---+----+------------------------
 1 | 19 | [ 1 ]
 2 | 18 | [ 1, 1 ]
 3 | 16 | [ 1, 1, 2 ]
 4 | 13 | [ 1, 1, 3, 3 ]
 5 |  9 | [ 1, 1, 4, 4, 6 ]
 6 |  4 | [ 1, 1, 5, 5, 10, 10 ]
                        ^^


Python 3 (62 bytes)

Very straightforward:

from ipaddress import*
lambda i,m:ip_address(i)in ip_network(m)


Ruby, 48 33 Bytes

15 Bytes saved thanks to G B

256.times{|i|puts "%08b"%(i^i/2)}


Vitsy, 10 27 bytes

'rddd++&"rdd8++a[v}v1-D);].

If : was allowed, I could shorten this to 11 bytes. :(

Explanation:

'rddd++&"rdd8++a[v}v1-D);].
'                           Capture all instructions as a string until encountering
                              ' again, looping if necessary.
 r                          Reverse the current stack (output is top-down).
  ddd++                     Push char literal ' to the stack.
       &                    Push a new stack to the stack stack.
        "                   Same as ', but " specific.
         r                  Reverse the current stack.
          dd8++             Push char literal " to the stack.
               a            Push 10 to the stack.
                [        ]  Loop forever.
                 v          Capture the top value as a variable.
                  }         Take the bottom item of the stack and put it on the top.
                   v        Dump the variable to the stack.
                    1-      Subtract 1.
                      D     Duplicate the top item.
                       );   Pop n; if n is 0, exit the loop.
               a[v v1-D);]  This is a makeshift for loop with 10 iterations.
                          . Pop the top stack as n, and the second stack as o.
                              Write a file called "n" with the contents of "o".

The two stacks will be identical at the end. On some Java versions, this may throw a FileNotFoundException due to different implementations of the FileInputStream class.

Previous answer before edit:

&'rddd++}.

Explanation:

&           Push a new stack to the stack stack.
 'rddd++    Modified standard quine.
        }   Move the ' to the right place.
         .  Pop the top stack as n, and the second stack as o. Write a file called
                 "n" with the contents of "o". (Quine name, no content)

Because I might as well, here's a diagram of the steps that occur within the stacks (each stack is represented by []):

Initial state: [[]]

&              [[], []]
                  Push a new stack to the stack stack.

 '             [[], ["r", "d", "d", "d", "+", "+", "}", ".", "&"]]
                  This stack state occurs because ' will loop around the line
                    until finding the next '.

  r            [[], ["&", ".", "}", "+", "+", "d", "d", "d", "r"]]
                  Reverses the top (last) stack.

   ddd         [[], ["&", ".", "}", "+", "+", "d", "d", "d", "r", 13, 13, 13]
                  Push thirteen thrice.

      ++       [[], ["&", ".", "}", "+", "+", "d", "d", "d", "r", "'"]
                  Because char ' is 39 = 13 + 13 + 13.

        }      [[], [".", "}", "+", "+", "d", "d", "d", "r", "'", "&"]]
                  Takes the bottom item, then puts it on the top.

         .     []
                  Writes a file with content from the second-to-top stack and the
                    name as the concatenation of all elements in the top stack,
                    with top member priority (backwards from my representation).

I'm actually not sure how this works right; minute changes cause this to break. For example, placing the & in various other locations should work just as well, but it causes ClassCastExceptions, IOExceptions, and ArrayOutOfBoundsExceptions depending on where you put it. I might need to do some bugfixing.


Jelly, 11 9 bytes

bRI¬P€TḊṖ

Returns a list of bases, which is empty (falsy) if there is none. Try it online!

How it works

bRI¬P€TḊṖ  Main link. Argument: x (number)

 R         Range; yield [1, ..., x].
b          Base; convert x to base n, for each n in the range.
  I        Compute the increment (differences of successive values) of each array
           of base-n digits. This yields only 0's for a repdigit.
   ¬       Apply logical NOT to each increment.
    P€     Compute the product of all lists of increments.
      T    Get the indices of all truthy products.
       Ḋ   Discard the first index (1).
        Ṗ  Discard the last index (x - 1).


QuadR, 1 byte

Thanks to A__ for halving the byte count!

!

Try it online!

Replaces nothing with !


Move the "post your answer" form next to the question on SE sites

JavaScript, 35 34 bytes

$(answers).before($('#post-form'))


Retina, 86 70 65 bytes
T`-'`L
\bnot?\s+(?!not?\b)(\w+?)n?\b
$1n't
\bnot?\b
yesn't
T`L`-'

-16 bytes thanks to @Neil.
-5 bytes thanks to @ovs.
Try it online.
Explanation:
T`-'`L             # Replace all "-" with "A" and all "'" with "B" to store them

\bnot?             # Then replace the word "no" or "not",
 \s+               #  followed by 1 or more whitespaces,
 (?!not?\b)(\w+?)  #  followed by a word/letter that is not "not" or "no"
 n?\b              #  minus a single trailing "n" if there are any
$1                 # with: the word/letter
 n't               #  appended with "n't"

\bnot?\b           # Then replace any remaining loose "no" or "not"
yesn't             # with "yesn't"

T`L`-'             # And finally replace all "A" with "-" and all "B" with "'" again


Ruby 2.0, 133 characters

A collaboration with @Ventero.  Always a good sign when it starts breaking the syntax highlighter!

This is a recursive flood-fill solution.  Reads from STDIN and outputs to STDOUT:

f=->*a{a.product([~n=$_.to_i,-1,1,n+1]){|p,d|a|=[p]if$_[p+=d]<?.}!=a ?f[*a]:a.size}
gets(p).scan(/ /){$*<<f[$`.size]}
p$*.max<f[~/X/]

See it running on Ideone.


MATLAB, 255 210 bytes
This is my first golf, so there are probably improvements to be made.
Thanks to Luis for helping me save 45 bytes :)
function f(n,m)
c=dec2bin(1:6)-48;r=1;p=c(r,:);x=zeros(1,n*m,3);x(:,:,1)=1;while 1
x=circshift(x,[0,1,0]);if rand>0.94;r=randi(6);end
x(1,1,:) = c(r,:);imagesc(permute(reshape(x,n,m,3),[2 1 3]));pause(1/40);end

Explanation:
c=dec2bin(1:6)-48  % c is the colormap
r=1;p=c(r,:);                % p is color number r (starting at 1) from the colormap c
x=zeros(1,n*m,3);x(:,:,1)=1; % 2D matrix in the third dimension. The first layer is 1
while 1                      % while true
x=circshift(x,[0,1,0]);      % shift the vector horizontally along the second dimension
if rand()>0.94;              % 5 percent chance of changing color
k=randperm(6);k=k(k~=r);r=k(1); % Create a vector with color numbers 1..6. Discard the current color, and choose the first color
x(1,1,:) = c(r,:);           % The first light gets color number r
imagesc(permute(reshape(x,n,m,3),[2 1 3]));  % Reshape the vector so that it's a 3D matrix
% Permute it so that the dimensions are correct
% Use imagesc to display
pause(1/40)  % 0.025 seconds pause

Unfortunately, this doesn't save the animation, it just runs it. In order to save it I either need a screen capture program, or rewrite it all using imwrite. Instead, I'll provide two pictures showing different times, for n=15,m=30.


Jelly, 24 bytes
“zẈ€$ụ¤’b6’ị@µỊị⁾+×żCFḊV

Takes a list of 0-indexed ingredients.
Try it online! or see a test suite
How?
Uses a slightly convoluted form of compressing the values as a base-6 number and the fact that the multiplicative entries are the negative ones. Instead of simply shifting up by 3 to get the base-6 digits, the complemented values incremented are used - this saves bytes by allowing the Ị atom to pick out the negative entries prior to the complement step while also saving a byte in the base-250 compression.
“zẈ€$ụ¤’b6’ị@µỊị⁾+×żCFḊV - Main link: 0-based ingredient list  e.g. [6,4,5]
“zẈ€$ụ¤’                 - base 250 compressed number: 120851767994004
        b6               - convert to base 6: [1,1,0,5,0,1,0,3,1,1,4,2,1,0,3,0,1,0,0]
          ’              - decrement: [0,0,-1,4,-1,0,-1,2,0,0,3,1,0,-1,2,-1,0,-1,-1]
           ị@            - index into [reversed @rguments]          [0,4,-1]
             µ           - monadic chain separation (call that x)
              Ị          - insignificant(x)? (abs(x)<=1)            [1,0,1]
                ⁾+×      - ['+','×']
               ị         - index into                               ['+','×','+']
                    C    - complement(x) (1-x)                      [1,-3,2]
                   ż     - zip                                      [['+',1],['×',-3],['+',2]]
                     F   - flatten                                  ['+',1,'×',-3,'+',2]
                      Ḋ  - dequeue                                  [1,'×',-3,'+',2]
                       V - evaluate as Jelly code                   -1


Outsmart the boffins at New Scientist (string rotation)

Python 3, 269 266 bytes

def f(a,m=0,b=[],c=[]):
 a=[k.lower()for k in a]
 while a:
  w,k,u=a[0],[],1
  for i in range(len(w)):
   x=w[i:]+w[:i]
   u,k=x in a and(u,k+[x])or(0,k)
  p=len(k)
  for j in{*k}:a.remove(j)
  if u and len(w)>2:c+=[w]
  if p==m:b+=[w]
  if p>m:m,b=p,[w]
 return b,c

Try it online!
Takes a list of words as input. First convert all words to lowercase, then for each word check all it's rotations and if they are valid, remove them from the list. Outputs two lists containing maximum rotatable words and completely rotatable words respectively.
Needless to say this is not optimal at all and takes several minutes to execute for the provided input.
Output I got for the given dictionary: (['aol', 'alan', 'alar', 'ernst', 'evan', 'hank', 'lesa', 'levi', 'rca', 'terran', 'vera', 'ablest', 'asp', 'ate', 'emit'], ['aol', 'rca', 'asp', 'ate'])
-3 bytes thanks to pxeger


Matlab, 43 bytes

y=hist(+num2str(1:input('')),47:57);y(2:11)

Example:

>> y=hist(+num2str(1:input('')),47:57);y(2:11)
10
ans =
     1     2     1     1     1     1     1     1     1     1

How it works:

1:input('') generates a vector of numbers from 1 to the input number.

num2str converts all those numbers to a space-separated string (char array).

The + converts from char to ASCII codes. Digits are 48 to 57 in ASCII.

hist counts how many times each of those ASCII codes appears. Actually the count for value 47 is necessary too, because hist collects all lower values in the first bin. So that 47 just intercepts all spaces and prevents them from being confused as zeroes.

Lastly, y(2:11) removes that first count and prints the result.


Python, 284 characters

def M(A,R):
 X,Y=range(len(A[0])),range(len(A))
 G,P,H=[set(x+1j*y for x in X for y in Y if A[y][x]>=z) for z in(0,1,2)]
 P-=H
 for i in' '*R:P|=G&reduce(lambda x,y:x|y,[set(p+d for p in P)-(H&set(p+d for p in H))for d in(1,1j,-1,-1j)])
 return[[x+1j*y in P-H for x in X]for y in Y]

def display(A):print'\n'.join(''.join('_+'[c]for c in r)for r in A)

A=[[0,0,0,0,0,0,0,0],
   [0,0,0,0,0,2,0,0],
   [0,0,0,1,0,0,2,0],
   [2,0,0,2,0,0,0,0],
   [0,0,0,0,0,0,0,0]]
display(M(A,2))

A=[[0,0,0,0,0,0,0,0,0,0],
   [0,0,0,0,0,0,0,0,0,0],
   [0,0,0,0,0,0,2,0,0,0],
   [0,0,2,0,1,2,2,0,0,0],
   [0,0,0,0,0,0,0,0,0,0],
   [0,0,0,0,2,0,0,0,0,0],
   [0,0,0,0,0,0,0,0,0,0]]
display(M(A,4))

The main M routine takes the 2D array containing the map and the range, and returns the 2D array of booleans.
G is the set of all indexes of (in-bounds) squares, encoded as complex numbers.  H is the same but for the obstacles, and P is the same for the player.  The main loop updates P by moving P in each of the 4 cardinal directions, filtered by the obstacles and the bounds of the array.


52 characters

}static Program(){System.Console.Write(0<1);for(;;);

so the whole thing becomes:

class Program
{
    static void Main()
    {
        System.Console.Write( "False" );
    }
    static Program()
    {
        System.Console.Write( 0 < 1 );
        for ( ; ; ) ;
    }
}


Pascal's Triangle as a 2-dimensional list

Mathematica, 70 68 bytes
NestList[ListConvolve[{1,0,1},#,2]&,Join[#,{1},#],#2]&[0~Table~#,#]&

Similar to the MATL solution.


Catenary Between Two Points (Hanging Chain)

Python + NumPy + Matplotlib, 1131

Just to get us started, here's an attempt that uses no knowledge of calculus or physics other than the fact that the catenary minimizes the energy of a chain. Hey, my algorithm may not be efficient, but at least it's not implemented efficiently either!

import math
import random
import numpy as np
import matplotlib.pyplot as plt
length, x0, y0, x1, y1 = input(), input(), input(), input(), input()
chain = np.array([[x0] + [length / 1000.]*1000, [y0] + [0.] * 1000])
def rotate(angle, x, y):
 return x * math.cos(angle) + y * math.sin(angle), -x * math.sin(angle) + y  * math.cos(angle)
def eval(chain, x1, y1):
 mysum = chain.cumsum(1)
 springpotential = 1000 * ((mysum[0][-1] - x1) ** 2 + (mysum[1][-1] - y1)  ** 2)
 potential = mysum.cumsum(1)[1][-1]
 return springpotential + potential
def jiggle(chain, x1, y1):
 for _ in xrange(100000):
  pre = eval(chain, x1, y1)
  angle = random.random() * 2 * math.pi
  index = random.randint(1,1000)
  chain[0][index], chain[1][index] = rotate(angle, chain[0][index], chain[1][index])
  if( pre < eval(chain, x1, y1)):
   chain[0][index], chain[1][index] = rotate(-angle, chain[0][index], chain[1][index])
jiggle(chain, x1, y1)
sum = chain.cumsum(1)
x1 = 2 * x1 - sum[0][-1]
y1 = 2 * y1 - sum[1][-1]
jiggle(chain, x1, y1)
sum = chain.cumsum(1)
plt.plot(sum[0][1:], sum[1][1:])
plt.show()


Scratch, 145 bytes

-2 thanks to boboquack
-??? because writing it in Oto is shorter than English

(Because Scratch is the standard scratch.)

Here's a sample run:

.


Print your code backwards - reverse quine

huh?, 5 characters

!hcuO

I actually have NO idea how it works, but If you download the interpreter, and if you write !hcuO, then you get Ouch!

To run this, you need to execute the program like this:

huh.exe !hcuO

It will actually look for a file called !hcuO, but it doesn't exist, so it outputs Ouch!


Golfscript, 44 43 40 41 38 37 36 chars

Since the criterion now requires golfing, here's the golfed version:

!:^;n).+{[^\{^$^$={;\)}^if\}*].n@}*;

The original, ungolfed, version actually dealt with strings rather than abusing Golfscript's formatting conventions for dumping the stack to stdout at program termination:

# Assumes nothing passed to stdin, so input length is zero
,):$''+
{
    .puts
    # Convert to an array of [count char count char ...]
    [$\{.@.@={;\)\}{\$\}if}*]
    # Convert to an array of [[count char] [count char] ...]
    $)/
    # Form the next string
    ''\{(@\+\+}/
}
# Nineteen times. There are a *lot* of ways of generating the number nineteen
# but I like this one
$).?.)*(*


Use an empty variable instead of ""

Uninitialized variables are set to a special value: empty.  When empty is cast to a string it becomes "".

Contrived example (using z instead of ""):

s=InputBox(z)
For i=1To 5
    For j=1To i
        r=r&s
    Next
    MsgBox r
    r=z
Next

For numeric types Empty is 0, and for booleans it is false.  This can cut down on initialization code.

a=inputbox("Enter Starting Value")
b=a
while done=0
    i=i+1
    b=b*2
    done=(b>10000 or i>10)
wend
msgbox "Your "&a&" rabbit(s) have turned into "&b&" rabbit(s) in "&i&" years."


Ruby, 74 bytes

->n{(1..n).map{|x|a=(n^x*x).to_s 2;a.size>Math.log2(n)?n:a.count(?1)}.min}

Try it online!

This simply generates the sequence \$\left[1^2, 2^2, \ldots, n^2\right]\$ (which is far more than enough), XORs it with \$n\$, and then takes either the number of 1s in its binary representation if the number of bits is less than or equal to \$\log_2n\$, or \$n\$ otherwise. It then takes the minimum number of bits flipped. Returning \$n\$ instead of the number of bits flipped when the highest bit flipped is greater than \$\log_2n\$ prevents these cases from being chosen as the minimum, as \$n\$ will always be greater than the number of bits it has.

Thanks to Piccolo for saving a byte.