Write a line in program that looks useless

C

int main(int argc, char **argv) {
    switch(argc) {
        case 2:
            ;
            int allowed = 0;
        case 3:
            argc--;
            break;
        default:
            argc = 3;
    }
    return 0;
}

Won't compile if we remove the single ;.

EDIT:

Solution below:

   This happens because a case statement is just a label, and, as such, must be followed by a statement (which the standard refers to as a "specifier for actions to be performed", which rules out declarations). To prevent this, we prefix the declaration with a ;, a null statement. Specifications for the case label can be found here at page 142 (131 in-document)


Haskell, 66 62 60 bytes

f n=[n|n>1]:[k:l:m|k<-[2..n],l:m<-f$div n k,mod(gcd n l)k<1]

Try it online!


Brachylog (v2), 10 bytes

{{s\s\}ᵈ}ᶜ

Try it online!

I like how clear and straightforward this program is in Brachylog; unfortunately, it's not that short byte-wise because the metapredicate syntax takes up three bytes and has to be used twice in this program.

Explanation

{{s\s\}ᵈ}ᶜ
  s         Contiguous subset of rows
   \s\      Contiguous subset of columns (i.e. transpose, subset rows, transpose)
 {    }ᵈ    The operation above transforms the first input to the second input
{       }ᶜ  Count the number of ways in which this is possible


Charcoal, 92 79 bytes

Ａ¹θＷＳ⊞υ⪫__ιＷυ«Ａ⌈ＥυＬκεＡ⁺θθδＦυ«Ｐ×_εＰκＭδ↓»ＡＥ✂υ¹Ｌυ²⎇‽²κ§υ⁺λλυＭε→Ｆυ«Ｍδ↑↗θ←↖θ→»Ｍθ↘Ａδθ

Try it online! Link is to verbose version of code. Needs a blank line to mark the end of the input. Explanation:

Ａ¹θ

Initialise the variable q. This holds the size of the zig-zags i.e. half the gap between rows.

ＷＳ⊞υ⪫__ι

Read nonblank input lines into the array u. The lines are automatically surrounded by _s as they are read in, although they are not padded yet.

Ｗυ«

Loop while there are still strings left.

Ａ⌈ＥυＬκε

Calculate the width of the largest string in e.

Ａ⁺θθδ

Calculate the gap between rows in d.

Ｆυ«Ｐ×_εＰκＭδ↓»

For each team, print the padding, print the team, and then move down to the next team.

ＡＥ✂υ¹Ｌυ²⎇‽²κ§υ⁺λλυ

For every other team, randomly pick between that team or the previous team. (Note that if there is only one team left then this produces an empty list.)

Ｍε→Ｆυ«Ｍδ↑↗θ←↖θ→»Ｍθ↘

If there are still teams left, draw the zigzags joining them in pairs.

Ａδθ

Double the length of the zigzags each time.


C# (Visual C# Interactive Compiler), 231+21=252 bytes

s=>Color.FromArgb(Convert.ToInt32(s,16));f=s=>Enum.GetNames(typeof(KnownColor)).Select(x=>Color.FromName(x)).Where(x=>!x.IsSystemColor&x.A>254).OrderBy(x=>Math.Abs(x.R-C(s).R)+Math.Abs(x.G-C(s).G)+Math.Abs(x.B-C(s).B)).First().Name

Explanation:

using System.Drawing; //System library that handles Colors in C#

C=s=>Color.FromArgb(Convert.ToInt32(s,16));        //helper method. receives a hex string and returns it's Color

f=s=>Enum.GetNames(typeof(KnownColor))             //collection of color names from the System.Drawing.KnownColor enum
         .Select(x=>Color.FromName(x))             //convert the color names to Colors
             .Where(x=>!x.IsSystemColor&x.A>254)   //filter out unwanted colors
                 .OrderBy(x=>Math.Abs(x.R-C(s).R)  //order by increasing distance
                            +Math.Abs(x.G-C(s).G)
                            +Math.Abs(x.B-C(s).B))
                     .First().Name                 //return the closest color's name

For some reason, Tio complains that the namespace 'Drawing' does not exist in the namespace 'System', despite the source project Mono stating it's compatible. It works fine in VisualStudio though.

EDIT: apparently it hasn't been implemented into Tio yet!

Try it online!


Determine which value represents which direction in a path

C#

EDIT: Fixed a division and formatting. And added the helper class.

This is the golfed code, 807 chars

class M{public int c,x,y,u;}
void G(string[] z){
M K;int[]x={0,0,-1,1},y={-1,1,0,0},I={0,0,0,0};
string[]T={"Up","Down","Left","Right"};
int X,Y,R,n=0,H=z.Length,W=z[0].Length;W-=W/2;var D= string.Join(" ", z).Where(c=>c!=' ').Select(c=>new M(){c=c,x=n%W,y=n++/W}).ToList();n=0;var S=D.GroupBy(k=>k.c).ToDictionary(k=>k.Key,k =>n++);
for(;I[0]<4;I[0]++)for(I[1]=0;I[1]<4;I[1]++)for(I[2]=0;I[2]<4;I[2]++)for(I[3]=0;I[3]<4;I[3]++){
if ((1<<I[0]|1<<I[1]|1<<I[2]|1<<I[3])!=15)continue;
foreach (var Q in D){D.ForEach(p=>p.u=-1);R=1;K=Q;j:if((X=K.x+x[n=I[S[K.c]]])>=0&&X<W&&(Y=K.y+y[n])>=0&&Y<H&&(K=D[X+Y*W]).u<0){
K.u=1;if(++R==D.Count){Console.WriteLine("{4} Start({0}:{1}) End({2}:{3})",Q.x,Q.y,K.x,K.y,string.Join(", ",S.Select(k=>string.Format("{1}: '{0}'",(char)k.Key,T[I[k.Value]])).ToArray()));return;}goto j;}}}
}

Results for the three test cases:

  Down: '1', Right: '2', Up: '3', Left: '4' Start(0:0) End(5:2)
  Up: '@', Left: '.', Down: 'e', Right: 'H' Start(1:1) End(0:0)
  Right: 'X', Down: 'V', Up: 'I', Left: 'C' Start(0:2) End(2:4)

This is the raw code without "golf", almost 4,000 characters:

class Program
{
    static string[] input1 =  { "1 2 2 2 2 1",
               "1 3 4 4 1 4",
               "2 3 1 3 4 2",
               "1 4 4 2 1 3",
               "2 2 2 3 2 3"};

    static string[] input2 =  { "@ . .",
                                "e . @",
                                "H H @",
               };

    static string[] input3 =  { "0 0 1",
                                "0 0 1",
                                "3 2 2",
               };

    static void Main(string[] args)
    {
        Resolve(input1);
        Resolve(input2);
        Resolve(input3);
        Console.ReadLine();
    }

    class N { public int c; public int x, y, i, u; }

    static void Resolve(string[] input)
    {
        int[] ox = { -1, 1, 0, 0 }, oy = { 0, 0, -1, 1 }, I = { 0, 0, 0, 0 };
        string[] TXT = { "Left", "Right", "Up", "Down" };
        int X, Y, R, n = 0, H = input.Length, W = input[0].Length;
        W -= W / 2;
        N K = null;
        var data = string.Join(" ", input).Where(c => c != ' ').Select(c => new N() { c = c, x = (n % W), y = (n / W), i = n++, u = -1 }).ToList();
        n = 0;
       var S = data.GroupBy(k => k.c).ToDictionary(k => k.Key, k => n++);

        for (; I[0] < 4; I[0]++)
            for (I[1] = 0; I[1] < 4; I[1]++)
                for (I[2] = 0; I[2] < 4; I[2]++)
                    for (I[3] = 0; I[3] < 4; I[3]++)
                    {
                        if (((1 << I[0]) | (1 << I[1]) | (1 << I[2]) | (1 << I[3])) != 15) continue;
                        foreach(var Q in data)
                        {
                            data.ForEach(p => p.u = -1);
                            R = 0;
                            K = Q;
                            while (K != null)
                            {
                                n = I[S[K.c]];
                                X = K.x + ox[n];
                                Y = K.y + oy[n];
                                if (X >= 0 && X < W && Y >= 0 && Y < H)
                                {
                                    n = X + Y * W;
                                    if (data[n].u < 0)
                                    {
                                         data[n].u = K.i;
                                         K = data[n];
                                        R++;
                                        if (R == data.Count - 1)
                                        {
                                            Console.WriteLine();
                                            Console.WriteLine("Start({0}:{1}) End({2}:{3})", Q.x, Q.y, K.x, K.y);
                                            Console.WriteLine(string.Join(", ", S.Select(k => string.Format("'{0}': {1}", (char)k.Key, TXT[I[k.Value]])).ToArray()));
                                            Action<N> Write = null;
                                            Write = (k) =>
                                             {
                                                 if (k.u != -1)
                                                 {
                                                     Write(data[k.u]);
                                                 }
                                                 Console.Write(string.Format("({0}:{1}){2}", k.x, k.y, k == K ? "\n" : " => "));
                                             };

                                            Write(K);
                                            return;
                                        }
                                        continue;
                                    }
                                }
                                K = null;
                            }
                        }
                    }
        Console.WriteLine("Solution not found");
    }
 }
}

These are the results for the three examples:

  Solution not found

  Start(1:1) End(0:0) '@': Up, '.': Left, 'e': Down, 'H': Right

  (1:1) => (0:1) => (0:2) => (1:2) => (2:2) => (2:1) => (2:0) => (1:0) => (0:0)

  Start(0:0) End(1:1) '0': Right, '1': Down, '3': Up, '2': Left

  (0:0) => (1:0) => (2:0) => (2:1) => (2:2) => (1:2) => (0:2) => (0:1) => (1:1)


R, 48 47 bytes

cat(x<-sample(9,2,T),y<-x%*%c(10,1),y^2,fill=1)

Try it online!

Thanks to J.Doe for golfing down a byte.


Pyth, 27 bytes

jsCM.u:R"v "" v"N+R\-.t*L\v

Try it online!


Pyth, 22
mj\.jd256}FmivMcd\.256

Try it online.
               cd\.       # split string by "."
             vM           # eval list (convert strings to integers)
            i      256    # convert list of base256 digits to integer
           m          Q   # map the above over implicit input list
         }F               # inclusive range
    jd256                 # convert to list of base256 digits
 j\.                      # join by "."
m                         # map over inclusive range


Python - 48 characters

exec("".join(map(chr,map(len,'                                                                                '.split("    ")))))

Abusing the whitespace rule.

First I converted every character in CesiumLifeJacket's answer to its ASCII value (I could have written my own but I am lazy, and it wouldn't have affected the final score anyway). The long string in my solution is one space for each one of those ASCII values, and tabs separating them. Split at tabs, find the lengths, convert back to characters and execute.

SE converts tabs to 4 spaces each, so copypasting won't work. You'll just have to believe me :)


Ruby -p, 48 47 bytes

$_=$_[l= ~/$//2,l]+$_[0,l];gsub /(.)(.)/,'\2\1'

Try it online!
Operation 1 is handled by splitting $_ (the predefined global variable that contains the input) into two substrings of equal length; ~/$/ gives the length of the input. Then gsub /(.)(.)/,'\2\1' completes Operation 2 by swapping each pair of characters. (With the -p flag, gsub without a receiver implicitly acts on $_.)


username = 'toString', password = {}.toString

Try it online!
Note: Due to a certain username pointed out by Wezl in the comments, this answer is not valid for the current challenge.
Why this works:

 Among other properties, Object.prototype.toString is inherited from Object.prototype, even if it wasn't a part of the object literal given to the validator. Since any object inherits the same function {}.toString is the same as the toString of the credentials object.


Octave - 59 chars

pkg load image;imwrite(imcrop(imread(input(''))),input(''))

MATLAB - 44 chars (not free, out of the contest)

imwrite(imcrop(imread(input(''))),input(''))

MATLAB seemed spot-on for this. Requires the Image Processing Toolbox (or package image 2.0.0 from Octave Forge). Usage:

Write at prompt 'input-filename' (single quotes included)
MATLAB: Drag from top-left to bottom-right corner and double click the rectangle.
Octave: Click top-left and bottom-right corner
Write 'output-filename' (between single quotes too)


This is a fun problem, and I'm sad that it has no solution, so I made my own!

Requires arguments in the form M P where M is the size of the board and P is the code for the piece

Java - S.java - 1359 Characters

public class S{int s;String p;String e=".";String b;String t;int c;public static void main(String[]args){new S(args);}S(String[] a){s=Integer.parseInt(a[0]);p=a[1];b="";int i;if(p.equals("P")){String r="P";for(i=1;i<s;i++)r+=e;r+="\n";for(i=0;i<s;i+=3){a(r);f(p);a(r);}m(0);}if(p.equals("B")){for(i=0;i<s-1;i++){if(s/2==i)f(p);f(e);}}if(p.equals("N")){for(i=0;i<s;i+=5){f(e);f(e);f("N");f(e);f(e);}m(0);if(s%5==2|s%5==1){m(1);f(p);}}if(p.equals("R")){f(p);for(i=1;i<s;i++)f(e);}if(p.equals("K")){String k="";for(i=0;i<s;i+=3)k+=".K.";k=k.substring(0,s-1);k+=(s%3==0)?e:"K";k+="\n";for(i=0;i<s;i+=3){f(e);a(k);f(e);}m(1);if(s%3==0)f(e);else a(k);}if(p.equals("Q"))for(i=0;i<s*s;i++){try{q(i,0,new String[s][s]);}catch(Exception e){}b=t;}System.out.println(b);}void q(int d,int g,String[][] o) throws Exception{int u=0;int i;if(g==s*s|u>c){if(u<=c){c=u;t="";for(i=0;i<s;i++){for(int j=0;j<s;j++)t+=o[i][j];t+="\n";}}throw new Exception();}int r=(d/s)%s;int c=d%s;if(o[c][r]==null){for(i=0;i<s;i++){try{o[c-r+i][i]=(o[c-r+i][i]==null)?e:o[c-r+i][i];}catch(Exception e){}try{o[i][r+c-i]=(o[i][r+c-i]==null)?e:o[i][r+c-i];}catch(Exception e){}o[i][r]=(o[i][r]==null)?e:o[i][r];o[c][i]=(o[c][i]==null)?e:o[c][i];}o[c][r]="Q";u++;}q(d+1,g+1,o);}void m(int d){b=b.substring(0,(s+1)*(s-d));}void a(String d){b+=d;}void f(String f){for(int i=0;i<s;i++){b+=f;}b+="\n";}}

(Pawns are attacking from left to right)

I couldn't find any proof of the minimum of any domination problem, but my Queen's solver at 8 solves with 5 queens and the others don't seem to be doing too badly (18 queens at 25x25). Someone will have to beat my other solutions to disprove them as minimums. That probably won't be hard!

Here is my de-golfed solution, for anyone interested. It's a bit of a mess... My first thought for doing the Queen's solver was to use backtracking, but I got lazy.

Java - SimpleChessSolver.java - 3496 Characters
(There was once a version which had a whole bunch of different classes, to represent the board, squares, pieces... But it quickly got out of control and was renamed ComplicatedChessSolver.java)

public class SimpleChessSolver {
int size;
String piece;
String period = ".";
String board;
String bestBoard;
int bestCount;

    public static void main(String[] args) {
        new SimpleChessSolver(args);
    }

    SimpleChessSolver(String[] args){
        size = Integer.parseInt(args[0]);
        piece = args[1];
        board = "";
        int index;
        if (piece.equals("P")){
            String periods = "P";
            for (index = 1; index < size; index++){
                periods += period;
            }
            periods += "\n";
            for (index = 0; index < size; index += 3){
                addString(periods);
                fillRow(piece);
                addString(periods);
            }
            trimToSize(0);
        }
        if (piece.equals("B")){
            for (index = 0; index < size - 1; index++){
                if (size/2 == index){
                    fillRow(piece);
                }
                fillRow(period);
            }
        }
        if (piece.equals("N")){
            for (index = 0; index < size; index += 5){
                fillRow(period);
                fillRow(period);
                fillRow("N");
                fillRow(period);
                fillRow(period);
            }
            trimToSize(0);
            if (size%5 == 2 || size%5 == 1){
                trimToSize(1);
                fillRow(piece);
            }
        }
        if (piece.equals("R")){
            fillRow(piece);
            for (index = 1; index < size; index++){
                fillRow(period);
            }
        }
        if (piece.equals("K")){
            String kings = "";
            for (index = 0; index < size; index += 3){
                kings += ".K.";
            }
            kings = kings.substring(0, size - 1);
            kings += (size%3 == 0) ? period : "K";
            kings += "\n";
            for (index = 0; index < size; index += 3){
                fillRow(period);
                addString(kings);
                fillRow(period);
            }
            trimToSize(1);
            if (size%3 == 0) {
                fillRow(period);
            }
            else {
                addString(kings);
            }
        }
        if (piece.equals("Q")){
            for (index = 0; index < size*size; index++){
                System.out.println(bestBoard);
                System.out.println("BlankLine\n");
                try {
                    queenSolve(index, 0, new String[size][size]);
                }
                catch (Exception e) {}
            }
            System.out.println("Final Answer");
            board = bestBoard;
        }

        System.out.println(board);
    }

    void queenSolve(int start, int depth, String[][] board2D) throws Exception {
        int currentCount = 0;
        int index;
        if (depth == size*size || currentCount > bestCount){
            if (currentCount <= bestCount){
                bestCount = currentCount;
                bestBoard = "";
                for (index = 0; index < size; index++){
                    for (int jdex = 0; jdex < size; jdex++){
                        bestBoard += board2D[index][jdex];
                    }
                    bestBoard += "\n";
                }
            }
            throw new Exception();
        }
        int row = (start / size) % size;
        int col = start % size;
        if (board2D[col][row] == null){
            for (index = 0; index < size; index++){
                try{
                    board2D[col - row + index][index] = (board2D[col - row + index][index] == null) ? period : board2D[col - row + index][index];
                } catch (ArrayIndexOutOfBoundsException e) {}
                try{
                    board2D[index][row + col - index] = (board2D[index][row + col - index] == null) ? period : board2D[index][row + col - index];
                } catch (ArrayIndexOutOfBoundsException e) {}
                board2D[index][row] = (board2D[index][row] == null) ? period : board2D[index][row];
                board2D[col][index] = (board2D[col][index] == null) ? period : board2D[col][index];
            }
            board2D[col][row] = "Q";
            currentCount++;
        }
        queenSolve(start + 1, depth + 1, board2D);
    }

    void trimToSize(int additionalTrim){
        board = board.substring(0, (size + 1) * (size - additionalTrim));
    }

    void addString(String toAdd){
        board += toAdd;
    }

    void fillRow(String filler){
        for (int index = 0; index < size; index++){
            board += filler;
        }
        board += "\n";
    }

}

How it works
Other than the queens, the other solutions are very simple. The Knights, Rooks, and Bishops can all be solved by putting a straight line in the correct place. Rooks cover their whole rank, so it works to just put a line anywhere on the board. A row of knights will cover four parallel rows, two in each direction. If there is a row of bishops on approximately (+/- 0.5) the middle row, they can cover every square. A row of pawns covers the parallel rows to their immediate left and right except for the bottom square, so I put a pawn on that square to occupy it. Kings can only cover the 3x3 squares around them, so I just stick Kings such that their squares don't overlap, with overlapping kings added if I need to fill out a size%3 != 0 board.

Queens is a little trickier. My algorithm, which may not be the best, iterates over the board, so that it starts on every square, then puts a queen there. It fills in periods for every square that queen covers, then walks along the board until it finds a square not already occupied by a Q or a period. As I said, this produces the current minimum for a 8x8 board (5 Queens) and I couldn't find a reference for any other board size.


How long is my number: Restricted Version

Mathematica, 13 bytes

IntegerLength

Well...


Python 2, 95 bytes

l=[];n=input()
exec"a=min(set(range(n))-{2*b-c for b,c in zip(l,l[1::2])});print-~a;l=[a]+l;"*n

The main trick is in generating the numbers the new value must avoid. Keeping the reversed sequence so far in l, let's look at what elements might form a three-term arithmetic progression with the value we're about to add.
? 4 2 2 1 1 2 1 1   a b c
^ ^ ^               ? 4 2
^   ^   ^           ? 2 1
^     ^     ^       ? 2 2
^       ^       ^   ? 1 1

The other numbers are the paired members of l and every second element of l, so zip(l,l[1::2]). If this pair is (b,c) then the arithmetic progression (a,b,c) happens for a=2*b-c. After generating the set of a's to avoid, the code takes the minimum of the complement, prints it, and prepends it to the list. (Actually, the computation is done with numbers decreased by 1, and printed 1 higher, to let range(n) serve as a universe of candidates.)


Pyth, 13 bytes

:#%*"[%s]"5Q0c"ABOUTAFTERAGAINBELOWCOULDEVERYFIRSTFOUNDGREATHOUSELARGELEARNNEVEROTHERPLACEPLANTPOINTRIGHTSMALLSOUNDSPELLSTILLSTUDYTHEIRTHERETHESETHINGTHINKTHREEWATERWHEREWHICHWORLDWOULDWRITE"5

Test suite.

 #             filter possible words on
:           0  regex match, with pattern
  %        Q   format input as
    "[%s]"     surround each group of letters with brackets (regex char class)
   *      5    repeat format string 5 times for 5 groups of letters


Ruby, 228 bytes * 21895 =4992060

->n{a=(0..n*2).map{$b=' '*n}
g=0
m=n*2
(n**0.5).to_i.downto(1){|i|n%i<1&&(m=[m,n+h=n/i].min
g+=h+1
g<m+2?(a[g-h-1,1]=(1..h).map{?**i+$b}):(x=(m-h..m).map{|j|r=a[j].rindex(?*);r ?r:0}.max
(m-h+1..m).each{|j|a[j][x+2]=?**i}))}
a}

Several changes from ungolfed code. Biggest one is change of meaning of variable m from the height of the squarest rectangle, to the height of the squarest rectangle plus n.

Trivially, *40 has been changed to *n which means a lot of unnecessary whitespace at the right for large n; and -2 is changed to 0 which means rectangles plotted across the bottom always miss the first two columns (this results in poorer packing for numbers whose only factorization is (n/2)*2)

Explanation

I finally found time to get back to this.

For a given n the smallest field must have enough space for both the longest rectangle 1*n and the squarest rectangle x*y. It should be apparent that the best layout can be achieved if both rectangles have their long sides oriented in the same direction.

Ignoring the requirement for whitespace between the rectangles, we find that the total area is either (n+y)*x = (n+n/x)*x or n*(x+1). Either way, this evaluates to n*x + n. Including the whitespace, we have to include an extra x if we place the rectangles end to end, or n if we place the rectangles side by side. The former is therefore preferable.

This gives the following lowerbounds (n+y+1)*x for the field area:

n     area
60    71*6=426
111  149*3=447
230  254*10=2540
400  421*20=8240
480  505*20=10100

This suggests the following algorithm:

Find the value (n+y+1) which shall be the field height
Iterate from the squarest rectangle to the longest one
  While there is space in the field height, draw each rectangle, one below the other, lined up on the left border.
  When there is no more space in the field height, draw the remaining rectangles, one beside the other, along the bottom border, taking care not to overlap any of the rectangles above.
  (Expand the field rightwards in the rare cases where this is necessary.)

It is actually possible to get all the rectangles for the required test cases within the above mentioned lower bounds, with the exception of 60, which gives the following 71*8=568 output. This can be improved slightly to 60*9=540 by moving the two thinnest rectangles right one square and then up, but the saving is minimal, so it's probably not worth any extra code.

10
12
15
20
30
60
******
******
******
******
******
******
******
******
******
******

*****  *
*****  *
*****  *
*****  *
*****  *
*****  *
*****  *
*****  *
*****  *
*****  *
*****  *
*****  *
       *
****   *
****   *
****   *
****   *
****   *
****   *
****   *
****   *
****   *
****   *
****   *
****   *
****   *
****   *
****   *
       *
***    *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
*** ** *
    ** *
    ** *
    ** *
    ** *
    ** *
    ** *
    ** *
    ** *
    ** *
    ** *
    ** *

This gives a total area of 21895.

Ungolfed code

f=->n{
  a=(0..n*2).map{' '*40}                                      #Fill an array with strings of 40 spaces
  g=0                                                         #Total height of all rectangles
  m=n                                                         #Height of squarest rectangle (first guess is n)
  (n**0.5).to_i.downto(1){|i|n%i<1&&(puts n/i                 #iterate through widths. Valid ones have n%i=0. Puts outputs heights for debugging.
    m=[m,h=n/i].min                                           #Calculate height of rectangle. On first calculation, m will be set to height of squarest rectangle.
    g+=h+1                                                    #Increment g
    g<n+m+2?                                                  #if the rectangle will fit beneath the last one, against the left margin
      (a[g-h-1,1]=(1..h).map{'*'*i+' '*40})                      #fill the region of the array with stars
    :                                                         #else
      (x=(n+m-h..n+m).map{|j|r=a[j].rindex('* ');r ?r:-2}.max    #find the first clear column
      (n+m-h+1..n+m).each{|j|a[j][x+2]='*'*i}                    #and plot the rectangle along the bottom margin
    )
  )}
a}                                                            #return the array

puts f[gets.to_i]


Java

Wow, this is a complicated problem. I've never done a square root before. I've taken square roots, but I haven't done one. Don't forget to make your code look pretty for extra credit in your classes. Here's the code that makes a square root of a number inputted:

       import java
       .awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;
       import javax
       .swing.JPanel;

public class SquareRoot {

    public static void main(String[] args) {
        java.util.Scanner scan = new java.util.Scanner(java.lang.System.in);
        System.out.print("Please input a number to take the square root of: ");
        int num = scan.nextInt();
        System.out.print("The answer is: ");
        System.out.print(sqrt(num));
    }

    static int sqrt(int n){int
    m = n ;while (n==n){m++;if
    (m * m
    > n&&m    <n        &&
    m>0 ){
    return     0+      0+
    m-1;}}       ;;  ;;
    return        0+0+
 n  == 0 ?       1+  1-
  m --:--m     +0     -0
   ;}//sqr

            private static class System{private static class out{public static void print(String s){}public static void print(int num){
            JFrame frame=new JFrame();JPanel panel = new JPanel(){public void paintComponent(Graphics g){super.paintComponent(g);;;;;g.
            setColor(new Color(0x964B00));g.fillRect(0,500,3000,3000);g.setColor(new Color(0xCC7722));g.fillRect(700,505,75,75);;;;;;g.
            fillRect
            (720,450,
            36,50);g.
            drawLine
            (700,581,
             690,600);
            g.drawLine
            (685,600,
            665,615);
            g.drawLine
            (685,600,
            695,610);
            g.drawLine
            (780,581,
             795,600);
            g.drawLine
            (790,600,
            775,615);
            g.drawLine
            (790,600,
            810,610);
            g.setColor
            (Color.
            GREEN);g.
            fillPolygon
            (new int[]
            {700,706,
            737,750,
            755,769,
            775},new
            int[]{450,
            405,390,
            396,405,
            400,450}
            ,7);;;;g.
            drawString
            (""+num,
            725,542);
}};         frame.add
(panel      );;//;;/
 ;;;        ;;;frame.
   setAlwaysOnTop
   (true);  frame.
   setDefaultCloseOperation
    (JFrame.DO_NOTHING_ON_CLOSE);
       frame.setVisible(true)
         ;;;;;;;;;}}}}

Trolls:

Obviously, the code is obfuscated.

Do I get bonus points for the art in the code?

The System.out.prints don't print to java.lang.System.out.print. They print to an inner class. The first two (which are supposed to print strings) don't do anything; the second one:
Outputs to a window. Sample output - do you see the square root (input is 100)?:
The window does nothing on close. Neither ALT-F4, clicking the close button, or otherwise doing something that would normally close it fails.
The window is always on top of other windows. Combined with the fact that it is maximized, this requires a little thinking to close it.
finds the sqrt by integer ADDITION from the number until we reach the correct number. This takes a long time since we wait for integer wrap-around. Because of this, it actually takes less time for larger numbers. For the sample output, it took 20 seconds.
Doesn't work properly for when the input is 0. Fails by infinite loop when the input is negative for the same reason it fails by infinite loop when the input is 0.
I trolled myself and spent ~2 hours coding this and aligning it.


Python 2.7.6, 1244 1308 1265 1253 1073 1072 1071 1065 1064 1063 bytes
Alright, I'm not breaking any records here but this is about the smallest Python will go insofar as reading input all at once from a file rather than sequentially over time. I'll try to one-up this later in a different language (and an interpreter, not just a parser). Until then, enjoy the disgustingly horrid monstrosity.
Note: opens a file called t in the working directory. To make it open a command line argument, add import sys to the top of the file and change 't' to sys.argv[1]

n=s='\n';m=',';X='[';Y=']';c=';';A='~ATH';D='import';b,g,k=[],[],[];r=range;l=len;f=open('t','r').read().split(n)
def d(j,u):
 p=[]
 for e in j:
  if e!=u:p.append(e)
 return''.join(p)
for h in r(l(f)):f[h]=f[h].split('//')[0].split()
while[]in f:f.remove([])
for h in r(l(f)):
 i=f[h]
 if i[0]==D and l(i)==2and i[1][l(i[1])-1]==c and d(i[1],c)not in b:g.append(0);b.append(d(i[1],c))
 elif i[0].startswith(A):
  i=i[0].split('){')
  for e in r(l(i)):
   if i[e].startswith(A):
    i[e]=i[e].split('(')
    if i[0][1]in b:g[b.index(i[0][1])]+=(i[1].count('+')-i[1].count('-'))
 elif i[0].startswith('bifurcate')and l(i)==2and i[1][l(i[1])-1]==c:
  i=i[1].split(X)
  if i[0] in b:
   z=d(d(i[1],c),Y).split(m)
   for e in r(l(z)):g.append(g[b.index(i[0])]);b.append(z[e])
   g.remove(g[b.index(i[0])]);b.remove(i[0])
 elif i[0].startswith(X)and i[0].endswith('.DIE();')and l(i)==1:
  z=d(i[0],X).split(Y)[0].split(m)
  for e in r(l(z)):
   k.append((z[e],g[b.index(z[e])]))
for e in r(l(k)):k0=k[e][0];k1=k[e][1];s+=k0+'='+str(k1)+n+('DIE '+k0+n)*abs(k1)
print s


Python 3

import numpy
from scipy.ndimage import measurements

def crosswords(arr):
    M=numpy.asarray(arr)
    # check connectivity
    if measurements.label(numpy.where(M!='',1,0))[-1] != 1:
        return 'false'

    words = []
    def get_words(mat):
        for r in mat:
            word,counter='',0
            for c in r:
                if c=='':
                    if counter>1:
                        words.append(word)
                    word, counter = '', 0
                else:
                    word, counter = word+c, counter+1
            if counter > 1:
                words.append(word)
    get_words(M)
    # transpose M
    get_words(M.T)
    return words

Usage:

Function takes an array of array of strings as input:

crosswords(
[["",  "wo", "r",  "k"],
[ "",   "r",  "",   ""],
[ "he", "l",  "lo", ""],
[ "",   "d",  "ad", ""]])

Returns the string false when connectivity returns multiple labels.
Returns array of valid words otherwise.

I timed it with timeit, time.time() and using the console command time and but I don't know which one to use or which one to post here.


JavaScript (ES6), 58 54 bytes

a=>a.map(c=>a<(a=c)?`Excelsior${s+='!'}
`:s='').join``

Try it online!

Commented

a =>                           // a[] = input array, also used to store the previous value
  a.map(c =>                   // for each value c in a[]:
    a <                        //   compare the previous value
    (a = c)                    //   with the current one; update a to c
                               //   this test is always falsy on the 1st iteration
    ?                          //   if a is less than c:
      `Excelsior${s += '!'}\n` //     add a '!' to s and yield 'Excelsior' + s + linefeed
    :                          //   else:
      s = ''                   //     reset s to an empty string and yield an empty string
  ).join``                     // end of map(); join everything

Why re-using a[ ] to store the previous value is safe

There are three possible cases:

If \$a[\text{ }]\$ is empty, the callback function of .map() is not invoked at all and we just get an empty array, yielding an empty string.
If \$a[\text{ }]\$ contains exactly one element \$x\$, it is coerced to that element during the first (and unique) test a < (a = c). So, we're testing \$x < x\$, which is falsy. We get an array containing an empty string, yielding again an empty string.
If \$a[\text{ }]\$ contains several elements, it is coerced to NaN during the first test a < (a = c). Therefore, the result is falsy and what's executed is the initialization of \$s\$ to an empty string -- which is what we want. The first meaningful comparison occurs at the 2nd iteration.


C and C++, 68 65 bytes

#include<math.h>
float f(float n){auto p=.5;return pow(n,2-p*3);}

Original answer:

#include<math.h>
float f(float n){return pow(n,sizeof('-')-1?2:.5);}

For both versions, C produces n^2 and C++ produces sqrt(n).


05AB1E, 23 21 bytes

Uses CP-1252 encoding.

œJvy3ôD€SøJìHDps2›*P—

Too slow for TIO.

Explanation

œJ                     # all permutations of input as strings
  v                    # for each permutation
                       # EXAMPLE: 2E3815DD5
   y3ô                 # split in pieces of 3
                       # EXAMPLE: ['2E3','815','DD5']
      D                # duplicate
                       # EXAMPLE: ['2E3','815','DD5'], ['2E3','815','DD5']
       €SøJ            # zip the copy to swap rows and columns
                       # EXAMPLE: ['2E3','815','DD5'], ['28D','E1D','355']
           ì           # attach them to the same list
                       # EXAMPLE: ['2E3','815','DD5','28D','E1D','355']
            H          # convert from base 16 to base 10
                       # EXAMPLE: [739, 2069, 3541, 653, 3613, 853]
             D         # duplicate
                       # EXAMPLE: [739, 2069, 3541, 653, 3613, 853],[739, 2069, 3541, 653, 3613, 853]
              p        # check first copy for primality
                       # EXAMPLE: [739, 2069, 3541, 653, 3613, 853],[1,1,1,1,1,1]
               s2›     # check that each in second copy is larger than 2
                       # EXAMPLE: [1,1,1,1,1,1],[1,1,1,1,1,1]
                  *    # pairwise multiplication
                       # EXAMPLE: [1,1,1,1,1,1]
                   P   # product (1 if all were primes larger than 2, else 0)
                       # EXAMPLE: 1
                    —  # if 1, print y
                       # EXAMPLE: 2E3815DD5


MATL, 1 byte

)

Try it online!

Well, hard to make it much simpler. ) indexes the first input, using the second input value. This is 1-indexed.


Pyth - 8 bytes
^+jkUTG4

Try smaller password length online here.


Align function arguments on their own lines

Haskell, 115 bytes

import Data.Lists
f x|(a,b:c)<-span(/='(')x,(d,e)<-span(/=')')c=a++b:intercalate(",\n "++(a>>" "))(splitOn", "d)++e

Usage example:

*Main> putStrLn $ f "fn f(a: i32, b: f64, c: String) -> (String, Vec<i32>) {"
fn f(a: i32,
     b: f64,
     c: String) -> (String, Vec<i32>) {

How it works:

bind
  a: everything before the first (
  b: the first (
  c: everything after the first (
  d: everything of c before the first )
  e: everything of c from the first ) to the end

construct the output string by concatenating
  a
  b
  splitting d at the argument separator ", " and rejoining it with ",\n " followed by (length a) spaces
  e


Compare char to other chars in javascript

Try /[AEIOU]/.test(s)

Body must be at least 30 characters; you entered 21


APL, 16 chars

{×/1⌈÷/⊃⍵,¨¯1⌽⍵}

This version uses @Frxstrem's simpler algorithm and @xnor's max(r,1) idea.

It also assumes that the series is overall rising, that is, the first bitcoin value is smaller than the last one. This is consistent with the problem description. To get a more general formula, the first couple of rates must be dropped, adding 2 chars: {×/1⌈÷/⊃1↓⍵,¨¯1⌽⍵}

Example:

    {×/1⌈÷/⊃⍵,¨¯1⌽⍵}  0.48 0.4 0.24 0.39 0.74 1.31 1.71 2.1 2.24 2.07 2.41
10.86634461
    {×/1⌈÷/⊃⍵,¨¯1⌽⍵}  (the 1000 array from pastebin)
321903884.6

Explanation:

Start with the exchange rate data:

    A←0.48 0.4 0.24 0.39 0.74 1.31 1.71 2.1 2.24 2.07 2.41

Pair each number with the preceding one (the first will be paired with the last) and put them into a matrix:

    ⎕←M←⊃A,¨¯1⌽A
0.48 2.41
0.4  0.48
0.24 0.4
0.39 0.24
0.74 0.39
1.31 0.74
1.71 1.31
2.1  1.71
2.24 2.1
2.07 2.24
2.41 2.07

Reduce each row by division, keep those with ratio > 1, and combine the ratios by multiplication. This will eliminate any repeating factors in a row of successive rising rates, as well as the spurious ratio between the first and last exchange rates:

    ×/1⌈÷/M
10.86634461


In addition to the ones already posted, here are some tricks I've gathered over time, in no specific order...

For the function calls that only have one parameter delimited by a symbol (" for strings, { for tables), the parameter doesn't need to be wrapped around parentheses.
For example, instead of doing print("hello"), you can simply do : print"hello"
Remove as much whitespace as possible - this is especially easy to do after a symbol that closes strings (or before one opening), function calls, tables... Instead of print(42) a=1 you can do print(42)a=1. Other example: print(a and-1 or-2).
Use the ternary operator when you can! Instead of if a>0 then print("hello") else print("goodbye") end, prefer print(a>0 and "hello" or "goodbye"). More info here.
(This can actually get even better : print(a>0 and"hello"or"goodbye"))
Use the colon-call syntactic sugar when you can : instead of string.rep(str,12), do str:rep(12). That also works on non-variables this way (and only this way) : ("a"):rep(5)
Instead of doing tonumber(str) just do str+0
For functions with no parameters, instead of defining them the usual way (function tick() blabla() end), you can do : ticks=loadstring"blabla()", which saves 1 or more bytes, depending on the content. Also, if you define multiple functions, localize loadstring to a 1-char variable before and you'll save a lot of bytes ;). Credits to Jim Bauwens for this trick.
Lua considers empty string (and 0 too unlike other languages) as true in conditional tests, so, for example, instead of doing while 1 do ... end, save 1 byte by writing while''do ... end


Ruby, 184 bytes

a=0
l=$<.map{|x|x.bytes.map{|y|y==32?0:1}+[0]*2}
(0..l[0].count-1).map{|i|l[0][i]+2*l[1][i]+4*l[2][i]}.each{|x|
x>0?(a=x+2*a):(p Hash[[40,6,32,20,18,26,42,8,44,64].zip(0..9)][a];a=0)}

Explanation

takes the input from stdin
converts the strings to binary sequences, 1/0 for segment on/off
encodes columns to 3bit binary number
encodes sequences of 3 bit numbers to 9 bit numbers, use '0' columns as stop symbols
use a lookup table to convert the 9 bit numbers to digits

This is my first code-golf. Thanks for the fun!


Pyth, 86 bytes, full program

=N.tE7=Z*6*.n0cEl.n'zMmhtS[0255ss*VG.>+Lc-1.tH1 3[.tH1Kc.tH0@3 2_K)d)3.wmmgk~-NZd'z

Pyth doesn't have built-in color space conversions - this is the real deal.

Takes input in the following format on stdin:

input_filename.png
offset
cycles

The output image is written to o.png.

This works by rotating the color cube around its diagonal, and then clamping any values outside of the range.

If a is the angle to rotate by, and r, g, b is the input color, we calculate the new color r', g', b' by:

o = cos(a), i = sin(a) / sqrt(3)
n = (1 - o) / 3
m = [n + o, n - i, n + i]
clamp(c) = max(0, min(255, c))
r' = clamp(r*m[0] + g*m[1] + b*m[2])
g' = clamp(r*m[2] + g*m[0] + b*m[1])
b' = clamp(r*m[1] + g*m[2] + b*m[0])


Piet, 9625

(It finally works!)

The people demanded it, so here it is. This is an extremely naive solution (essentially the same as the loose upper bounds on the OEIS page): it divides each square into just two rectangles.

This gist contains the details in two files:

The program's output (using npiet v1.3) for all required inputs. Note that I only captured stdout, so the ? is the input prompt, followed immediately by the output score, then the grid.
The "pseudo-assembly" source I used to plan out the program.

Explanation

This program takes a single number N as input. If the number is odd, the score is the number; if even, the score is twice the number.

After outputting the score, the rest of the left-hand side of the program is spent filling the stack with five lots of the following information:

The grid width (which is N)
A number of lines to print
A character to print across the grid (either _ or space)
A character to print at each edge of the grid (either space or |)

The right-hand side of the program takes each set of four values and prints out that part of the grid.


COW, 363 285 bytes
moOoommoOmoOmoOoomMOOmoOmOoMOOMOomOoMoOmoOMMMMOOMMMMOomOoMOomoOmoOMoOmOoMMMOOOmooMMMmoomoOMMMOOOmOoMMMmOoMOOmOoMMMmoOmoOmoOMMMMOOMOomoOMMMMOOMMMMOoMOoMMMOOOmooMMMMoOmOomoomOomOoOOOmoomOomOoMOOMOomoOMoOmOoMMMMOOMMMMOomoOMOomOomOoMoOmoOMMMOOOmooMMMmoomOoMMMOOOmoOMMMmoOmoOmoOmoomoOmoOOOM

Try it online!
A major change! (It's faster but still test cases exceed the 60 seconds timeout on TIO)
Now I like it better, it's cleaner, symmetric and I've brute forced the memory cells disposition for least number of movements.
The idea is to directly operate in terms of parity. Information in both LSB will be used in each iteration and then a and b will be halved, until b=0.

Every a%2 is calculated (during repeated subtraction) alternating +1 and -1 in one memory cell, so that their partial sum p is available.
When a '1' is found in b, the parity (the answer) is toggled p many times.

Detailed Explanation:
moo ]    mOo <    MOo -    OOO *    OOM i
MOO [    moO >    MoO +    MMM =    oom o

[0]: a/2     [1]: a     [2]: Sum(a%2)     [3]: b%2     [4]: b     [5]: b/2     [6]: parity

>i>>>i                        ;  Read a in [1] and b in [5]
[                             ;  Loop while [5] is non-zero
    ><                        ;     Just 2 instructions for free cause COW doesn't handle consecutive parethesis :D
    [                         ;     Loop while [5] is non-zero
        -<+>=[=-<->>+<=*]=    ;         SECTION B
    ]                         ;     [5] is 0, [3] is b%2, [5] is b/2
    >=*<=                     ;     Copy [5] in [4], delete [5]
    <                         ;     Point to [3]
    [                         ;     Loop if [3] is non-zero. '1' it's been found in b, parity gets updated
        <=>>>=                ;         Copy [2] in [5]
        [                     ;         Loop while [5] is non zero
            -                 ;             Decrement [5]
            >=[=--=*]=+<      ;             TOGGLE [6]
        ]                     ;
        <<*                   ;         Delete [3] (to exit the loop)
    ]                         ;
    <<                        ;     Point to [1]
    [                         ;     Loop while [1] is non-zero
        ->+<=[=->-<<+>=*]=    ;         SECTION A
    ]                         ;     [1] is 0, a%2 is added in [2], [0] is a/2
    <=*>=                     ;     Copy [0] in [1], delete [0]
    >>>                       ;     Point to [5]
]                             ;     a's and b's LSB have been treated. Now a=a/2 and b=b/2
>>o                           ;  Print [6]

SECTION A ≈ SECTION B is repeated subtraction that divide \$n\$ (a or b, resp.) by \$2\$.
This can't be done in one single step (i.e. --), because \$0\$ can't be surpassed in order to stop (so it'd be -[- =*]=). These sections contextually produce \$n\bmod 2\$ (LSB).
TOGGLE is a toggling method:
When target is 0 it fails the condition and simply +1 is done.
When target is 1 it passes the condition and it's set to -1 so that +1 on exit makes it 0.
Copy, delete, and paste in the same memory cell is a tecnique to treat a while loop like an if loop, also the seemgly useless copy-paste at the beginning of these (=[=) serves to balance the ending one (=*]=) in case if condition fails.


Python workarounds for assignment in lambda

Assignment expressions in Python 3.8

Python 3.8 (TIO) introduces assignment expressions, which use := to assign a variable inline as part of expression.

>>> (n:=2, n+1)
(2, 3)

This can be used inside a lambda, where assignments are not ordinarily allowed. Compare:

lambda s:(t:=s.strip())+t[::-1]
lambda s:s.strip()+s.strip()[::-1]
def f(s):t=s.strip();return t+t[::-1]

See this tip for more.


c99 -- 620ish neccessary characters

#include <stdlib.h>
#define S return
typedef struct n N;struct n{int x,y;N*n;};
N*I(int x,int y,N*l){if(!l)goto z;N*m=l;do{if((m->x==x)&&(m->y==y))
S m;m=m->n;}while(m!=l);z:S NULL;}N*A(N*n,N*l){if(!l)n->n=n,l=n;
else n->n=l->n,l->n=n;S l;}N*R(N*n,N*l){if(!l||(l==n&&n->n==n))goto z;
N*m=l;do{if(m->n==n){m->n=n->n;S m;}m=m->n;}while(m!=l);z:S NULL;}
int E(N*l){int i=0;if(!l)goto z;N*m=l;do{++i;m=m->n;}while(m!=l);z:S i;}
int C(N*l){N*c=NULL,*n=l,*m=l=R(n,l);c=A(n,c);int a=E(l)*E(l);do{
if(!l)S 1;n=m->n;if(I(m->x-1,m->y,c)||I(m->x+1,m->y,c)||I(m->x,m->y-1,c)
||I(m->x,m->y+1,c))l=R(m,l),c=A(m,c);m=n;}while(--a);S 0;}

More than half the bulk is taken up by a minimal implementation of a linked list---c is horribly deficient in that sense.

The code here includes the definition of the nodes and all the list manipulation functions called by C, my connectedness checker.

The method is to maintain two lists (one of connected nodes initialized by the first node) and one of yet-to-be-connected nodes (starting with everything else). What follows is an exhaustive cyclic search to find a connection for each node in turn. There is an upper limit on the number of attempts conservatively set to length-of-the-list squared, which marks the end of attempts. Very inefficient, but functional.

It completes several simple cases of my own devising and both of the given test cases correctly.

Full program with test scaffold and some comments

#include <stdio.h>
#include <stdlib.h>
typedef struct n N;
struct n{
  int x,y;
  N*n;
};
N*I(int x,int y,N*l){ /* Return pointer to node x,y in l or NULL */
  if(!l)goto z;
  N*m=l;
  do{
    if((m->x==x)&&(m->y==y)){
      return m;
    }
    m=m->n;
  }while(m!=l);
 z:return NULL;
};
N*A(N*n,N*l){ /* Add node n to list l. Return the new l */
  if(!l){
    n->n=n;
    l=n;
  }else{
    n->n=l->n;
    l->n=n;
  }
  return l;
};
N*R(N*n,N*l){ /* Remove node n from list l. Return the new l */
  if(!l||(l==n&&n->n==n))goto z;
  N*m=l;
  do{
    if(m->n==n){m->n=n->n; return m;}
    m=m->n;
  }while(m!=l);
 z:return NULL;
}
int E(N*l){ /* Return the Enumberation of nodes in list l */
  int i=0;
  if(!l)goto z;
  N*m=l;
  do{++i;m=m->n;}while(m!=l);
 z:return i;
}
int C(N*l){ /* return true if all nodes in list l are connected */
  N*c=NULL,*n=l,*m=l=R(n,l); /* put the first node in the connected
                            list, and mark the start of the
                            working list */
  c=A(n,c);
  int a=E(l)*E(l); /* maximum number of times to try to place nodes */
  do {
    if (!l) return 1; /* when l is empty: we win! */
    n=m->n;
    if ( I(m->x-1,m->y  ,c) ||
     I(m->x+1,m->y  ,c) ||
     I(m->x  ,m->y-1,c) ||
     I(m->x  ,m->y+1,c) ) l=R(m,l), c=A(m,c);
    m=n;
  } while (--a);
  return 0;
}
void P(N*l){ /* Print the list */
  printf("List: [");
  if(!l)goto z;
  N*m=l;
  do{printf(" (%d, %d)",m->x,m->y);m=m->n;}while(m!=l);
 z:printf(" ]\n");
}
N*G(int x,int y){ /* generate a new node with (x, y) */
  N*n;
  if(n=malloc(sizeof(N)))n->x=x,n->y=y;
  return n;
}
int main(){
  N*n,*l=NULL;

  n=G(0,0); l=A(n,l);
  n=G(1,0); l=A(n,l);
  n=G(2,0); l=A(n,l);
  n=G(0,1); l=A(n,l);
  n=G(0,2); l=A(n,l);
  n=G(2,2); l=A(n,l);
  n=G(3,2); l=A(n,l);
  n=G(4,2); l=A(n,l);
  n=G(0,3); l=A(n,l);

  n=G(4,3); l=A(n,l);
  n=G(0,4); l=A(n,l);
  n=G(1,4); l=A(n,l);
  n=G(2,4); l=A(n,l);
  n=G(4,4); l=A(n,l);
  n=G(4,5); l=A(n,l);
  n=G(2,6); l=A(n,l);
  n=G(3,6); l=A(n,l);
  n=G(4,6); l=A(n,l);

  P(l);
  if (C(l)) {
    printf("Connected!\n");
  } else {
    printf("Not connected.\n");
  };
}


Who will win a Rock, Paper, Scissors, Lizard, Spock game?

Python 3, 68 50 48 bytes

EDIT: Thanks to 3 tricks from Neil, and 2 from Mr. Xcoder

Each input string has a distinct fourth character, so I'm using that to distinguish them. If you arrange the elements in the cycle (scissors, paper, rock, lizard, spock), then each element beats the element directly after it and the element 3 spots to the right, cyclically. So we subtract the inputs' positions in the cycle. If that number is 0, it's a tie. If it's 1 or 3, it's a win for the first player. In my original solution, the cycle difference would index into the string "210100" to distinguish the results of the game. Neil somehow figured out this can be accomplished without indexing by adding 7 and taking the modulus by 3. Edit: Originally I used the second character to identify the string, but if you use the fourth and reverse the cycle, you get cake. And we could all use more cake.

lambda x,y,z="cake".find:(7+z(y[3])-z(x[3]))%5%3

Try it online!

Older version:

lambda x,y,z="caoip".index:(7+z(y[1])-z(x[1]))%5%3

Try it online!

Original version:

b="caoip"
def r(x,y):return"210100"[(b.index(y[1])-b.index(x[1]))%5]

Try it online!


The algorithm is quite straightforward: Compute the modulus using a state machine (the largest part with eight branches - one of the states is duplicated for logistical purposes), then encode and collect the results. Since almost every result contains a one digit, an extra compression step is employed to reduce the amount of parts.

Designed in yEd, then transcribed to Manufactoria.

Uses way too many conveyer belts, in my opinion.


Describe a 2D Bitmap Using Filled Rectangle Mapping

Rust

Try it online

Average case num rectangles: 57.9054 (10000 iterations of 20x20 matrices, with 1/7 probability of "0")

Solution to example input:
{10,0,13,3,8,1,14,3,4,2,15,2,5,3,15,3,0,5,6,7,17,5,21,5,0,6,10,7,20,6,21,6,0,7,15,7}

The algorithm is pretty simple: for each horizontal line of 1s, use that as the top side of a rectangle, extend this rectangle down while possible, and if it covers some previously uncovered area, add it to the list. This assumes rectangles can overlap. I have not verified whether the output is always correct, but the example input looks ok. The output was verified against the input for 10000 iterations, and it looks correct.

The code includes a benchmark function to calculate the score, and a function to draw the result. The input can be changed in the main function.

extern crate rand;
use rand::{Rng, thread_rng};

#[derive(Copy, Clone, Debug)]
struct Rect {
    x0: usize,
    y0: usize,
    x1: usize,
    y1: usize
}

impl Rect {
    fn contains_xslice(&self, xa: usize, xb: usize) -> bool {
        self.x0 <= xa && xb <= self.x1
    }
    fn contains(&self, r: &Rect) -> bool {
        // r is completely inside of self
        self.x0 <= r.x0 && r.x1 <= self.x1 && self.y0 <= r.y0 && r.y1 <= self.y1
    }
}

fn display_rects(r: &[Rect]) -> String {
    let s = r.iter()
        .map(|z| format!("{},{},{},{}", z.x0, z.y0, z.x1, z.y1))
        .collect::<Vec<_>>()
        .join(",");

    // transform 1,1 into {1,1}
    format!("{{{}}}", s)
}

fn draw_rects(r: &[Rect], w: usize, h: usize) -> String {
    let mut s = format!("");
    for y in 0..h {
        for x in 0..w {
            let p = Rect { x0: x, x1: x, y0: y, y1: y };
            if r.iter().any(|a| a.contains(&p)) {
                s.push_str("1");
            } else {
                s.push_str("0");
            }
        }
        s.push_str("\n");
    }
    s
}

#[derive(Clone, Debug, PartialEq, Eq)]
struct Matrix {
    v: Vec<u8>,
    size: (usize, usize),
}

impl Matrix {
    fn new(w: usize, h: usize) -> Self {
        Self {
            v: vec![0; w*h],
            size: (w, h),
        }
    }
    fn from_str(s: &str) -> Self {
        let mut v = vec![];
        let mut w = None;
        let mut h = 0;
        for l in s.lines() {
            h += 1;
            let mut tw = 0;
            for c in l.chars() {
                tw += 1;
                let x = match c {
                    '0' => 0,
                    '1' => 1,
                    a => panic!("Invalid input! {:?} at {},{}", a, tw, h),
                };
                v.push(x);
            }
            if let Some(ww) = w {
                if tw != ww {
                    panic!("All lines must have the same width! {} != {}", tw, ww);
                }
            } else {
                w = Some(tw);
            }
        }

        let w = w.unwrap_or(0);

        Matrix {
            v,
            size: (w, h),
        }
    }
    fn random(w: usize, h: usize) -> Self {
        let mut rng = thread_rng();
        let mut v = vec![];

        for _ in 0..w*h {
            let n = rng.gen_range(0, 6+1);
            let x = if n == 0 { 0 } else { 1 };
            v.push(x);
        }

        Matrix {
            v,
            size: (w, h),
        }
    }
    fn get(&self, x: usize, y: usize) -> u8 {
        self.v[y * self.size.0 + x]
    }
    fn hline(&self, y: usize) -> &[u8] {
        &self.v[y * self.size.0 .. (y + 1) * self.size.0]
    }
    fn hline_1_pieces(&self, y: usize) -> Vec<Rect> {
        let mut r = vec![];
        let line = self.hline(y);
        let xmax = self.size.0 - 1;
        let y0 = y;
        let y1 = y;
        let mut lineit = line.iter();
        let mut xoff = 0;
        while lineit.len() > 0 {
            // Find first non-zero pixel
            if let Some(x0) = lineit.position(|&x| x != 0) {
                let x0 = xoff + x0;
                // x0..x1 is a line of 11111
                let x1 = x0 + lineit.position(|&x| x == 0).unwrap_or(xmax - x0);
                r.push(Rect { x0, x1, y0, y1 });
                // Remember offset because the iterator is being consumed
                xoff = x1 + 2;
            }
        }

        r
    }
    fn rectangles(&self) -> Vec<Rect> {
        let mut r: Vec<Rect> = vec![];
        let ymax = self.size.1 - 1;
        // For each hline, add rectangles covering the maximum width possible
        let hpieces: Vec<Vec<Rect>> = (0..self.size.1).map(|i| self.hline_1_pieces(i)).collect();
        // Extend each rectangle down while possible
        for (y0, layer) in hpieces.iter().enumerate() {
            for rect in layer {
                let mut y = y0 + 1;
                while y <= ymax {
                    if hpieces[y].iter().any(|&r| r.contains_xslice(rect.x0, rect.x1)) {
                        y += 1;
                    } else {
                        break;
                    }
                }
                let y1 = y - 1;
                let rn = Rect { y1, ..*rect };
                if r.iter().any(|&r1| r1.contains(&rn)) {
                    // An equivalent rectangle is already in the vec
                } else {
                    // This rectangle covers some new area, push it
                    r.push(rn);
                }
            }
        }

        r
    }
}

fn benchmark(iterations: usize) -> f64 {
    let mut sum = 0;
    for _ in 0..iterations {
        let m = Matrix::random(20, 20);
        let r = m.rectangles();
        let output = draw_rects(&m.rectangles(), 20, 20);
        assert_eq!(m, Matrix::from_str(&output));
        sum += r.len();
    }
    sum as f64 / iterations as f64
}

fn main() {
    let input = "\
0000000000111100000000
0000000011111110000000
0000111111111111000000
0000011111111111000000
0000000000000000000000
1111111000000000011111
1111111111100000000011
1111111111111111000000
";
    let m = Matrix::from_str(input);
    assert_eq!(input, draw_rects(&m.rectangles(), 22, 8));
    println!("{}", display_rects(&m.rectangles()));
    println!("{}", benchmark(10000));
}


Golf Me a Random Dubstep of the Day List

JavaScript, 532 536 538 582 bytes

Thanks to @ӍѲꝆΛҐӍΛПҒЦꝆ and @Quill for a whole bunch of bytes.

I did do a couple of things here which may not be 100% to the spec - If they aren't admissible please tell me and I'll fix them:

I shortened the YouTube URL
The shuffle is VERY weak, and is not considered in any way close to
random.
There's a bit of whitespace due to the join.

I'd like to start by saying, to any JavaScript developers out there: I'm so sorry.

New version alternates captures to reduce on regex byte cost and strips some URL length, but sacrifices on alerts. Now instead of 3, you get like 20. Unfortunately the https on the URL's seem to be required or the page won't load, though that may be my setup :/.

This could possibly be improved with proper XML parsing and loops instead of weird recursion things with calls to other functions. I had fun taking advantage of the fact that XMLHttpRequest causes synchronous execution.

d="https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=PLF5C76212C58C464A&key={REALLY SUPER LONG GOOGLE API KEY HERE}",h=[];o=l=>{x=new XMLHttpRequest,x.open("GET",l,!1),x.send(0),j=x.responseText;y=`nextPageToken": "`;e(j)
j.includes(y)&&(q=j.split(y)[1].split('"')[0],o(d+"&pageToken="+q));h.sort(b=>.5-Math.random());alert(h.join `
`)}
e=v=>{for(r=/(title": "(.*)\[)|(oId": "(.*)")/g;null!==(m=r.exec(v));)a=m[2]+": https://youtu.be/"+r.exec(v)[4],z="] - ",a.includes(z)&&(a=a.split(z)[1]),h.push(a)}
o(d)

Replace the {REALLY SUPER LONG GOOGLE API KEY HERE} with your 39 character long YouTube API key.

Ungolfed:

//Define base URL, sacrificing speed and pages for bytes
d = "https://www.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=PLF5C76212C58C464A&key={REALLY SUPER LONG GOOGLE API KEY HERE}";
h = [];
o = l => {
    //Grab API data
    x = new XMLHttpRequest();
    x.open("GET", l, false);
    x.send(0);
    j = x.responseText;
    //Set up a split since we use it twice
    y = `nextPageToken": "`;
    //At this point, jump off to the other function to deal with the output
    e(j);
    //If there are multiple pages of results, as we only get a couple from each API call to save bytes with URL's
    if (j.includes(y)) {
        //Get the ID for the next page
        q = j.split(y)[1].split("\"")[0];
        //Call again with an added parameter
        o(d + "&pageToken=" + q)
    }
    //Taking advantage of XMLHttpRequest forcing this as synchronous, so all the above happens first
    //Bad shuffle
    h.sort(b => .5 - Math.random())
    alert(h.join `
        `);
}
e = v => {
    //Regex for titles/ID's - Grabbitz doesn't fit the "[Genre] - Song - Artist" mould so we need a slightly longer regex
    r = /(title": "(.*)\[)|(oId": "(.*)")/g;
    //Since we know there's one title to one video, we can run them both at the same time
    while ((m = r.exec(v)) !== null) {
        //Build the string
        a = m[2] + ": https://youtu.be/" + r.exec(v)[4];
        z = "] - ";
        //That Grabbitz edge case ruining my day again, I'm glad it's a good track...
        if (a.includes(z)) {
            a = a.split(z)[1];
        }
        h.push(a);
    }
}
o(d)


Find the shortest route on an ASCII road

Python 3, 163 bytes

def f(g,s=[]):w=len(g[0])+1;k=' '.join(g)+w*' ';*p,x=s or[k.find('#')];return' '<k[x]and{x}-{*p}and[min(f(g,s+[x+a])or len(k)for a in(-1,1,-w,w)),len(p)]['+'<k[x]]

Try it online!

Uses # for start and @ for end. Finds all paths along + and returns the shortest. Each path ends when either a space is encountered, the range is outside the box or a previous position is visited.


JavaScript (ES6),  18  17 bytes
Similar to my answer to Is this number evil? except that the last iteration returns \$0\$, which saves a byte.

f=n=>n&&!f(n&~-n)

Try it online!

JavaScript (ES6), 30 bytes
Converts to binary, parses as base-3 and returns the parity.

n=>parseInt(n.toString(2),3)&1

Try it online!


Charcoal, 83 bytes
≔AηＦ↨Ｎ⁵≔§⁺η§⪪”$⌊∧Ｘ;F‖ρ=ＪD θ⊘⊙～'ΣV⦄Ｋ◨｜]≕‖◨⟧TJρ¿¿C´!⁸⁶S/Ｕ¶V×Ｗ⧴a“,=6；‴*Þ↓h!�{≦”⁴⌕αηιηη

Try it online! Link is to verbose version of code. Explanation:
≔Aη

Start with A at the 0th index.
Ｆ↨Ｎ⁵

Input n, convert it to base 5 and loop over the digits.
≔§⁺η§⪪”...”⁴⌕αηιη

Get the current animal from the compressed string of all animal suffixes (excluding EBRA) and lookup the appropriate letter from the current digit.
η

Output the final letter.


Pyke, 1 byte
s

Try it here!
Takes the digital root of the input


Python
import this
love = this
this is love, love is not True or False, love is love
# (True, True, True)

Okay, this returns a tuple of Truths, but that itself evaluates as True anyway.


Build a pair of spies that will throw stones into a river

C#, M = 2535

This implements* the system which I described mathematically on the thread which provoked this contest. I claim the 300 rep bonus. The program self-tests if you run it either without command-line arguments or with --test as a command-line argument; for spy 1, run with --spy1, and for spy 2 with --spy2. In each case it takes the number which I should communicate from stdin, and then does the throws via stdin and stdout.

* Actually, I've found an optimisation which makes a massive difference (from several minutes to generate the decision tree, to less than a second); the tree which it generates is fundamentally the same, but I'm still working on a proof of that. If you want a direct implementation of the system which I described elsewhere, see revision 2, although you might want to backport the extra logging from Main and the better inter-thread comms from TestSpyIO.

If you want a test case which completes in less than a minute, change N to 16 and M to 87.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

namespace CodeGolf
{
    internal class Puzzle625
    {
        public static void Main(string[] args)
        {
            const int N = 26;
            const int M = 2535;

            var root = BuildDecisionTree(N);

            if (args.Length == 0 || args[0] == "--test")
            {
                DateTime startUtc = DateTime.UtcNow;
                Console.WriteLine("Built decision tree in {0}", DateTime.UtcNow - startUtc);
                startUtc = DateTime.UtcNow;

                int ok = 0;
                int fail = 0;
                for (int i = 1; i <= M; i++)
                {
                    for (int j = 1; j <= M; j++)
                    {
                        if (Test(i, j, root)) ok++;
                        else fail++;
                    }
                    double projectedTimeMillis = (DateTime.UtcNow - startUtc).TotalMilliseconds * M / i;
                    Console.WriteLine("Interim result: ok = {0}, fail = {1}, projected test time {2}", ok, fail, TimeSpan.FromMilliseconds(projectedTimeMillis));
                }
                Console.WriteLine("All tested: ok = {0}, fail = {1}, in {2}", ok, fail, DateTime.UtcNow - startUtc);
                Console.ReadKey();
            }
            else if (args[0] == "--spy1")
            {
                new Spy(new ConsoleIO(), root, true).Run();
            }
            else if (args[0] == "--spy2")
            {
                new Spy(new ConsoleIO(), root, false).Run();
            }
            else
            {
                Console.WriteLine("Usage: Puzzle625.exe [--test|--spy1|--spy2]");
            }
        }

        private static bool Test(int i, int j, Node root)
        {
            TestSpyIO io1 = new TestSpyIO("Spy 1");
            TestSpyIO io2 = new TestSpyIO("Spy 2");
            io1.Partner = io2;
            io2.Partner = io1;

            // HACK! Prime the input
            io2.Output(i);
            io1.Output(j);

            Spy spy1 = new Spy(io1, root, true);
            Spy spy2 = new Spy(io2, root, false);

            Thread th1 = new Thread(spy1.Run);
            Thread th2 = new Thread(spy2.Run);
            th1.Start();
            th2.Start();

            th1.Join();
            th2.Join();

            // Check buffer contents. Spy 2 should output spy 1's value, so it's lurking in io1, and vice versa.
            return io1.Input() == i && io2.Input() == j;
        }

        private static Node BuildDecisionTree(int numStones)
        {
            NodeValue[] trees = new NodeValue[] { NodeValue.Trivial };
            for (int k = 2; k <= numStones; k++)
            {
                int[] prev = trees.Select(nv => nv.Y).ToArray();
                List<int> row = new List<int>(prev);
                int cap = prev.Length;
                for (int i = 1; i <= prev[0]; i++)
                {
                    while (prev[cap - 1] < i) cap--;
                    row.Add(cap);
                }

                int[] next = row.OrderByDescending(x => x).ToArray();
                NodeValue[] nextTrees = new NodeValue[next.Length];
                nextTrees[0] = trees.Last().Reverse();
                for (int i = 1; i < next.Length; i++)
                {
                    int cp = next[i] - 1;
                    nextTrees[i] = trees[cp].Combine(trees[i - prev[cp]]);
                }

                trees = nextTrees;
            }

            NodeValue best = trees.MaxElement(v => Math.Min(v.X, v.Y));
            return BuildDecisionTree(numStones, best, new Dictionary<Pair<int, NodeValue>, Node>());
        }

        private static Node BuildDecisionTree(int numStones, NodeValue val, IDictionary<Pair<int, NodeValue>, Node> cache)
        {
            // Base cases
            // NB We might get passed val null with 0 stones, so we hack around that
            if (numStones == 0) return new Node(NodeValue.Trivial, new Node[0]);

            // Cache
            Pair<int, NodeValue> key = new Pair<int, NodeValue>(numStones, val);
            Node node;
            if (cache.TryGetValue(key, out node)) return node;

            // The pair-of-nodes construction is based on a bijection between
            //     $\prod_{i<k} T_i \cup \{(\infty, 0)\}$
            // and
            //     $(T_{k-1} \cup \{(\infty, 0)\}) \times \prod_{i<k-1} T_i \cup \{(\infty, 0)\}$

            // val.Left represents the element of $T_{k-1} \cup \{(\infty, 0)\}$ (using null for the $(\infty, 0)$)
            // and val.Right represents $\prod_{i<k-1} T_i \cup \{(\infty, 0)\}$ by bijection with $T_{k-1} \cup \{(\infty, 0)\}$.
            // so val.Right.Left represents the element of $T_{k-2}$ and so on.
            // The element of $T_{k-i}$ corresponds to throwing $i$ stones.
            Node[] children = new Node[numStones];
            NodeValue current = val;
            for (int i = 0; i < numStones && current != null; i++)
            {
                children[i] = BuildDecisionTree(numStones - (i + 1), current.Left, cache);
                current = current.Right;
            }
            node = new Node(val, children);

            // Cache
            cache[key] = node;
            return node;
        }

        class Pair<TFirst, TSecond>
        {
            public readonly TFirst X;
            public readonly TSecond Y;

            public Pair(TFirst x, TSecond y)
            {
                this.X = x;
                this.Y = y;
            }

            public override string ToString()
            {
                return string.Format("({0}, {1})", X, Y);
            }

            public override bool Equals(object obj)
            {
                Pair<TFirst, TSecond> other = obj as Pair<TFirst, TSecond>;
                return other != null && object.Equals(other.X, this.X) && object.Equals(other.Y, this.Y);
            }

            public override int GetHashCode()
            {
                return X.GetHashCode() + 37 * Y.GetHashCode();
            }
        }

        class NodeValue : Pair<int, int>
        {
            public readonly NodeValue Left;
            public readonly NodeValue Right;

            public static NodeValue Trivial = new NodeValue(1, 1, null, null);

            private NodeValue(int x, int y, NodeValue left, NodeValue right) : base(x, y)
            {
                this.Left = left;
                this.Right = right;
            }

            public NodeValue Reverse()
            {
                return new NodeValue(Y, X, this, null);
            }

            public NodeValue Combine(NodeValue other)
            {
                return new NodeValue(other.X + Y, Math.Min(other.Y, X), this, other);
            }
        }

        class Node
        {
            public readonly NodeValue Value;
            private readonly Node[] _Children;

            public Node this[int n]
            {
                get { return _Children[n]; }
            }

            public int RemainingStones
            {
                get { return _Children.Length; }
            }

            public Node(NodeValue value, IEnumerable<Node> children)
            {
                this.Value = value;
                this._Children = children.ToArray();
            }
        }

        interface SpyIO
        {
            int Input();
            void Output(int i);
        }

        // TODO The inter-thread communication here can almost certainly be much better
        class TestSpyIO : SpyIO
        {
            private object _Lock = new object();
            private int? _Buffer;
            public TestSpyIO Partner;
            public readonly string Name;

            internal TestSpyIO(string name)
            {
                this.Name = name;
            }

            public int Input()
            {
                lock (_Lock)
                {
                    while (!_Buffer.HasValue) Monitor.Wait(_Lock);

                    int rv = _Buffer.Value;
                    _Buffer = null;
                    Monitor.PulseAll(_Lock);
                    return rv;
                }
            }

            public void Output(int i)
            {
                lock (Partner._Lock)
                {
                    while (Partner._Buffer.HasValue) Monitor.Wait(Partner._Lock);
                    Partner._Buffer = i;
                    Monitor.PulseAll(Partner._Lock);
                }
            }
        }

        class ConsoleIO : SpyIO
        {
            public int Input()
            {
                return Convert.ToInt32(Console.ReadLine());
            }

            public void Output(int i)
            {
                Console.WriteLine("{0}", i);
            }
        }

        class Spy
        {
            private readonly SpyIO _IO;
            private Node _Node;
            private bool _MyTurn;

            internal Spy(SpyIO io, Node root, bool isSpy1)
            {
                this._IO = io;
                this._Node = root;
                this._MyTurn = isSpy1;
            }

            internal void Run()
            {
                int myValue = _IO.Input() - 1;
                int hisValue = 1;

                bool myTurn = _MyTurn;
                Node n = _Node;
                while (n.RemainingStones > 0)
                {
                    if (myTurn)
                    {
                        if (myValue >= n.Value.X) throw new Exception("Internal error");
                        for (int i = 0; i < n.RemainingStones; i++)
                        {
                            // n[i] allows me to represent n[i].Y values: 0 to n[i].Y - 1
                            if (myValue < n[i].Value.Y)
                            {
                                _IO.Output(i + 1);
                                n = n[i];
                                break;
                            }
                            else myValue -= n[i].Value.Y;
                        }
                    }
                    else
                    {
                        int thrown = _IO.Input();
                        for (int i = 0; i < thrown - 1; i++)
                        {
                            hisValue += n[i].Value.Y;
                        }
                        n = n[thrown - 1];
                    }

                    myTurn = !myTurn;
                }

                _IO.Output(hisValue);
            }
        }
    }

    static class LinqExt
    {
        // I'm not sure why this isn't built into Linq.
        public static TElement MaxElement<TElement>(this IEnumerable<TElement> e, Func<TElement, int> f)
        {
            int bestValue = int.MinValue;
            TElement best = default(TElement);
            foreach (var elt in e)
            {
                int value = f(elt);
                if (value > bestValue)
                {
                    bestValue = value;
                    best = elt;
                }
            }
            return best;
        }
    }
}

Instructions for Linux users

You'll need mono-csc to compile (on Debian-based systems, it's in the mono-devel package) and mono to run (mono-runtime package). Then the incantations are

mono-csc -out:codegolf31673.exe codegolf31673.cs
mono codegolf31673.exe --test

etc.


brainfuck - 169 146 142 bytes
-[+>+[+<]>+]>+>>,[>,]<[<]<[->>[->]<[<]<]>>>[[<[-<+<+<+>>>]+++++++++[<[-<+>]<<[-<+>>>+<<]<[->+<]>>>>-]]<,<<,>[->>>+<<<]>>>---------->]<-[->.+<]

Limitations:

EOF must be 0
Requires 8-bit wrapping cells
Because of ^, mods input by 256

Not the shortest answer here, but hey, brainfuck! This would be a really, really good brainfuck challenge, except for the fact that it requires human readable input without guaranteeing the number of digits. I could have required input to have leading zeroes to make it 3 characters long, but what fun is that? :D One major problem with taking input this way is that brainfuck's only branching or looping structure checks if the current cell is zero or not. When the input can contain zeroes, it can cause your code to take branches it shouldn't be taking. To solve this problem, I store each digit of input plus 1, then subtract the excess at the last possible second. That way, I always know where my zeroes are.
I did say that this would have been a great brainfuck challenge without having to parse input. Why is that? Well, let's pretend that we don't take a numeric input. We'll say the challenge is "Given a byte of input, output all ASCII characters below that byte". Here's what my answer would be:

brainfuck - 8 bytes
,[->.+<]

It's quite a difference! The real program uses 135 instructions to collect the input (over 95% of the program!), just because it's a human typing it. Store the number as a byte and give that to me, and it only takes one.
(Fun fact: If you understood the hypothetical program, then congratulations! You understand brainfuck in its entirety. The whole language has only eight commands, and that program happens to use each one exactly once.)
Explanation
-[+>+[+<]>+]>+               abuse 8 bit wrapping to put 47 in cell 4

>>,[>,]                      starting in cell 6; get each character of input

<[<]<[->>[->]<[<]<]          subtract the value of cell 4 from each input character
                             '0' has an ascii value of 47 so subtracting 47 from each
                             digit gives you that digit's value plus 1

>>>[                         if the number is in more than one cell
                             (when the program first starts this means "if the input has
                             more than one digit")

[<[-<+<+<+>>>]               copy first input cell to 3 new cells

+++++++++[<[-<+>]<<          do some fancy addition magic to multiply that value by 10
[-<+>>>+<<]<[->+<]>>>>-]]

<,<<,>                       clean up a bit (abusing comma to set cells to 0)

[->>>+<<<]>>>                add the value to the next cell of input

----------                   because we multiplied (the digit plus 1) by 10; the answer
                             is 10 too high; so subtract 10

>]                           if the input is still in multiple cells; do the song and
                             dance again (multiply by 10; add to next cell; subtract 10)

<-                           we never got a chance to fix the final digit; so it's still 1
                             too high

               ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
               ;;         we have now finished processing input         ;;
               ;;     the tape is empty except for the current cell     ;;
               ;;  the current cell contains the number that was input  ;;
               ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

[                            while the cell containing input != 0

-                            subtract 1 from it

>.+                          go a cell to the right; output that cell; then add 1

<]                           repeat


Pyth, 21 bytes

hf.A.e!f>xYTxkTbQ.plQ

                    Q  input
                   l   length of input array
                 .p    all permutations of [0, 1, ..., lQ-2, lQ-1]
hf                     find the first permutation for which...
    .e          Q        map over the input array with indices...
       f       b           find all elements in each input subarray where...
        >xYT                 index of dependency is greater than...
            xkT              index of item
      !                    check whether resulting array is falsy (empty)
  .A                     is the not-found check true for [.A]ll elements?

Test:

llama@llama:~$ echo '[[2],[0,3],[],[2]]' | pyth -c 'hf.A.e!f>xYTxkTbQ.plQ'
[2, 0, 3, 1]


Jelly, 10 bytes
2*Ḷ^‘l2Ċ⁸_

A dyadic Link that accepts \$w\$ on the left and \$x\$ on the right and yields a list of integers.
Try it online!
How?
2*Ḷ^‘l2Ċ⁸_ - Link: integer, w; integer x   e.g.  3; 5
2          - two                                 2
 *         - (2) exponentiate (w)                8
  Ḷ        - lowered range                       [0,1,2,3,4,5,6,7]
   ^       - XOR (x)                             [5,4,7,6,1,0,3,2]
    ‘      - increment                           [6,5,8,7,2,1,4,3]
     l2    - log base two                        [2.58,2.32,3,2.80,1,0,2,1.58]
       Ċ   - ceiling                             [3,3,3,3,1,0,2,2]
        ⁸  - chain's left = w                    3
         _ - subtract                            [0,0,0,0,2,3,1,1]

Without floating points involved, also 10: 2*Ḷ^ḤBẈ⁸_‘
...would be 8 if 0 in binary were [] rather than [0] (2*Ḷ^BẈ⁸_)


14. X86 Assembly (gcc 6.3), 324 bytes

.TITLE "a"#"a" ELTIT.
.data
i:.fill 25,1,0
s:.string "%25[^\n]"
t:.string "->Hi, Retina!"
f:.string "Bye Retina!"
.global main
main:
pushl $i
pushl $s
call scanf
addl $8, %esp
pushl $i
call strlen
addl $4, %esp
sub $21, %eax
jz y
pushl $f
call printf
addl $4, %esp
jmp en
y:
pushl $t
call printf
addl $4, %esp
en:
ret

Try it on ideone!

Note: this will return a runtime error because the exit code is not zero. Running this in the ideone editor will display all stdout output regardless of how the program concludes.

Truthy output: "->Hi, Retina!"
Falsy output: "Bye Retina!"

Satisfies:

The first character is a ..
It contains an e.
Its length is even.
Its length is a perfect square.
It contains an a.
It contains a > character.
Contains the exact string ->.
Contains the exact string Hi, Retina!.
The sum of the first two Unicode code points is a multiple of 5.
The 10-th character is a ".
The last non-empty line does not have any duplicate characters.
The first line is a palindrome of length > 5.
The first line is exactly 21 characters long (not including newline).

For future answers:

The first character is a ..
Its length is an even perfect square.
Contains the exact sequence ->.
Contains the exact string Hi, Retina!.
The second character's Unicode code point, mod 5, is 4.
The 10-th character is a ".
The last non-empty line does not have any duplicate characters.
The first line is a palindrome of length = 21


Avoid repeating letters between five simple programs

CJam, 73 bytes

"Obkkh+'Phukc&"7f^
q~m!
ri){'j3+_3++~},:+
lS-el_&
4{_' *4@-Y*('**+}%_1>W%\+N*

Each line is a full program. Try them online: 1 | 2 | 3 | 4 | 5

Letter map

 bc  f h  k   op    u       18
            m   q            4
        ij       r          17
    e      l      s          7
             n        w y   27

If you want (and each of your programs fits in a line), you can use this CJam program to create a letter map for your own submission.


Width
The interpreter is still a work in progress (I have several unused command slots still). The repo, with more documentation, can be found here.
Dennis added Width to TIO less than a minute ago: Try It Online!
Width is an esoteric stack-based language I developed recently based on ideas I first dumped in this question. It is based entirely on how wide, more or less, a letter is in a "regular" font. The only characters that do anything are letters, uppercase and lowercase. All other characters are ignored. I split letters up into 10 different width categories, which form the 10 different actions possible in Width:
0: i j l                     # do while counter > 0
1: f r t I                   # end
2: c k s v x y z J           # 0 in commands
3: a b d e g h n o p q u L   # separator (no-op)
4: F T Z                     # push base 10 number, using left side row titles (width numbers); terminated with original char
5: A B E K P S V X Y         # 1 in commands
6: w C D H N R U             # 2 in commands
7: G O Q                     # push string literal; sets of 2 width numbers equate to index in printable ASCII; terminated with original char
8: m M                       # if top of stack
9: W                         # else

2, 5, and 6 provide access to the commands, most of which interact with the stack. More information can be found at the info.txt page in the Github repo.
This is the Python code of the interpreter. I still have several commands to add, and I'm considering how to work with error-handling, but otherwise it should be complete. (I'm also going to add a flag at some point to allow testing with a more abstract syntax, because otherwise this language is a giant pain to work with)
import sys
import math
import numbers
import functools

try:
    file = sys.argv[1]
except IndexError:
    file = "source.wide"

with open(file) as f:
    source = f.read()

translation = ("ijl", "frtI", "cksvxyzJ", "abdeghnopquL", "FTZ", "ABEKPSVXY", "wCDHNRU", "GOQ", "mM", "W")
chars = "".join(sorted("".join(translation)))
strings = """ !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`abcdefghijklmnopqrstuvwxyz{|}~\n\t"""

def trans(letter):
    for each in translation:
        if letter in each:
            return translation.index(each)

COMMAND = "COMMAND"
COMMANDS = (2, 5, 6)
NUMBER = "NUMBER"
STRING = "STRING"
DO = "DO"
IF = "IF"
ELSE = "ELSE"
END = "END"
SEPARATOR = "SEPARATOR"

class Token:
    def __init__(self, val, type_):
        self.val = val
        self.type = type_

class Lexer:
    def __init__(self, src):
        self.src = src
        self.pos = 0
        self.char = self.src[self.pos]

    def read(self):
        if self.char is None:
            return None

        command = trans(self.char)

        if command == 0:
            self.advance()
            return Token(0, DO)
        elif command == 1:
            self.advance()
            return Token(1, END)
        elif command == 3:
            self.advance()
            return Token(3, SEPARATOR)
        elif command == 4:
            return self.read_num()
        elif command == 7:
            return self.read_str()
        elif command == 8:
            self.advance()
            return Token(8, IF)
        elif command == 9:
            self.advance()
            return Token(9, ELSE)
        else:
            return self.read_cmd()

    def advance(self):
        self.pos += 1

        try:
            self.char = self.src[self.pos]
        except IndexError:
            self.char = None

    def read_num(self):
        delim = self.char
        self.advance()

        res = ""
        while self.char is not None and self.char != delim:
            res += str(trans(self.char))
            self.advance()

        self.advance()

        return Token(int(res), NUMBER)

    def read_str(self):
        def read_char():
            res_ = str(trans(self.char))
            self.advance()
            res_ += str(trans(self.char))
            self.advance()
            try:
                return strings[int(res_)]
            except IndexError:
                return " "

        delim = self.char
        self.advance()

        res = ""
        while self.char is not None and self.char != delim:
            res += read_char()

        self.advance()

        return Token(res, STRING)

    def read_cmd(self):
        command = ""
        while self.char is not None and trans(self.char) in COMMANDS and len(command) <= 4:
            command += str(COMMANDS.index(trans(self.char)))
            self.advance()

        return Token(command, COMMAND)

source = "".join(filter(lambda c: c in chars, source))

stack = []
backburner = []
counter = 0

def set_counter(val):
    global counter
    counter = int(val)

    if counter < 0:
        counter = 0

def set_stack(val):
    global stack
    stack = val

def num_input():
    inp = input()
    try:
        stack.append(int(inp))
    except ValueError:
        try:
            stack.append(float(inp))
        except ValueError:
            pass

def flip_ends():
    if len(stack) > 1:
        stack[0], stack[-1] = stack[-1], stack[0]

def clear_stack():
    global stack
    stack = []

def reload_stack(is_top):
    global backburner, stack

    if is_top:
        stack.extend(backburner)
    else:
        stack = backburner + stack

    backburner = []

# https://stackoverflow.com/a/15285588/7605753
def is_prime(n):
    if n == 2 or n == 3:
        return True
    if n < 2 or n % 2 == 0:
        return False
    if n < 9:
        return True
    if n % 3 == 0:
        return False
    r = int(math.sqrt(n))
    _f = 5
    while _f <= r:
        if n % _f == 0:
            return False
        if n % (_f + 2) == 0:
            return False
        _f += 6
    return True

def error():
    raise Exception

commands = {
    "0": lambda: stack.append(stack[-1]),
    "1": lambda: stack.append(stack.pop(-2)),
    "2": lambda: stack.pop(),
    "00": lambda: set_counter(stack[-1]),
    "01": lambda: stack.append(len(stack)),
    "02": lambda: stack.append(input()),
    "10": num_input,
    "11": lambda: stack.append(str(stack.pop())),
    "12": lambda: stack.append(int(stack.pop())),
    "20": lambda: set_counter(counter + 1),
    "21": lambda: set_counter(counter - 1),
    "22": lambda: print(stack.pop()),
    "000": lambda: stack.append(float(stack.pop())),
    "001": lambda: stack.append(-stack.pop()),
    "002": lambda: stack.append(not stack.pop()),
    "010": lambda: stack.append(stack.pop(-2) + stack.pop()),
    "011": lambda: stack.append(stack.pop(-2) - stack.pop()),
    "012": lambda: stack.append(stack.pop(-2) / stack.pop()),
    "020": lambda: stack.append(stack.pop(-2) // stack.pop()),
    "021": lambda: stack.append(stack.pop(-2) * stack.pop()),
    "022": lambda: stack.append(stack.pop(-2) % stack.pop()),
    "100": lambda: stack.append(math.factorial(stack.pop())),
    "101": lambda: stack.append(str(stack.pop(-2)) + str(stack.pop())),
    "102": lambda: stack.append(math.pow(stack.pop(-2), stack.pop())),
    "110": lambda: stack.append(math.sqrt(stack.pop())),
    "111": lambda: stack.append(math.log(stack.pop(-2), stack.pop())),
    "112": lambda: stack.append(~stack.pop()),
    "120": lambda: stack.append(stack.pop(-2) | stack.pop()),
    "121": lambda: stack.append(stack.pop(-2) & stack.pop()),
    "122": lambda: stack.append(stack.pop(-2) << stack.pop()),
    "200": lambda: stack.append(stack.pop(-2) >> stack.pop()),
    "201": lambda: stack.append(stack.pop(-2)[stack.pop()]),
    "202": lambda: stack.append(str(stack.pop(-2)) * stack.pop()),
    "210": lambda: stack.append(counter),
    "211": lambda: set_counter(stack.pop()),
    "212": lambda: stack.extend(list(str(stack.pop()))),
    "220": flip_ends,
    "221": lambda: stack.append(len(stack[-1])),
    "222": lambda: print(stack[-1]),
    "0000": lambda: stack.reverse(),
    "0001": lambda: stack.sort(),
    "0002": lambda: stack.append(stack[counter]),
    "0010": lambda: stack.append(stack[stack.pop()]),
    "0011": 0,
    "0012": 0,
    "0020": lambda: stack.append(sum(n for n in stack if isinstance(n, numbers.Number))),
    "0021": lambda: stack.append(functools.reduce(lambda x, y: x*y, [n for n in stack if isinstance(n, numbers.Number)], 1)),
    "0022": 0,
    "0100": lambda: (backburner.extend(stack), clear_stack()),
    "0101": lambda: reload_stack(True),
    "0102": lambda: reload_stack(False),
    "0110": lambda: backburner.append(stack.pop()),
    "0111": lambda: backburner.append(list(stack.pop())),
    "0112": lambda: stack.pop().split(stack.pop()),
    "0120": lambda: stack.append(backburner[-1]),
    "0121": lambda: (lambda depth=stack.pop(): (set_stack(stack[-depth:]), backburner.append(stack[:depth])))(),
    "0122": lambda: (lambda depth=stack.pop(): (set_stack(stack[:-depth]), backburner.append(stack[depth:])))(),
    "0200": lambda: set_stack([stack.pop().join(stack)]),
    "0201": lambda: set_stack(["".join(stack)]),
    "0202": lambda: (lambda depth=stack.pop(-2): set_stack(stack[-depth:] + [stack.pop().join(stack[:depth])]))(),
    "0210": lambda: (lambda depth=stack.pop(): set_stack(stack[-depth:] + ["".join(stack[:depth])]))(),
    "0211": 0,
    "0212": 0,
    "0220": lambda: stack.append(stack.pop().split(stack.pop())),
    "0221": lambda: stack.append(stack.pop().split(", ")),
    "0222": 0,
    "1000": lambda: stack.append(is_prime(stack[-1])),
    "1001": lambda: stack.append((lambda s=stack.pop(): s == s[::-1])()),
    "1002": lambda: stack.append(1 / stack.pop()),
    "1010": lambda: stack.append(stack.pop() - 1),
    "1011": lambda: stack.append(stack.pop() + 1),
    "1012": lambda: stack.append(stack.pop() * 2),
    "1020": lambda: stack.append(stack.pop() / 2),
    "1021": lambda: stack.append(stack.pop() ** 2),
    "1022": lambda: float("." + str(stack.pop())),
    "1100": lambda: stack.append(stack.pop() == stack.pop()),
    "1101": lambda: stack.append(stack.pop() != stack.pop()),
    "1102": lambda: stack.append(stack.pop() > stack.pop()),
    "1110": lambda: stack.append(stack.pop() < stack.pop()),
    "1111": lambda: stack.append(stack.pop() >= stack.pop()),
    "1112": lambda: stack.append(stack.pop() <= stack.pop()),
    "1120": lambda: stack.append(stack.pop() in stack),
    "1121": lambda: stack.append(stack.pop() in backburner),
    "1122": lambda: stack.append(stack.pop() == counter),
    "1200": lambda: stack.append(stack.pop() in stack.pop()),
    "1201": lambda: stack.append(stack.pop(-2).find(stack.pop())),
    "1202": 0,
    "1210": 0,
    "1211": 0,
    "1212": lambda: stack.append(stack.pop().lower()),
    "1220": lambda: stack.append(stack.pop().upper()),
    "1221": lambda: stack.append(ord(stack.pop())),
    "1222": lambda: stack.append(chr(stack.pop())),
    "2000": lambda: stack.append(math.floor(stack.pop())),
    "2001": lambda: stack.append(math.ceil(stack.pop())),
    "2002": lambda: stack.append(round(stack.pop())),
    "2010": lambda: stack.append(abs(stack.pop())),
    "2011": 0,
    "2012": 0,
    "2020": lambda: stack.append(len(stack.pop())),
    "2021": 0,
    "2022": 0,
    "2100": lambda: stack.append(min(stack)),
    "2101": lambda: stack.append(max(stack)),
    "2102": lambda: stack.append(stack.count(stack.pop())),
    "2110": lambda: stack.append(sum(stack) / len(stack)),
    "2111": 0,
    "2112": 0,
    "2120": 0,
    "2121": 0,
    "2122": 0,
    "2200": lambda: stack.append(stack.pop(-3).replace(stack.pop(-2), stack.pop())),
    "2201": lambda: stack.append(stack.pop(-3).replace(stack.pop(-2), stack.pop(), 1)),
    "2202": lambda: stack.append(stack.pop(-2).replace(stack.pop(), "")),
    "2210": lambda: stack.append(stack.pop(-2).replace(stack.pop(), "", 1)),
    "2211": 0,
    "2212": lambda: stack.append(eval(stack.pop())),
    "2220": lambda: stack.append(eval(input())),
    "2221": lambda: print(stack[-1]),
    "2222": lambda: error()
}

def run_cmd(name):
    global stack, counter, backburner

    state = {
        "stack": list(stack),
        "counter": counter,
        "backburner": list(backburner)
    }

    # TODO: unknown command

    try:
        commands[name]()
    except IndexError:
        stack = state["stack"]
        counter = state["counter"]
        backburner = state["backburner"]

class AST:
    pass

class Main(AST):
    def __init__(self):
        self.nodes = []

class Do(AST):
    def __init__(self, node):
        self.node = node

class If(AST):
    def __init__(self, first, second):
        self.first = first
        self.second = second

class Literal(AST):
    def __init__(self, val):
        self.val = val

class Command(AST):
    def __init__(self, val):
        self.val = val

class Parser:
    def __init__(self, lexer):
        self.lexer = lexer
        self.token = None

    def parse(self):
        pgm = Main()
        self.token = self.lexer.read()

        while self.token is not None and self.token.type != END and self.token.type != ELSE:
            if self.token.type == DO:
                pgm.nodes.append(Do(self.parse()))

            elif self.token.type == NUMBER or self.token.type == STRING:
                pgm.nodes.append(Literal(self.token.val))

            elif self.token.type == IF:
                first = self.parse()

                if self.token.type == ELSE:
                    second = self.parse()
                else:
                    second = None

                pgm.nodes.append(If(first, second))

            elif self.token.type == COMMAND:
                pgm.nodes.append(Command(self.token.val))

            self.token = self.lexer.read()

        return pgm

class Interpreter:
    def __init__(self, tree):
        self.tree = tree

    def visit(self, node):
        method_name = "visit_" + type(node).__name__
        visitor = getattr(self, method_name.lower())
        return visitor(node)

    def interpret(self):
        self.visit(self.tree)

    def visit_main(self, node):
        for each in node.nodes:
            self.visit(each)

    def visit_do(self, node):
        while counter:
            self.visit(node)

    def visit_if(self, node):
        if stack[-1]:
            self.visit(node.first)
        elif node.second:
            self.visit(node.second)

    def visit_literal(self, node):
        stack.append(node.val)

    def visit_command(self, node):
        run_cmd(node.val)

if source == "":
    with open("info.txt") as f:
        info = f.read()

    print(info)
else:
    main = Parser(Lexer(source)).parse()

    interpreter = Interpreter(main)
    interpreter.interpret()

    try:
        sys.exit(stack[-1])
    except IndexError:
        pass


Python 3, 21 bytes
lambda*l:sum(l)/2in l

If two numbers add to the other, the sum of all three will be double that other number, so half the sum will be an element of the list. Python 3 is needed to avoid floor-division, unless the numbers are given like 3.0 rather than 3.


J, 100

z=:"."0@":@(+/)^:9@(64-~a.i.])@(#~' '&i.)"1
f=:*@-/"2@(z@((]#~]i.~{.@\:~)"1^:([:=/z))){'STALEMATE'&,

runs like this:

f 'NO',:'ZOO'
NO
f 'CAN',:'BAT'
CAN
f 'FAT',:'BANANA'
FAT
f 'ONE',:'ONE'
STALEMATE

it doesn't yet accept input exactly as asked.


Write a function/method that takes in a string and spells that word out using the NATO Phonetic Alphabet. Titlecase optional

sfk, 78 59 57 bytes

+filt
+spell -nato
+xed _ph_f_ _et_ett_ _-__ "*: [keep]""

Try it online!

Just use the right tool.

Output is the phonetics separated by one or more spaces.


J, 26 bytes
_(]+1-1</@(=],+./)q:)^:_>:

Try it online!
I started with the "do-until" idiom f^:g^:_ with g boolean (apply f while g is true), but soon realized that the "find next integer" can be written in a single fixpoint (]+1-g)^:_. The only problem is that we don't have a straightforward/more golfy way to express the boolean negation of g other than 1-g.
How it works
_(]+1-1</@(=],+./)q:)^:_>:  NB. Input: n
                        >:  NB. n+1
_(                  )^:_    NB. Fixpoint with left arg of _ (infinity)...
                  q:    NB. (_ q: n) gives prime exponents including zeros
                        NB. _ q: 700 -> 2 0 2 1 (2^2 * 5^2 * 7^1)
          ( ],+./)      NB. Append GCD of ^ to itself
      1    =            NB. Test if each number equals 1 (gives boolean vector)
       </@   NB. Test if the only 1 is the last item
  ]+1-       NB. Negate the condition and add to the input number


Mathematica, 71 bytes
(t=s=1;While[t<=#,If[++s~Mod~CarmichaelLambda@s==1&&!PrimeQ@s,t++]];s)&

Try it online!
50->1461241  Try it online!


Calculate the bounded cumulative sum of a vector

CJam, 16 15 bytes

l~f{\T++$1=:T}`

Try it online

This takes the list as first argument, and the pair of upper/lower limit as a second 2-element list. Example input:

[1 4 3 -10 3 2 2 5 -4] [6 -2]

The latest version saves 1 byte by sorting the 3 values, and taking the middle value, instead of using a max and min operation. This was also used in Jakube's solution, as well as suggested by Martin.

Explanation:

l~    Get and parse input. This leaves the value and bounds lists on the stack.
f{    Apply block with value (the bounds list).
  \     Swap new value to top.
  T     Get previous value from variable T (which is default initialized to 0).
  +     Add new value and previous value.
  +     Append new value to bounds list, producing a 3 value list.
  $     Sort it...
  1=    And take the middle value.
  :T    Store in variable T for next iteration.
}     End of apply loop.
`     Convert list to string.


Pyth - 26 25 bytes
Very straightforward, maybe I can golf the filtering.
fhhT_m+hB/xrdZ\x2@"RL"}\x

Try it online here.


J, 15

|:>'\S+| 'rxall

Usage:

   |:>'\S+| 'rxall 'Hello, World! My name is Foo.'
H W M n i F
e o y a s o
l r   m   o
l l   e   .
o d
, !