Pyth, 20 24 bytes
My first attempt on Pyth :)
Jcw;FG.ptJI:hJj".*"G0jdG

How it works:
Jcw;FG.ptJI:hJj".*"G0jdG
Jcw                         assign("J",chop(input()))
    FG.ptJ                  for G in permutations(tail(J)):
          I:hJj".*"G0        if match(head(J),join(".*",G)):
                     jdG      print(join(" ",G))

Notes: it takes a long time in the third example (dababbabadbaccbcbaaacdacdbdd aa bb cc dd ba ba ba ab ac da db dc).


Ruby, 125
anonymous function, prints to stdout.
RevB: golfed, but a bug fix brought it back to the same length as before.
->x,y,z{72.times{|i|v=y-i/9;u=x-i%=9
e=u*u+v*v
$><<(i<8?e<1?z:[r=0==v*u,b=u*u==v*v,b|r,3>e,5==e]["RBQKN"=~/#{z}/]??*:?.:$/)}}

Prints each of the 64 squares + 8 newlines = 72 characters individually.
Relies on e, the square of the Euclidean distance between the current square and the given coordinates for checking king moves and knight moves (and also for printing the piece value z when the Euclidean distance is zero.)
Ungolfed in test program
f=->x,y,z{                         #x,y,character
  72.times{|i|                     #8 rows of (8 chars + newline) = 72 chars
    v=y-i/9;                       #vertical diff between y coord and current square
    u=x-i%=9                       #horizontal diff between x coord and current square. note i%=8
    e=u*u+v*v                      #square of euclidean distance
    $><<(                          #$> is stdout. send to it....
      i<8?                         #if not the newline column,
        e<1?z:                       #if the euclidean distance is 0, print the symbol for the piece, else
        [r=0==v*u,                   #TRUE if v or u is 0 (rook)
        b=u*u==v*v,                  #TRUE if abs(u)==abs(v) (bishop)
        b|r,                         #TRUE if either of the above are true (queen)
        3>e,                         #TRUE if e == 1 or 2 (king)
        5==e                         #TRUE if e == 5 (knight)
        ]["RBQKN"=~/#{z}/]??*:?.:    #select value from array corresponding to piece and print * or . accordingly
      $/                           #if newline column, print a newline
    )
  }
}

x=gets.to_i
y=gets.to_i
z=gets.chomp
f[x,y,z]


GolfScript 28 characters
{2{base}:|~4|43691-~256|~\}%

Equivalent version without obfuscating optimization:
{2base 4base 43691-~256base~\}%

The code accept input as an array of integers, and return ditto.
For each number in the array the number is converted to base 2 array form, it is then converted back to a number as if it was base 4, this has the effect of spacing out the bits with a 0 in between each. 43691 is then subtracted from the number, and the result is binary inverted, this is equivalent to subtracting the number from 43690 (43690 = 0b1010101010101010). The number is then split into two parts by converting it to a base 256 array, the array is decomposed and the order of the two resulting numbers is inverted.
Example input:
[1 2 3 241 242 243]

Example output:
[169 170 166 170 165 170 169 85 166 85 165 85]


Python 2 - 216
My first shot, might be some stuff to take out, but my brain hurts, so it's good enough for now
x=raw_input()
for l in range(5):print'  '.join((' '*7+'|   | |  ||| || '+'|'*7+'__|'+'_'*7)[[7*(4-l<n%6+n/6)+(n>5)*(l<10-n)-(l==10-n),n%6+n/6+(l<1)*(n>5)*(12-n)][(len(x)-i)%2]*5:][:5]for i,n in enumerate(map(int,x)))


APL, 1 char

I know it doesn't fit the (revised) requirements, but it's too good not to post:

⌹

Symbol "domino" ⌹ (division ÷ inside a rectangle) performs matrix division, therefore it can solve any system of linear equations. You just have to put it between the constant term vector and the matrix with the other terms:

      8 ¯11 ¯3 ⌹ ⊃(2 1 ¯1)(¯3 ¯1 2)(¯2 1 2)
2 3 ¯1

(if you want to try it on TryApl, ⊃ is ↑)


CJam, 55 50 48 47 bytes

Encoder, 24 22 21 bytes

l$:L4m*{$L|L=},rc'0-=

Try it online.

Decoder, 31 28 27 26 bytes

4_m*{$4,|4,=},l_$_|f#a#'0+

Try it online.


Convert a logical expression to conjunctive normal form

You're going to hate me....

Mathematica, 23 bytes

#~BooleanConvert~"CNF"&

The input will use True and False instead of ⊤ and ⊥, but otherwise will look very similar to the notation of the question: all of the characters ¬, ⇒, ⇔, ∧, and ∨ are recognized in Mathematica (when input with UTF-8 characters 00AC, F523, 29E6, 2227, and 2228, respectively), and parentheses act as you would expect.

By default, the output will use Mathematica's preferred symbols: for example, the last test case will output (! P || ! Q || R) && (! P || Q || ! R) instead of ((¬ P) ∨ ((¬ Q) ∨ R)) ∧ ((¬ P) ∨ (Q ∨ (¬ R))). However, changing the function to

TraditionalForm[#~BooleanConvert~"CNF"]&

will make the output look pretty and conforming to these usual symbols:


05AB1E, 11 bytes

žh.r3£ûÁÂ)Ω

Try it online!

Explanation

žh            # push "0123456789"
  .r          # random shuffle
    3£        # take the first 3
              # EX: 152
      û       # palendromize
              # EX: 15251
       Á      # rotate right
              # EX: 11525
        Â)    # pair with its reverse
              # EX: [11525, 52511]
          Ω   # pick one at random


PowerShell v4+, 160 bytes

param($a)iwr (((iwr "google.com/search?tbm=isch&q=$($a-replace' ','+')+glamour+shot").links|?{$_.innerhtml-like"*$a*"})[0].innerhtml-split'"')[3] -outf "$a.jpg"

Takes input $a as a string. Does an Invoke-WebRequest (iwr) to the appropriate Google location, using inner-string script block to -replace spaces with + in the input string. We take the .links of that, where the .innerhtml is -like our input string. That yields the links with the proper thumbnail description. Take the first [0] one of those, take its .innerhtml and -split it on quotations. The fourth [3] element is the text inside the img src=" portion, so we do another iwr on that, specifying -outfile to be $a.jpg in the local folder. Since these are just the Google generated thumbnails, they're guaranteed to be jpg.


JavaScript (ES6),  48 47 44 43  42 bytes

m=>31^'311'[parseInt(m[1]+m[2],34)*3%49%8]

Demo

let f =

m=>31^'311'[parseInt(m[1]+m[2],34)*3%49%8]

;(
  'JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC,' +
  'JANUARY,FEBRUARY,MARCH,APRIL,MAY,JUNE,JULY,AUGUST,SEPTEMBER,OCTOBER,NOVEMBER,DECEMBER'
).split`,`
.forEach(m => console.log(m, '->', f(m)))

How?

These operations lead to a lookup table of 8 entries, which would not be very interesting if the values were randomly distributed. But any result greater than 2 is mapped to 31 days. Therefore, only the first 3 entries need to be stored explicitly.

Month | [1:2] | Base 34 -> dec. | * 3  | % 49 | % 8 | Days
------+-------+-----------------+------+------+-----+-----
  JAN |    AN |             363 | 1089 |   11 |   3 |  31
  FEB |    EB |             487 | 1461 |   40 |   0 |  28
  MAR |    AR |             367 | 1101 |   23 |   7 |  31
  APR |    PR |             877 | 2631 |   34 |   2 |  30
  MAY |    AY |              10 |   30 |   30 |   6 |  31
  JUN |    UN |            1043 | 3129 |   42 |   2 |  30
  JUL |    UL |            1041 | 3123 |   36 |   4 |  31
  AUG |    UG |            1036 | 3108 |   21 |   5 |  31
  SEP |    EP |             501 | 1503 |   33 |   1 |  30
  OCT |    CT |             437 | 1311 |   37 |   5 |  31
  NOV |    OV |             847 | 2541 |   42 |   2 |  30
  DEC |    EC |             488 | 1464 |   43 |   3 |  31


C (451 bytes)

Uses only squared lengths and slopes.

p[2],q[2],r[2];z(c){char*y[]={"Line","Point","Isosceles ","Equilateral ","Scalene ","Right","Oblique ","Acute","Obtuse"};printf(y[c]);}d(int*a,int*b){int c=*a++-*b++,e=*a-*b;return c*c+e*e;}main(){scanf("%d%d%d%d%d%d",p,p+1,q,q+1,r,r+1);int a=d(p,q),b=d(q,r),c=d(r,p),e=!a+!b+!c,f=(a==b)+(b==c)+(c==a),g=a>b&&b>c?a:b>c?b:c,h=g^a?g^b?a+b:c+a:b+c;e?z(e/2):(1[q]-1[p])*(*r-*q)^(1[r]-1[q])*(*q-*p)?f?z(2+f/2),f-1&&z(2):z(4),h^g?z(6),z(7+(h<g)):z(5):z(0);}

Ungolfed (and ternary operator replaced with if/else):

int p[2],q[2],r[2];

void print(c){
    char *y[]={"Line","Point","Isosceles ","Equilateral ","Scalene ","Right","Oblique ","Acute","Obtuse"};
    printf(y[c]);
}
squared_distance(int *a,int *b){
    int c = *a++ - *b++, e = *a - *b;
    return c*c+e*e;
}
main(){
    scanf("%d%d%d%d%d%d",p,p+1,q,q+1,r,r+1); // read in coordinates
    int a = squared_distance(p,q),b = squared_distance(q,r),c = squared_distance(r,p),
    e=!a+!b+!c, // number of sides of length 0
    f=(a==b)+(b==c)+(c==a), // number of equal-length pairs
    g = a > b && b > c ? a : (b > c ? b : c), // longest side
    h = g != a ? g != b ? a + b : c + a : b + c; // sum of squares of length of other two sides
    if(e)
        print(e/2); // 1 side of len 0: line, 3 sides: point
    // comparing slopes PQ and QR
    else if((q[1]-p[1])*(*r-*q) != (r[1]-q[1])*(*q-*p)){ // not line
        if(f){
            print(2+f/2); // 1 pair of equal length sides: isosceles, 3: equilateral
            if(f-1) print(2); // equilateral therefore also isosceles
        }else print(4); // 0: scalene
        if(h!=g){ // a^2+b^2!=c^2: not right
            print(6); // oblique
            print(7+(h<g)); // a^2+b^2<c^2:obtuse, acute otherwise
        }else print(5); // right
    }else
        print(0); // line
}

Input (through stdin) Format: x y x y x y

ex. 0 0 1 1 2 0 for Isosceles Right


JavaScript ES6, 16

n=>n%1?0:~-n*n/2

Test

f=n=>n%1?0:~-n*n/2

function test()
{
  var i=I.value
  O.textContent=f(i)
}
<input id=I oninput=test()>


The Professor's base building number converter

Mathematica (REPL environment), 858 total bytes

Here is the 86-byte code snippet for the digit 9:

1;ValueQ@a||(a=0;b=3);a=10a+9;b++;FromDigits[a~IntegerDigits~MixedRadix@Range[b,1,-1]]

The code snippets for the digits 1 through 8 are identical, except that the 9 is replaced by the appropriate digit. The code snippet for the digit 0 is identical, except that +9 is simply deleted.

a~IntegerDigits~MixedRadix@Range[b,1,-1] computes the list of the factorial-number-system digits of a, as long as b is at least as large as the number of digits; FromDigits converts that list of digits to a regular base-10 integer for the purposes of output. (If any of the list elements exceeds 9, something funny happens.)

In Mathematica's REPL environment, computations can be terminated with semicolons to suppress the output; so only the last output in a semicolon-separated chain will be displayed. We recursively define the integer a designated by the snippets, and also a bound b on the number of factorial-system digits needed. The command ValueQ@a||(a=0;b=3) initializes these variables if they're uninitialized (i.e., in the first snippet) and leaves them alone otherwise; then a=10a+9;b++ carries out the recursion. Finally, the initial 1; is for gluing the snippets together: it multiplies intermediate computations by 1 (which we never see anyway).


Java

I decided to add another entry since this is completely different from my first one (which was more like an example).

This program calculates the average of an array entered by the user...

import java.util.Scanner;

public class Numbers {
    public static double getSum(int[] nums) {
        double sum = 0;
        if(nums.length > 0) {
            for(int i = 0; i <= nums.length; i++) {
                sum += nums[i];
            }
        }

        return sum;
    }

    public static double getAverage(int[] nums) { return getSum(nums) / nums.length; }
    public static long roundAverage(int[] nums) { return Math.round(getAverage(nums)); }

    private static void beginLoop(int[] nums) {
        if(nums == null) {
            return;
        }

        long avg = roundAverage(nums);
        System.out.println("enter nums for average");
        System.out.println("example:");
        System.out.print("array is " + nums[0]);
        for(int i = 1; i <= nums.length; i++) {
            System.out.print(", " + nums[i]);
        }

        System.out.println();
        System.out.println("avg is " + avg);
    }

    private static int[] example = { 1, 2, 7, 9, };

    public static void main(String[] args) {
        boolean done = false;
        while(!done) {
            try {
                int[] nums = example;
                beginLoop(nums);

                nums = getInput();
                if(nums == null) {
                    done = true;
                } else {
                    System.out.println("avg is " + getAverage(nums));
                }
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    }

    static int[] getInput() {
        Scanner in = new Scanner(System.in);
        System.out.print("enter length of array to average or 0 to exit: ");
        int length = in.nextInt();
        if(length == 0) {
            return null;

        } else {
            int[] nums = new int[length];
            for(int i = 0; i <= nums.length; i++) {
                System.out.print("enter number for index " + i + ": ");
                nums[i] = in.nextInt();
            }
            return nums;
        }
    }
}

...or does it?

java.lang.ArrayIndexOutOfBoundsException: 4
    at Numbers.getSum(Numbers.java:8)
    at Numbers.getAverage(Numbers.java:15)
    at Numbers.roundAverage(Numbers.java:16)
    at Numbers.beginLoop(Numbers.java:23)
    at Numbers.main(Numbers.java:42)
java.lang.ArrayIndexOutOfBoundsException: 4
    at Numbers.getSum(Numbers.java:8)
    at Numbers.getAverage(Numbers.java:15)
    at Numbers.roundAverage(Numbers.java:16)
    at Numbers.beginLoop(Numbers.java:23)
    at Numbers.main(Numbers.java:42)
java.lang.ArrayIndexOutOfBoundsException: 4
    at Numbers.getSum(Numbers.java:8)
    ...


CJam, 19 17 15 bytes

{s"_~"+N*""-}_~

Try it online! Try the rotation.

Explanation

{s"_~"+  e# Standard quine framework. Puts a string representation of the entire
         e# program on the stack.
  N*     e# Riffle linefeeds into the string, which is effectively a clockwise
         e# rotation by 90°.
  ""-    e# Does nothing.
}_~

In the rotated code, we've got linefeeds everywhere:

{
s
"
_
~
"
+
N
*
"
"
-
}
_
~

As Lynn noticed on Dom's earlier quine challenge inserting linefeeds actually still forms valid quine, because the linefeeds inside the block will just be retained verbatim anyway, and there will also be linefeeds in the "_~" string to make those two characters at the end show up on their own line. So {s"_~"+...}_~ (with linefeeds) is still a valid quine framework (although there'll be an additional linefeed at the end of the string). N* now inserts even more linefeeds into that string, but we don't really care: because now ""- has a linefeed inside that string so it actually removes all linefeeds from the program representation. So we end up with the horizontal form of the code again, undoing the rotation.


Number of characters in an integer's name

C : 117 bytes

(From kind suggestion of @edc65 and @ColeCameron)

f(a){char *d="0446554665366887798803665557667";printf("%d : %d",a,(a?a<20?d[a]-(a<10):d[a%10]+d[20+a/10]-48:52)-48);}

Live example

C++ : 159 bytes 178 bytes

int f(int a){char *d[3]={"0446554665","0366555766","3668877988"};printf("%d : %d",a,(a?a<20?a>9?d[2][a-10]:d[0][a]-1:a>99?55:d[0][a%10]+d[1][a/10]-48:52)-48);}

Live example

Explanation

Explanation from previous code, with all suggestions from comments incorporated.

int f(int a) {  // Return int to save a byte, a is the argument

    int d[3][10]={
             {0,4,4,6,5,5,4,6,6,5},  // Length of "", "-one", "-two", "-three" etc.
             {0,3,6,6,5,5,5,7,6,6},  // Length of "", "ten", "twenty", etc.
             {3,6,6,8,8,7,7,9,8,8}   // Length of "ten", "eleven", etc.
           };
    printf ("%d : %d", a,
               a
                 // If a is not zero
                 ? a < 20
                     // If a is less than 20
                     ? a > 9
                         // a is in range 10-19
                         ? d[2][a-10]
                         // a is in range 0-9
                         : d[0][a]-1  // Subtract one as '-' is not required
                     // If a is >= 20
                     : a > 99
                         // If a is 100
                         ? 7  // Length of hundred
                         // a is between 20-99
                         : d[0][a%10] + d[1][a/10]  // unit digit length + tens digit length
                 // If a is zero
                 : 4
            );
}


Brachylog (2) → Post correspondence problem, 9 bytes

~h=∋ᵐ\cᵐ=

Try it online!

Input is a list of lists of strings. (In the Post correspondence problem as defined on Wikipedia, the inner lists have two elements each, although this program can actually handle a generalisation to any number of elements.) This program brute-forces solutions to the problem, in order of length, until a solution is found. The Post correspondence problem is known to be able to simulate a Turing-machine, and thus brute-forcing solutions to it is Turing complete. If run as a function, rather than a program, it actually produces meaningful output as well.

The program in the TIO link above is [["a","baa"],["ab","aa"],["bba","bb"]], which I copied from Wikipedia. The solution (which the program finds fairly quickly) is ["bbaabbbaa","bbaabbbaa"].

Explanation

This is pretty much just a direct translation of the Post correspondence problem to Brachylog.

~h=∋ᵐ\cᵐ=
~h         Find {the shortest possible} list which starts with {the input}
  =        and for which all elements are equal
   ∋ᵐ      such that taking an element of each element,
     \cᵐ   and concatenating elements in corresponding positions,
        =  produces a list all of whose elements are equal.

Basically, we create a list that's repeated copies of the input (as few as possible, meaning that we don't miss any possibilities when brute-forcing), take one element from each copy, then concatenate corresponding elements (as in the Post correspondence problem).


Python 3, 98

lambda l:''.join(x*('='!=x[1:-1])for x in l).translate({'='!=x[1:-1]or ord(x[0]):x[2:]for x in l})

This lambda function receives a list of strings (input) and returns a string (the decoded message).

Examples:

>>> f(['ta', 'y=s', 'y', 'a=e', 'b=t', 'b', ' ', 'j', 'j=1'])
'test 1'
>>> f(['z=p', 'zota', 'g=e', 'yugkb', 'y=t', 'u=o', 'k=s', 'li', 'fg', 'b=='])
'potatoes=life'
>>> f(['p', '=', '==n', 'ot', 'p=a', 'hiz', 'i=e', 'z=r'])
'another'


Jelly, 11 10 bytes
-1 byte by @Dennis
×⁵S€żị@€ỤỤ

Uses the fact that lists are lexicographically ordered.
This is a dyadic link that takes two arguments plus one input. The left argument is x, the rankings. The right argument is y, the tiebreaker. The input is the weights.
×⁵S€żị@€ỤỤ         Dyadic function. Inputs: x, y
×⁵                 Vectorized multiply x by the weights.

  S                Sum the rows.
                   This is the weighted ordering.
   ż               Zip with
    ị@€             x indexed at y, mapped over x
       ỤỤ          and compute the inverse of the permutation vector that sorts that.
                   A list is sorted by its inverse permutation, so
                   this is the inverse of the inverse; i.e. the original permutation.

Try it here.


Mathematica, 459 392 bytes

f=(d=ImageData@Import@#/.{a_,_,_}:>a;(For[a={};b={#&@@d~Position~1},b!={},c=#&@@b;b=Rest@b;d[[##&@@c]]=0;a~AppendTo~c;If[Extract[d,c+#]==1,b=b⋃{c+#}]&/@{e={1,0},-e,e={0,1},-e}];m=1.Mean@a;m=#-m&/@a;n=Count[Partition[Norm/@SortBy[m,ArcTan@@#&],300,1,1],l_/;l[[150]]==Max@l];(d[[##&@@#]]=Round[n^.68])&/@a)&/@Range@4;Image[d/.n_Integer:>{{0,0,0},,{0,1,0},{1,0,0},,,,{1,1,0},{0,0,1}}[[n+1]]])&

Ungolfed:

f = (
 d = ImageData@Import@# /. {a_, _, _} :> a;
 (
    For[a = {}; b = {# & @@ d~Position~1},
     b != {},
     c = # & @@ b;
     b = Rest@b;
     d[[## & @@ c]] = 0;
     a~AppendTo~c;
     If[Extract[d, c + #] == 1,
        b = b ⋃ {c + #}] & /@ {e = {1, 0}, -e, e = {0, 1}, -e}
     ];
    m = 1. Mean@a; m = # - m & /@ a;
    n =
     Count[Partition[Norm /@ SortBy[m, ArcTan @@ # &], 300, 1, 1],
      l_ /; l[[150]] == Max@l];
    (d[[## & @@ #]] = Round[n^.68]) & /@ a
    ) & /@ Range@4;
 Image[d /.
   n_Integer :> {{0, 0, 0}, , {0, 1, 0}, {1, 0, 0}, , , , {1, 1,
       0}, {0, 0, 1}}[[n + 1]]]
) &

I could save 6 more bytes by turning m=1.Mean@a;m=#-m&/@a; into m=#-Mean@a&/@a;, but that significantly blows up execution time, which is annoying for testing. (Note, that this is two optimisations: pulling out the computation of Mean@a out of loop and using exact symbolic types instead of floating point numbers. Interestingly, the use of exact types is a lot more significant than computing the mean in every iteration.)

So this is approach number three:

Detect areas by flood-fill.
Find approximate centre of each area by averaging all pixel coordinates.
Now for all pixels in the shape let's plot distance from vs angle to that centre:

The triangle has 3 clear maxima, the square 4, the gear 16, and the circle has tons, due to aliasing fluctuations about the constant radius.
We find the number of maxima by looking at slices of 300 pixels (ordered by angle), and count the slices where the pixel at position 150 is the maximum.
Then we just colour all pixels depending on the number of peaks (the circle is anything over 16, and usually yields around 20 peaks, due to the size of the slices).

Just for the record, if I use Ell's idea, and simply sort the regions by largest distance between any pixel and centre, I can do this in 342 bytes:

f=(d=ImageData@Import@#/.{a_,_,_}:>a;MapIndexed[(d[[##&@@#]]=#&@@#2)&,SortBy[(For[a={};b={#&@@d~Position~1},b!={},c=#&@@b;b=Rest@b;d[[##&@@c]]=0;a~AppendTo~c;If[Extract[d,c+#]==1,b=b⋃{c+#}]&/@{e={1,0},-e,e={0,1},-e}];a)&/@Range@4,(m=Mean@#;Max[1.Norm[#-m]&/@#])&],{2}];Image[d/.n_Integer:>{{0,0,0},{0,0,1},{1,1,0},{1,0,0},{0,1,0}}[[n+1]]])&

But I do not intend to compete with that, as long as everyone else is using their own original algorithms, instead of golfing down those of others.


Python 3.

from random,sys import *
w=choice(*argv)
L=set(w)
a=10
while L and a:
 print(" ".join("_"if x in L else x for x in w),a)
 try:L-=set(input()[0])
 except:a-=1

I prefer this one though: longer but nicer.

import random
w=random.choice(list(open("/usr/dict/words")))[:-1]
L=set(w)
a=10
while L and a:
 print(" ".join("_"if x in L else x for x in w),a)
 try:L.remove(input()[0])
 except:a-=1
print w


Python 3, 273, 489, 429  bytes

Rock:

r=['tie', 'lose', 'win'];s="i=input();t=[f'r={r[n:]+r[:n]};s={s!r};exec(s)'for n in[0,1,2]];print(i in t and r[i.find('t')//7]or t[0])";exec(s)

Try it online against itself!
Try it online against Paper!
Try it online against Scissors!
Try it online against rubbish!

Paper:

r=['win', 'tie', 'lose'];s="i=input();t=[f'r={r[n:]+r[:n]};s={s!r};exec(s)'for n in[0,1,2]];print(i in t and r[i.find('t')//7]or t[0])";exec(s)

Try it online against itself!
Try it online against Scissors!
Try it online against Rock!
Try it online against garbage!

Scissors:

r=['lose', 'win', 'tie'];s="i=input();t=[f'r={r[n:]+r[:n]};s={s!r};exec(s)'for n in[0,1,2]];print(i in t and r[i.find('t')//7]or t[0])";exec(s)

Try it online against itself!
Try it online against Rock!
Try it online against Paper!
Try it online against trash!

The same as the previous version, but check that the input exactly matches the source code of one of the programs.

Try it online (together)!

Old (invalid) version

Rock:

s="print(['tie','lose','win','s='+repr(s)+';exec(s)',''][input().find('ti')//7-1])";exec(s)

Paper:

s="print(['win','tie','lose','s='+repr(s)+';exec(s)',''][input().find('ti')//7-1])";exec(s)

Scissors:

s="print(['lose','win','tie','s='+repr(s)+';exec(s)',''][input().find('ti')//7-1])";exec(s)

Try it online!

Three almost identical programs (all with 91 bytes), the only difference is the order of the win/tie/lose, which each program uses the position of the 'tie' to determine the result from it's own ordering.

As pointed out, these programs are invalid, as they will only print out themselves if the input doesn't contain 'ti' (or the 'ti' is in a certain place).


Check if a pattern appears in a DNA sequence

Python 3, 125 bytes

import re,sys
a=sys.argv
s=re.sub
print([i+1 for i in range(len(a[1]))if re.match(s('N','[ACGT]',s('/','|',a[2])),a[1][i:])])


Determine the Winner of a Game of Australian Football

Jelly, 3 bytes
ḅ6M

A monadic Link accepting a list of lists of integers, [[g1,b1],[g2,b2]], which yields a list [1] or [2].
(Draws would yield [1,2])
...Or a full program printing 1 or 2.
Try it online! Or see the test-suite.
How?
ḅ6M - Link: list of lists of integers, X
 6  - literal six
ḅ   - convert (X) from base 6 (vectorises)
  M - maximal indices


Count the words in a text and display them

grep and coreutils  44  42

grep -io '[a-z0-9]*'|sort|uniq -c|sort -nr

Test:

printf "This is a text and a number: 31." |
grep -io '[a-z0-9]*'|sort|uniq -c|sort -nr

Results in:

  2 a
  1 This
  1 text
  1 number
  1 is
  1 and
  1 31

Update

Use case-insensitive option and shorter regex. Thanks Tomas.


Matlab, 77 75

I just use the definition of the geometric median with a numerical minimization. In this case I make use of the Nelder-Mead simplex algorithm. It sould always converge as we try to find the minimum of a convex function (according to Wikipedia).

n=@(m)trace((m'*m).^.5);f=@(m)fminsearch(@(y)n(bsxfun(@minus,m,y)),m(:,1))

Old version:
    n=@(m)sum(diag(m'*m).^.5);f=@(m)fminsearch(@(y)n(bsxfun(@minus,m,y)),m(:,1))

The input format is a matix with the input vectors as columns, e.g:

m = [[2; 20; 3; 30],[20; 2; 20; 2],[1; 2; 3; 4]];


Python - 83 characters
Seems that we can take input from anywhere, so this takes input during execution, rather than from the command line, and uses Ejrb's suggestion to shorten it by 8.
s=map(len,raw_input().split())
c=0;exec'c+=1;print"%3d|"%c+"#"*s.count(c);'*max(s)

Python - 91 characters
This will fall over with quotes.
import sys;s=map(len,sys.argv[1:])
for i in range(1,max(s)+1):print"%3d|"%i+'#'*s.count(i)

Input:
> python hist.py Please write a specification rather than giving a single example which, solely by virtue of being a single example, cannot express the range of acceptable output styles, and which doesnt guarantee to cover all corner cases. Its good to have a few test cases, but its even more important to have a good spec.

Output:
  1|#####
  2|######
  3|#####
  4|##########
  5|######
  6|#############
  7|####
  8|#
  9|##
 10|#
 11|
 12|
 13|#


Pascal, 249 247 233 bytes

Well, this is Pascal's alternating triangle.

1 byte saved thanks to @Mr.Xcoder

function f(n,k:integer):integer;begin if((k<1)or(k>n)or(n=1))then f:=n mod 2 else if n mod 2=0then f:=f(n-1,k-1)*f(n-1,k)else f:=f(n-1,k-1)+f(n-1,k)end;
procedure g(n:integer);var k:integer;begin for k:=1to n do write(f(n,k),' ')end;

Try it online!


Wolfram Language (Mathematica), 72 bytes

Pick[Flatten[(i=IntegerDigits)/@Table[#,s=Length[p=#~i~2]]][[;;s]],p,1]&

Try it online!

Here is the plot of the first 30.000 such numbers

And here is the Logarithmic plot


JavaScript (ES6), 52 bytes

f=(n,t=0)=>t<n?f(n-++t,t):t.toString(36)+(n?f(n):'')

How?

Rather than explicitly computing Ti = 1 + 2 + 3 + … + i, we start with t = 0 and iteratively subtract t + 1 from n while t < n, incrementing t at each iteration. When the condition is not fulfilled anymore, a total of Tt has been subtracted from n and the output is updated accordingly. We repeat the process until n = 0.

Below is a summary of all operations for n = 100.

 n  |  t | t < n | output
----+----+-------+--------
100 |  0 | yes   | ""
 99 |  1 | yes   | ""
 97 |  2 | yes   | ""
 94 |  3 | yes   | ""
 90 |  4 | yes   | ""
 85 |  5 | yes   | ""
 79 |  6 | yes   | ""
 72 |  7 | yes   | ""
 64 |  8 | yes   | ""
 55 |  9 | yes   | ""
 45 | 10 | yes   | ""
 34 | 11 | yes   | ""
 22 | 12 | yes   | ""
  9 | 13 | no    | "d"
----+----+-------+--------
  9 |  0 | yes   | "d"
  8 |  1 | yes   | "d"
  6 |  2 | yes   | "d"
  3 |  3 | no    | "d3"
----+----+-------+--------
  3 |  0 | yes   | "d3"
  2 |  1 | yes   | "d3"
  0 |  2 | no    | "d32"

Test cases

f=(n,t=0)=>t<n?f(n-++t,t):t.toString(36)+(n?f(n):'')

console.log(f(1))   // 1
console.log(f(2))   // 11
console.log(f(3))   // 2
console.log(f(4))   // 21
console.log(f(5))   // 211
console.log(f(6))   // 3
console.log(f(100)) // d32
console.log(f(230)) // k5211
console.log(f(435)) // t
console.log(f(665)) // z731


GolfScript, 20 characters
~:x,2>{x\base.-1%=}?

A different approach with GolfScript other than Dennis'. It avoids the costly explicit loop in favour of a find operator. Try online.
~:x        # interpret and save input to variable x
,2>        # make a candidate list 2 ... x-1 (note x-1 is the maximum possible base)
{          # {}? find the item on which the code block yields true
  x\       # push x under the item under investigation
  base     # perform a base conversion
  .-1%     # make a copy and reverse it
  =        # compare reversed copy and original array
}?


JavaScript (ES6),  135 120  119 bytes
Saved 16 bytes thanks to @Shaggy!
Expects either an array of strings or a matrix of characters. Returns a matrix of characters.

a=>[...a,...a[0]].map((_,y,b)=>b.map((_,x)=>'\\/ '[(c=(a[~(x-=y+a.length)>>1]||0)[x+y-~y>>1])=='_|'[x&=1]|c=='L'?x:2]))

Try it online!


Mathematica, 96 94 89 bytes

StringReplace[#,n:DigitCharacter~Repeated~2/;(d=FromDigits@n)>0:>d~ElementData~"Symbol"]&

Mma has several datasets...


Dyalog APL, 31 32 bytes
{1⍳⍨+⌿∘.≡⍨{⍵/⍨~∧⌿⍵}¨⍵⊂⍨2>/∧⌿1,⍵}

⎕IO←0 to get indices starting with 0 (per OP), and which is anyway default in many APL systems.
1,⍵ prepend a column of white pixels (to ensure margin)
∧⌿ boolean for each column if all-white (vertical AND-reduction)
2>/ boolean at each character's left edge (pair-wise greater-than)
⍵⊂⍨ split into blocks beginning at each TRUE.
{…}¨ for each block
∧⌿⍵ boolean for each column if all-white (vertical AND-reduction)
⍵/⍨~ columns that are not [all-white]
∘.≡⍨ match each element to all elements
+⌿ number of blocks identical to each block (vertical plus-reduction)
1⍳⍨ index of first one (i.e. unique element)
Assumes the image is black (0) and white (1) pixels in the matrix I, and that there is at least one all-white pixel column between characters.
      f←{1⍳⍨+⌿∘.≡⍨{⍵/⍨~∧⌿⍵}¨⍵⊂⍨2>/∧⌿1,⍵}

"!I!!":
      ⊢I←6 12⍴(13/1),(22⍴0 1 1),(5/1),0,(8/1),(10⍴0 1 1),13/1
1 1 1 1 1 1 1 1 1 1 1 1
1 0 1 1 0 1 1 0 1 1 0 1
1 0 1 1 0 1 1 0 1 1 0 1
1 1 1 1 0 1 1 1 1 1 1 1
1 0 1 1 0 1 1 0 1 1 0 1
1 1 1 1 1 1 1 1 1 1 1 1
      f I
1

"mmnmm":
      ⊢I←7 31⍴(94/1),0 0,(∊0 1⌽¨2/⊂12⍴6↑1 0 1 1),0 1,(62⍴1 1 1,(⊢,⌽)(14⍴0 1)),33/1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 0 0 1 0 1 1 0 0 1 0 1 1 0 0 0 1 1 0 0 1 0 1 1 0 0 1 0 1 1 1
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1
1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
      f I
2


Brachylog, 4 bytes

It's always nice to see a challenge and know brachylog is gonna beat everyone.
Takes current classes as input and new classrooms as output; It will output true if it finds a way to fit the students, false otherwise

p≤ᵐ⊆

Explanation

The code has 3 parts of which the order actually doesn't matter

≤ᵐ --> projects each value to a value bigger/equal then input
⊆  --> input is a ordered subsequence of output
p  --> permutes the list so it becomes a unordered subsequence

Try it online!


Python 3, 69 68 bytes

-1 byte thanks to @WheatWizard

i=0
for c in input():
 i+=c==';'
 if'#'==c:print(end=chr(i%127));i=0

Try it online!


JavaScript (90 93)

function f(a,b){n=m=r=1;for(i=b;i>0;n*=-1){r+=n*m*Math.pow(i,a);m=m*i/(b-i--+1)}return--r}

http://jsfiddle.net/RDGUn/2/

Obviously, any math-based language such as APL will beat me because of syntax verbosity and lack of built-in mathematical constructs :)

Edit Also, I don't have any input-related functionality  except parameters passed into the function, not sure how to use standard input with JavaScript...

Edit: Move i-- into m=m* expression; move n*=-1 into for; start r=1 to  combine assignments and remove extraneous one on return. (save 3 chars)


05AB1E, 6 bytes
ćsžMм«

Try it online!
Explanation
       Input (e.g.). potato
ć      Head extract. otato, p
 s     Swap        . p, otato
  žM   Vowels      . p, otato, aeiou
    м  Remove      . p, tt
     « Concatenate . ptt

Implicit output    .


05AB1E, 51 38 bytes
-13 bytes thanks to Kevin Cruijssen!
',ð:#ʒ'-м€.ïß}D.ï≠ÅÏ'-¡¤LsнUʒX<›]˜Ùg1M

Try it online!
Explanation
                                      // Implicitly Read in multiline string
 ',ð:#                                //Swap commas with spaces and split on spaces
      ʒ'-м€.ïß}                       //Filter list to only those with - removed are numbers
               D                      //Duplicate
                .ï≠ÅÏ                 //For all the ones that aren't numbers (so the ranges)
                    '-¡               //Split on dashes
                       ¤L             //Generate list from 1 to the highest number
                         sнU          //Stick the lower number in the variable U
 ʒ®<›]                                //Filter out numbers less than the lower number
      ˜                               //deep flatten
        Ùg                            //Uniquify and count
          1M                          //Push 1 then output the largest number in the stack


Python 3, 80 bytes
Saved 1 byte thanks to Halvard Hummel and 1 byte thanks to Jonathan Allan.
import math
def f(*l):
 for k in 0,1:print(l[~k]//math.gcd(*l)*(~-l[k]*"-"+"|"))

Test it online!
lambda*l:"\n".join(l[0]*l[1]//math.gcd(*l)//k*(~-k*"-"+"|")for k in l)
import math

Test it online! (82 bytes - initial answer)
This is the best I could do in Python 2 (81 bytes). It seems like I cannot comment on that answer, I'll just post this here instead:
from fractions import*
l=a,b=input()
for k in l:print a*b/gcd(*l)/k*(~-k*"-"+"|")

Test it online!
First attempt here, probably sub-optimal!


Haskell, 357 306 277 251 228 224 188 185 180 bytes

A token-based parser with an explicit stack. (%) takes a token stack and a character and either pushes (opcode,defaultnumber) or (0,number) for ({[<, or pops topmost numbers and one opcode and pushes the answer for )}]>. Opcodes are encoded by a ascii enumeration hack.

Kudos to @ChristianSievers for his great answer that I borrowed some ideas from.

One-liner!

s%c|elem c"([<{",g<-div(fromEnum c)25=(g,[0,0,1,-1,1]!!g):s|(a,(o,n):b)<-span((==0).fst)s=(0,[foldr1(flip$[(+),quot,(-),(*)]!!(o-1))$snd<$>a,n]!!(0^length a)):b
snd.head.foldl(%)[]

Now with less error-handling!
Usage:

*Main> map (snd.head.foldl(%)[]) ["()","(()())","([][])","({}<>)","({}[])","[]","[[][]]","[()<>]","{()}","{([]<>)}"]
[0,0,-2,2,0,-1,0,-1,0,0]

Thanks @ChristianSievers for saving 14+3 bytes!

Thanks @Zgarb for saving some+4 bytes!


Jelly, 14 bytes

,þ%,ỊḄị“-|| ”Y

Try it online! or verify all test cases.

How it works

,þ%,ỊḄị“-|| ”Y  Main link. Left argument: w. Right argument: h

,þ              Pair table; yield a 2D array of all pairs [i, j] such that
                1 ≤ i ≤ w and 1 ≤ j ≤ h.
   ,            Pair; yield [w, h].
  %             Take the remainder of the element-wise division of each [i, j]
                by [w, h]. This replaces the highest coordinates with zeroes.
    Ị           Insignificant; map 0 and 1 to 1, all other coordinates to 0.
     Ḅ          Unbinary; convert each pair from base 2 to integer.
                  [0, 0] -> 0 (area)
                  [0, 1] -> 1 (top or bottom edge)
                  [1, 0] -> 2 (left or right edge)
                  [1, 1] -> 3 (vertex)
       “-|| ”   Yield that string. Indices are 1-based and modular in Jelly, so the
                indices of the characters in this string are 1, 2, 3, and 0.
      ị         At-index; replace the integers by the correspoding characters.
             Y  Join, separating by linefeeds.


Python 2 (384 368 365 348 347 bytes)

def c(s):
 s=s[:-6].replace('int','');k=0;d=dict(un=1,doe=2,tre=3,quattuor=4,quin=5,sex=6,septen=7,octo=8,novem=9,b=3,tr=4,quadr=5,qu=6,sext=7,sept=8,oct=9,non=10,dec=11,vig=21,trig=31,quadrag=41,quinquag=51,sexag=61,septuag=71,octog=81,nonag=91,cent=101)
 for p in(s!='m')*list(d)*2:
    if s.endswith(p):s=s[:-len(p)];k+=3*d[p]
 return 10**(k or 6)

(The if line is indented with a single tab, and the rest with single spaces.)

Here c('million') == 10**6 has to be a special case because 'novem' also ends in 'm'.

Examples:

c('million') == 10**6
c('trillion') == 10**12
c('quattuordecillion') == 10**45
c('novemnonagintillion') == 10**300
c('centillion') == 10**303

Thanks to Falko for obfuscating it down to 350 bytes.

For practice I tried rewriting this as a one-liner using lambdas. It's 404 398 390 384 380 379 bytes:

c=lambda s:(lambda t=[s[:-5].replace('gint',''),0],**d:([t.__setslice__(0,2,[t[0][:-len(p)],t[1]+3*d[p]])for p in 2*list(d)if t[0].endswith(p)],10**t[1])[1])(un=1,doe=2,tre=3,quattuor=4,quin=5,sex=6,septen=7,octo=8,novem=9,mi=2,bi=3,tri=4,quadri=5,qui=6,sexti=7,septi=8,octi=9,noni=10,deci=11,vii=21,trii=31,quadrai=41,quinquai=51,sexai=61,septuai=71,octoi=81,nonai=91,centi=101)


Ruby, 115 182 163 bytes

->s{z=('00'..'99').map{|x|x=~/[09]/||s[(x[1].ord+48).chr+x[0]]};(11..18).map &g=->x{z[x]||[x-11,x-9,x+z[x]=9,x+11].map(&g)};s=~/^([a-h][1-8])*$/&&(z[81,9]-[9])[8]}

Try it online!

Returns 1 for strong and nil for weak. (The +67 bytes was for taking into account "backtracking.")

->s{
 z=                             # this is the board
 ('00'..'99').map{|x|           # coordinates are described as y*10 + x
  x=~/[09]/||                   # truthy if out of bounds...
  s[(x[1].ord+48).chr+x[0]]     # ...or impassable
 }                              # now only the passable squares are falsey
 (11..18).map                   # for each x position at y=1,
  &g=->x{                       # call helper function on that square
   z[x]||                       # if the square is passable (i.e. falsey),
    [x-11,x-9,x+z[x]=9,x+11]    # mark it impassable by setting to 9 (truthy)
     .map(&g)                   # call helper recursively for each neighbor
  }
 s=~/^([a-h][1-8])*$/           # make sure the input was valid,
 &&(z[81,9]-[9])[8]             # and check that the last row was never reached
}

A few tricks that were used:

Instead of the numerical range 0..99, we use the string range '00'..'99' so that the number is automatically left-padded to 2 digits and stringified. This makes out of bounds checking very short -- match with regex /[09]/.
Inside the helper function, while building the list of new coordinates [x-11, x-9, x+9, x+11], we simultaneously assign z[x] to 9 in the process, which happens to be a truthy value (marking the square visited).
In the last line, we want to check that the array z[81,9] does not contain 9. We do this by removing all instances of 9 (z[81,9]-[9]), then asking for the 9th element of the resulting array ([8]). Since we know the array originally had 9 elements, if any were removed, we'll get nil, whereas if they all remained, we'll get the last element of the array (which happens to always be 1).


Mathematica 34 26

Besides the explicit search there is a nice convergent series:

n = 27

{i=√n//.i_:>n/⌈n/⌊i⌋⌉,n/i}

  {3, 9}

Three previous approaches with 34 characters:

{#,n/#}&@FixedPoint[n/⌈n/⌊#⌋⌉&,√n]

For[i=√n,i>(i=n/⌈n/⌊i⌋⌉),];{i,n/i}

f@i_:=f[f@i=n/⌈n/⌊i⌋⌉]
{i=f@√n,n/i}

ClearAll[f]

Visualization:

p = FixedPointList[n/⌈n/⌊#⌋⌉ &, Sqrt[n]];

Plot[n/x, {x, 0, 11}, GridLines -> {Range@n, Range@n},
 AspectRatio -> Automatic, PlotRange -> {{0, 10.2}, {0, 7.2}},
 Epilog -> {Red, Thickness[0.005],
   Arrow[Transpose[{{n/p, ⌈p⌉}, {n/p, ⌊p⌋}, {⌈n/⌊p⌋⌉, ⌊p⌋}}, {2, 3, 1}]],
  PointSize[0.02], Black, Point[{n/p[[-1]], p[[-1]]}]}]


Create a program that prints the number of characters it has, in words

Poetic, 400 bytes
Type fourhundred chars? I say, I think I have an angle.
I say "Gosh, could I just go create some poem? Clearly it comes a long way, writing stuff I say."
I compose the entire written poem, and someone reads a tiny, tiny portion.
"Surely, it all is garbage," cried a big fat crybaby.
Would HE frankly notice how many long, tedious hours I took?
The crybaby whined a lot. I watched, then I ignored him.

Try it online!
Prints Four HunDrED. (I tried to make it print some number in the 300s, but I can't seem to do so in under 400 bytes.)
Poetic is an esolang I made in 2018 for a class project. It's basically brainfuck with word-lengths instead of symbols.


Python 2, 229 213 204 200 188 bytes

lambda n,l:"\n".join(["-"*l]+[i%2and"".join(j-i/2&1+2*(n>1)and"  "or x.append(1)or"H0000##"[len(x)%7]*2for j in range(l/2))or((i-n*2and"- "or"=")*l)[:l]for i in range(1,n*4)]+["-"*l])
x=[]

Try it online!

My longest codegolf answer so far


Java 1286 1106 1100 bytes

Here's an easy entry to beat ;-)

Pretty messy. I traverse the tree, populating a 2d array with the node values (and left branch pipes), and a size array with the maximum column widths. Then print the node array using size array to determine correct horizontal spacing.  I look forward to seeing a better way of doing this.

class N{N l,r;int v,i,h,g,b,e,c,j;String[][]a=new String[10][10];int[]w=new int[10];String o="",p="";N(int x){v=x;}void i(int n){if(n>v)if(r==null)r=new N(n);else r.i(n);else if(n<v)if(l==null)l=new N(n);else l.i(n);}void p(N node){a[b][h]=""+node.v;if(w[h]<a[b][h].length())w[h]=a[b][h].length();if(node.r!=null){h++;p(node.r);h--;}if(node.l!=null){b++;while(g<b)a[++g][h]="|";h++;p(node.l);if(a[--g][--h].equals("|"))g--;}}void d(){for(e=-1;++e<a.length;){o="";for(j=-1;++j<a[0].length;){p=a[e][j];if(p!=null)if(p.equals("|")){for(i=0;i++<w[j]-p.length()+2;)o+=" "; o+=p;}else for(i=0;i++<w[j]+2;)o+=" ";else for(i=0;i++<=w[j]+1;)o+=" ";}if(!o.trim().equals(""))System.out.println(o);o="";for(c=-1;++c<a[0].length;){p=a[e][c];if(p!=null)if(p.equals("|")){for(i=0;i++<w[c]-p.length()+2;)o+=" ";o+=p;}else{for(i=0;i++<w[c]-p.length()+2;)o+="_"; o+=p; }else for(i=0;i++<=w[c]+1;)o+=" ";}if(!o.trim().equals(""))System.out.println(o);}}public static void main(String[]a){String[]q=a[0].split(",");N t=new N(Integer.parseInt(q[0]));for(int i=0;i++<q.length-1;)t.i(Integer.parseInt(q[i]));t.p(t);t.d();}}

__50__700__800__850__900__950
   |    |              |
   |    |              |__870
   |    |
   |    |___60__500
   |
   |___30___35
        |
        |____4____5___10___20
             |
             |____2
                  |
                  |____1
                       |
                       |__-10

Ungolfed

class N {
    N leftNode, rightNode;
    int index, loop, curRight, curDown, maxDown, row,col;
    String[][] nodes = new String[10][10];
    int[] colWidths = new int[10];
    String line = "", node="";

N(int index) {
    this.index = index;
}

void i(int newValue) {
    if (newValue > index) {
        if (rightNode == null) {
            rightNode = new N(newValue);
        }
        else {
            rightNode.i(newValue);
        }
    }
    else if (newValue < index) {
        if (leftNode == null) {
            leftNode = new N(newValue);
        }
        else {
            leftNode.i(newValue);
        }
    }
}

void p(N node) {
    // Push current node
    nodes[maxDown][curRight] = ""+node.index;
    // Keep track of max column widths
    if (colWidths[curRight] < nodes[maxDown][curRight].length()) {
        colWidths[curRight] = nodes[maxDown][curRight].length();
    }
    // Branch right
    if (node.rightNode != null) {
        curRight++;
        p(node.rightNode);
        curRight--;
    }
    // Branch left
    if (node.leftNode != null) {
        maxDown++;
        while (curDown<maxDown){
            nodes[++curDown][curRight] = "|";
        }
        curRight++;
        p(node.leftNode);
        if (nodes[--curDown][--curRight].equals("|")) { //following the ladder back up
            curDown--;
        }
    }
}

void d() {
    for ( row = -1; ++row < nodes.length;) {
        // Sloppy. Inject extra rows to extend pipes (double spacing)
        line = "";
        for (int col = -1; ++col < nodes[0].length;) {
            node = nodes[row][col];
            if (node!=null){
                if (node.equals("|")) {
                    for (loop=0; loop++< colWidths[col] - node.length() + 2; ){
                        line+=" ";
                    }
                    line+=node;
                }
                else {
                    for (loop=0; loop++< colWidths[col]  + 2;){
                        line+=" ";
                    }
                }
            }
            else {
                for (loop=0; loop++<=colWidths[col]+1;){
                    line+=" ";
                }
            }
        }
        if (!line.trim().equals("")){
            System.out.println(line);
        }
        line="";

        for ( col = -1; ++col < nodes[0].length;) {
            node = nodes[row][col];
            if (node!=null){
                if (node.equals("|")) {
                    for (loop=0; loop++< colWidths[col] - node.length() + 2;){
                        line+=" ";
                    }
                    line+=node;
                }
                else {
                    for (loop=0; loop++< colWidths[col] - node.length() + 2;){
                        line+="_";
                    }
                    line+=node;
                }
            }
            else {
                for (loop=0; loop++<=colWidths[col]+1;){
                    line+=" ";
                }
            }
        }
        if (!line.trim().equals("")){
            System.out.println(line);
        }
    }
}

public static void main(String[]a){
    String[] values = a[0].split(",");
    N t=new N(Integer.parseInt(values[0]));
    for (int i=0;i++<values.length-1;)
    t.i(Integer.parseInt(values[i]));
    t.p(t);
    t.d();
}
}


Python 3 does not have cmp. For golfing, you can do

11 chars

(a>b)-(a<b)

which loses 3 chars over cmp(a,b).

Amusingly, this is also an "official" workaround. The What's New in Python 3 page says "(If you really need the cmp() functionality, you could use the expression (a > b) - (a < b) as the equivalent for cmp(a, b).)"


Get delta of days by current hour and added delta of days

JavaScript (ES6),  26  25 bytes
Takes input as (current)(delta).

a=>b=>(a+b-(a<-b)*2)/3>>3

Try it online!
Commented
a =>                // a = current hour
b =>                // b = delta of hours
  (                 //
    a + b           // 1) we compute the sum
    - (a < -b) * 2  //    and we subtract 2 if this sum is negative
                    //    examples:
                    //      51 remains 51
                    //      23 remains 23
                    //      -1 is turned into -3
  ) / 3             // 2) float division by 3
                    //    examples:
                    //      51 is turned into 17
                    //      23 is turned into 7.666…
                    //      -3 is turned back into -1
  >> 3              // 3) right arithmetic shift by 3 on the integer part
                    //    examples:
                    //      17 becomes 2
                    //      7.666… becomes 0
                    //      -1 is unchanged

JavaScript (ES6), 26 bytes
More straightforward, but less fun and 1 byte longer anyway.
Takes input as (current)(delta).

a=>b=>Math.floor((a+b)/24)

Try it online!


Function/macro that returns true if one of its arguments contains a call to itself

Mathematica...

...was made for this.

SetAttributes[f, HoldAll]
f[x___] := ! FreeQ[Hold@x, _f]

f[]             (* False *)
f[0]            (* False *)
f[f[0]]         (* True *)
f[3 f[1] + 2]   (* True *)
f[True || f[1]] (* True *)

Everything is an expression, and an expression has a Head and a number of elements. So 1+2 is actually Plus[1,2], and {1,2} is actually List[1,2]. This means we can match any expression for the head we're interested in - in this case the function f itself.

All we need to do is find a way to prevent Mathematica from evaluating the function arguments before the function is called, such that we can analyse the expression tree within the function. What's what Hold and HoldAll is for. Mathematica itself uses this to all over the place to provide special cases for certain implementations. E.g. if you call Length[Permutations[list]] it will never actually create all those permutations and waste loads of memory, but instead realise that it can simply compute this as Length[list]!.

Let's look at the code above in detail, using the last call f[True || f[1]] as an example. Normally, Mathematica will evaluate function arguments first, so this would simply short-circuit and call f[True]. However we have set

SetAttributes[f, HoldAll]

This instructs Mathematica not to evaluate the arguments, so the FullForm of the call (i.e. the internal expression tree, without any syntactic sugar) is

f[Or[True,f[1]]]

And the argument will actually be received by f in this form. The next issue is that, within f, as soon as we use the argument, Mathematica will again try to evaluate it. We can suppress this locally with Hold@x (syntactic sugar for Hold[x]). At this point we've got a handle on the original expression tree and do with it whatever we want.

To look for a pattern in an expression tree we can use FreeQ. It checks that a given pattern is not found in the expression tree. We use the patter _f, which matches any subexpression with head f (exactly what we're looking for). Of course, FreeQ returns the opposite of what we want, so we negate the result.

One more subtlety: I've specified the argument as x___, which is a sequence of 0 or more elements. This ensures that f works with any number of arguments. In the first call, f[] this means that Hold@x will simply become Hold[]. If there were multiple arguments, like f[0,f[1]], then Hold@x would be Hold[0,f[1]].

That's really all there is to it.


Python 3, 128 79 bytes

Let me know if I got anything wrong and critiques are always welcome.

def f(a,b):
    c=len(a)-1-a[::-1].find(b[1])
    if a[-1]==b[0]:return a[:-1]+b
    if a[c]==a[c-1]:c-=1
    return a[:c]+b[1:]

Called with f(word 1,word 2) and returns the portmanteau. Will throw an error if the inputs aren't compatible. Works for all test cases.

Edit:

If I've read the edits to this question correctly, this updated code should work

f=lambda a,b:a[:-1]+b if a[-1]==b[0] else a[:len(a)-1-a[::-1].find(b[1])]+b[1:]


Bash, 9223372036854775810

Inspired by Doorknob's answer.

a='"2>/dev/null;if(((i=$((i-1)))>0));then $(declare -p a);$a;else 1;fi #"'
i=2**63
eval $a

It should be run with bash < file.sh, or use the same file name for each program, to get rid of the different file names in the error messages.

The first few errors are (with LANG=C):

bash: line 3: 2>/dev/null;if(((i=9223372036854775807)>0));then declare -- a="\"2>/dev/null;if(((i=\$((i-1)))>0));then \$(declare -p a);\$a;else 1;fi #\"";"2>/dev/null;if(((i=$((i-1)))>0));then $(declare -p a);$a;else 1;fi #";else 1;fi #: No such file or directory

bash: line 1: 2>/dev/null;if(((i=9223372036854775806)>0));then declare -- a="\"2>/dev/null;if(((i=\$((i-1)))>0));then \$(declare -p a);\$a;else 1;fi #\"";"2>/dev/null;if(((i=$((i-1)))>0));then $(declare -p a);$a;else 1;fi #";else 1;fi #: No such file or directory

bash: line 1: 2>/dev/null;if(((i=9223372036854775805)>0));then declare -- a="\"2>/dev/null;if(((i=\$((i-1)))>0));then \$(declare -p a);\$a;else 1;fi #\"";"2>/dev/null;if(((i=$((i-1)))>0));then $(declare -p a);$a;else 1;fi #";else 1;fi #: No such file or directory

And finally:

bash: line 1: 2>/dev/null;if(((i=0)>0));then declare -- a="\"2>/dev/null;if(((i=\$((i-1)))>0));then \$(declare -p a);\$a;else 1;fi #\"";"2>/dev/null;if(((i=$((i-1)))>0));then $(declare -p a);$a;else 1;fi #";else 1;fi #: No such file or directory

bash: line 1: 1: command not found

bash: line 1: bash:: command not found

which is an error quine.


JavaScript (ES7),  106 103 102  98 bytes

f=(m,n=b=-1,x,y,p)=>m.map((r,Y)=>r.map((v,X)=>(x-X)**2+(y-Y)**2-1|v/p?b=n<b?b:n:f(m,n+1,X,Y,v)))|b

Try it online!

Commented

f = (                        // f = recursive function taking:
  m,                         //   m[]  = input matrix
  n = b = -1,                //   n    = length of the current path; b = best length so far
  x, y,                      //   x, y = coordinates of the previous cell
  p                          //   p    = value of the previous cell
) =>                         //
  m.map((r, Y) =>            // for each row r[] at position Y in m[]:
    r.map((v, X) =>          //   for each value v at position X in r[]:
      (x - X) ** 2 +         //     compute the squared Euclidean distance
      (y - Y) ** 2           //     between (x, y) and (X, Y)
      - 1                    //     if A) the above result is not equal to 1
      | v / p ?              //     or B) v is greater than or equal to p:
        b = n < b ? b : n    //       end of path: update b to n if n >= b
      :                      //     else:
        f(m, n + 1, X, Y, v) //       do a recursive call
    )                        //   end of inner map()
  ) | b                      // end of outer map(); return b

How?

During the first iteration, \$x\$, \$y\$ and \$p\$ are all undefined and both tests (A and B in the comments) evaluate to NaN, which triggers the recursive call. Therefore, all cells are considered as a possible starting point of the path.


Ruby, Rev 1, 66
->(m,n){n.times{|i|puts ("#"*m**(1-i%2)).rjust(m,i>n-2?"# ":" ")}}

Used raising m to power 0 o 1 to decide whether 1 or m #'s will be printed.
Used > to test for last row instead of ==.
Can't get rid of the space after puts, nor any brackets!
Ruby, Rev 0, 69
->(m,n){n.times{|i|puts ("#"*(i%2==0?m:1)).rjust(m,i==n-1?"# ":" ")}}

This is an anonymous lambda function. Use it like this:
f=->(m,n){n.times{|i|puts ("#"*(i%2==0?m:1)).rjust(m,i==n-1?"# ":" ")}}

M=gets.to_i
N=gets.to_i
f.call(M,N)

In the end, after asking if M and N could be interchanged I didnt need it.

Typical outputs for N odd. If we delete the # on their own on the right hand side, clearly we will have (N+1)(M+1). Including them to join the shape removes 2 squares of horizontal perimeter and adds 2 squares of vertical perimeter, so there is no change.
Here we rely on the expression "#"*(i%2==0?m:1) to give alternating rows of M# symbols and one # symbol, and right justify to M characters.
5                        6
5                        5
#####                    ######
    #                         #
#####                    ######
    #                         #
#####                    ######

Typical outputs for N even. 5 6 clearly has the same perimeter as 6 5, or an increment of M+1=6 compared with 5 5 by addition of vertical perimeter due to the crenelation of the bottom row. 6 6 has the same as 6 5 plus an increment of (M+1)-1=6 in the vertical perimeter. Thus they are in accordance with the formula.
5                        6
6                        6
#####                    ######
    #                         #
#####                    ######
    #                         #
#####                    ######
# # #                    # # ##

It's very handy that Ruby's rjust allows you to specify the padding to use for the empty cells. Normally the padding is set to " " but for the last row we switch to "# " (note that padding will only be needed on the last row if N is even. Where N is odd the last row will be complete and there will be no justifying, so you won't see the crenelations.)
Check it out here.


JavaScript (ES6),  79 77  75 bytes
Saved 2 bytes thanks to @ExpiredData
Expects whitespace around operators. Returns a Boolean value.

s=>![/".*?"/g,/0x../g,/\S+f/g,/\d/,/e/i].filter(e=>s!=(s=s.split(e)+''))[1]

Try it online!
How?

We remove all strings, using /".*?"/g
We remove all bytes, using /0x../g
We remove all floats, using /\S+f/g
We look for a remaining digit with /\d/; if we do find one, there must be at least one integer
We look for a remaining "e" or "E" with /e/i; if we do find one, there must be at least one Boolean value

All removed expressions are actually replaced with a comma, which is harmless.
We filter out the regular expressions causing no change to the input string and test whether less than two of them remain at the end of the process.


Ruby, 34 32 bytes

This uses a formula from the OEIS page for the Narayana-Zidek-Cappell numbers.

Edit: Got rid of parentheses using operator precedence with thanks to feersum and Neil.

f=->x{x<4?1:2*f[x-1]-x%2*f[x/2]}


Java, 133 149

void f(){String s=x(2)<1?"-":"";for(s+=x(9)+1;x(50)>0;s+=x(10));System.out.print(x(9)<1?0:s);}int x(int i){return new java.util.Random().nextInt(i);}

Example outputs

-8288612864831065123773
0
660850844164689214
-92190983694570102879284616600593698307556468079819964903404819
3264

Ungolfed

void f() {
    String s = x(2)<1 ? "-" : "";       // start with optional negative sign
    s+=x(9)+1;                          // add a random non-zero digit
    for(; x(50)>0; )                    // with a 98% probability...
        s+=x(10)                        // append a random digit
    System.out.print(x(9)<1 ? 0 : s);   // 10% chance of printing 0 instead
}

int x(int i) {
    return new java.util.Random().nextInt(i);
}

Old answer (before rule change)

void f(){if(Math.random()<.5)System.out.print('-');do System.out.print(new java.util.Random().nextInt(10));while(Math.random()>.02);}


Vim, 22 bytes, Loojvo
qtiqtqx0l"tp^V^[^[qx0l"tp

Try it online!
Explanation:
qt                  " Start recording in register 'q'
  i                 " Enter insert mode
   qtqx0l"tp        " Enter this string
            ^V^[    " Enter a literal 'esc' character
                ^[  " Exit insert mode
                  q " Stop recording

At this point, the buffer looks like this:
qtqx0l"tp^[

And the cursor is on the last column (the 'esc' key).
x                   " Delete the esc character
 0l                 " Move to the second character on this line
   "tp              " And paste register 't'


Pure Bash (no utilities), 200 bytes - 40 bonus = 160
while read u;do
u=${u#*//}
d=${u%%/*}
exec 3<>/dev/tcp/$d/80
echo "GET /${u#*/} HTTP/1.1
host:$d
Connection:close
">&3
mapfile -tu3 A
a=${A[@]}
a=${a#*
}
a=${a%
*}
echo "${a//<\/p>*
/"
"}"
done

I think this is up to the spec, though of course watch out for parsing HTML using regex I think the only thing worse than parsing HTML using regex is parsing HTML using shell pattern matching.
This now deals with
...
 spanning multiple lines.  Each
...
 is on a separate line of output:
$ echo "http://example.com/" | ./smallbrowse.sh
This domain is established to be used for illustrative examples in documents. You may use this     domain in examples without prior coordination or asking for permission.
More information...
$


Bash - 32 characters

Script A - 16 characters

cmp -s b&&echo 1

Script B - 16 characters

cmp -s a||echo 1

Usage

$> echo "foo" | ./a
$> cat b | ./a
1
$> echo "foo" ./b
foo ./b
$> cat a | ./b


Vim - surround comment line with comment character

11 8 7 keystrokes

YpVkr#p

Yp - duplicate current line, leaving the cursor at the lower of the two
V - enter visual line mode
k - go up and select both lines
r# - replace every selected character with #. Leaves visual mode and leaves cursor at the upper line.
p - put the yanked line (the original) on the next line.

(thanks to doorknob for reminding Y=yy)


Pyth, 43 41 39 bytes

K*\#+2QKVvzp<*QXX*dyivzQN\\_hN\/Q\#\#)K

Try it online: Pyth Compiler/Executor. Input the numbers in the following order: height first line, width second line.

Thanks to isaacg, who helped saving two bytes.

Explanation:

My solution doesn't trace the laser, it uses a simple pattern that includes the gcd. If m, n are the dimensions of the box, let d = gcd(m, n). The size of the pattern is exactly 2*d x 2*d.

E.g. the repeating pattern for 7 5

#########
#\/\/\/\#
#/\/\/\/#
#\/\/\/\#
#/\/\/\/#
#\/\/\/\#
#########

is

\/
/\

(gcd(7, 5) = 1, size of pattern is 2 x 2)

And the repeating pattern for 22 6

########################
#\  /\  /\  /\  /\  /\ #
# \/  \/  \/  \/  \/  \#
# /\  /\  /\  /\  /\  /#
#/  \/  \/  \/  \/  \/ #
#\  /\  /\  /\  /\  /\ #
# \/  \/  \/  \/  \/  \#
########################

is

\  /
 \/
 /\
/  \

(gcd(22, 6) = 2, size of pattern is 4 x 4)

My solution does the following thing for each of the lines: it simply generates one line of the pattern, repeats it a few times and cut's it at the end so that it fit's into the box.

K*\#+2QK   implicit: Q is the second input number (=width)
K          K =
 *\#+2Q        "#" * (2 + Q)
       K   print K (first line)

Vvzp<*QXX*dyivzQN\\_hN\/Q\#\#)K  implicit: vz is the first input number (=height)
VQ                               for N in [0, 1, ..., vz-1]:
           ivzQ                             gcd(vz,Q)
          y                               2*gcd(vz,Q)
        *d                           string with 2*gcd(vz,Q) space chars
       X       N\\                   replace the Nth char with \
      X           _hN\/              replace the -(N+1)th char with /
    *Q                               repeat Q times
   <                   Q           only use the first Q chars
  p                     \#\#       print "#" + ... + "#"
                            )    end for
                             K   print K


05AB1E, 5 bytes
ŸÑ˜åO

Try it online!

Explanation
Ÿ       - the numbers between start and end
 Ñ      - get their divisors
  ˜     - deep flatten this list
   å    - find the instances of the elements in the list in these divisors
    O   - Sum this


C - GCC - 159 145 135 Bytes
x=0,w=0,i,j,c;main(int _,char**z){while(--_)for(j=i=0;_[z][i];j=++i,x=c>x?w=_,c:x)for(c=0;j--;)c+=z[_][i]==z[_][j];puts(x?z[w]:"-1");}

Will update when I can truncate it a bit
How to compile:         gcc -w cg.c
How to run:             ./a.out word1 word2 aass ddaaa ssdddd
Output:                 ssdddd
No-Output/No-match:     -1
First off, I cheated a bit, by taking in the words as program arguments, but getting GCC to parse the words and give me a word count for free was too much reward to pass up.
How does it work?
We have 3 nested loops. The first incrementing through each word, the next two are mimicking a bubble sort to compare values. The first letter is never compared with itself, and each subsequent letter is compared to each previous letter. Whenever a word has more same letters than a previous word, the word is stored in x, and the count of how many same letters is also stored.
GCC Abuse
We use implicit global auto int delcarations for our integers. We allow argv to be an int instead of a char (currently a char, this is a TODO). We make use of default functions such as puts and getchar. We also make use of the comma operator to overload our trinary (conditional) operator.
Want 2 less bytes?
Replace "-1" with *z and name the file -1
Program unobfuscated and untested:
int main(int argc, char * argv[])
{
    int word = 0           // Current most repeat letters word
    int count = 0;        // Current most repeat letters
    int i, j, increment; // Counter variables

    while(--argc != 0) // While we have words from program parameters
    {
        for(j = i = 0; argv[argc][i] != '\0'; j = ++i) // Iterate through each letter until end of word
        {
            for(increment = 0; j > 0; j--) // Iterative backwards through each letter
            {
                if(argv[argc][i] == argv[argc][j])
                {
                    increment++;
                }
            }
            if(increment > count) // New greatest lettered word
            {
                word = argc;
                count = increment;
            }
        }
    }

    if(word == 0)
    {
        puts("-1");
    }
    else
    {
        puts(argv[word]);
    }

    return 0;
}


JavaScript (ES6),  180 ... 155  152 bytes
Returns a multidimensional list. The outermost expression is parenthesized, and so are the atoms.

f=(i,a=i.split(/ +/))=>"w | ^ & <> =! : +- */%".split` `.some(p=>a.map((s,j)=>i=!!s.match(`^[\\${p}]`)&j?j:i)|i)?[f(i=a.splice(i),a),i.shift(),f(a,i)]:a

Try it online!
How?
This is a recursive algorithm. At each iteration, we look for the last operator with the lowest precedence, split the expression at this position and process recursive calls on both resulting parts. We stop the recursion when we reach an atom.
In order to split the expression and isolate the operator, we use a combination of splice() and shift() as shown in the following example, where integers are used instead of operators and operands.
a = [ 0, 1, 2, 3, 4, 5, 6 ];
i = 3;
i = a.splice(i); // --> a[] = [ 0, 1, 2 ] (left expression)
                 //     i[] = [ 3, 4, 5, 6 ] (operator + right expression)
i.shift();       // --> operator = 3
                 //     i[] = [ 4, 5, 6 ] (right expression)

Commented
f = (                      // f is a recursive function taking:
  i,                       //   i   = input string on the 1st iteration,
                           //         and then some non-empty array
  a = i.split(/ +/)        //   a[] = input string split on spaces
) =>                       //         NB: operators are expected at odd positions
  "w | ^ & <> =! : +- */%" // this string describes the groups of operators,
                           // from lowest to highest precedence
  .split` `                // split it
  .some(p =>               // for each pattern p:
    a.map((s, j) =>        //   for each string s at position j in a[]:
      i =                  //     update i:
        !!s.match(         //       see if s matches p; the '\' is required for
          `^[\\${p}]`      //       'w' and '^', and harmless for the other ones
        ) & j ?            //       if there's a match and j is odd:
          j                //         update i to j
        :                  //       else:
          i                //         leave i unchanged
    )                      //   end of map()
    | i                    //   make some() succeed if i is a number
  ) ?                      // end of some(); if successful:
    [                      //   build a new array consisting of:
      f(                   //     the result of a recursive call ...
        i = a.splice(i), a //     ... with the left expression
      ),                   //
      i.shift(),           //     followed by the operator
      f(                   //     followed by the result of a recursive call ...
        a, i               //     ... with the right expression
      )                    //
    ]                      //   end of new array
  :                        // else:
    a                      //   just return a[]


Distance Between Two Points Travelling on a Polar Graph Chart

Haskell, 49 48 bytes

(a!q)c r=min(q+r)$abs(q-r)+acos(cos$a-c)*min q r

Usage:

> let rect2polar (x,y)=(atan2 y x, sqrt(x^2+y^2))
> let test c1 c2=let [(a1,r1),(a2,r2)]=rect2polar<$>[c1,c2] in (a1!r1)a2 r2
> test (1,0) (-0.4161, 0.90929)
1.9999342590038496

Thanks to @Zgarb for saving a byte


Determining the rotation of square given a list of points

Rev 1: Ruby, 354 bytes

further golfing thanks to blutorange.

->a{t=s=Math::PI/18E4
d=r=c=0
a=a.map{|e|e-a[0]}
0.upto(36E4){|i|b=a.map{|e|(e/Complex.polar(1,i*s)).rect}.transpose
m,n=b
if n.min>=f=0
l=[m.max-x=m.min,n.max].max
a.each_index{|j|f+=((l-w=n[j])*(x+l-v=m[j])*(x-v)*w)**2}
(1E-9>q=f/l**8)&&(c>0&&(i-d)%9E4%89E3>1E3?c=9E9:0;c+=1;d=i)
q<t&&(r=i)&&t=q;end}
c<101&&a[1]?c<1?'impossible':r%9E4/1.0E3:'unknown'}

Ruby, 392 bytes

->(a){
s=Math::PI/18E4
t=1
d=r=c=0
a=a.map{|e|e-a[0]}
(0..36E4).each{|i|
b=a.map{|e|(e/Complex.polar(1,i*s)).rect}.transpose
m=b[0]
n=b[1]
x=m.min
if n.min>=0
l=[m.max-x,n.max].max
f=0
a.each_index{|j|f+=((l-n[j])*(x+l-m[j])*(x-m[j])*n[j])**2}
q=f/l**8
if q<1E-9
c>0&&(i-d)%9E4%89E3>1E3?(c=9E9):0
c+=1
d=i
end
if q<t
r=i
t=q
end
end
}
c>100||a.size<2?'unknown':c<1? 'impossible':r%9E4/1.0E3
}

The algorithm is as follows:

-Pick an arbitrary point (the first one) and move that to the origin (subtract the coordinates of this point from all points in the list.)

-Try all rotations of the square about the origin in 0.001 degree increments, through 360 degrees.

-For a given rotation, if all points are above the y axis, draw the smallest possible square around all the points, incorporating the lowest and leftmost point.

-Check if all points are on the edge. This is done with a soft calculation that takes each point, finds the squared distances from all edges, and multiplies them together. This gives a good fit rather than a yes/no answer. It is interpreted that a solution is found if this product divided by sidelength^8 is less than 1E-9. In practice this is less than a degree of tolerance.

-The best fit is taken mod 90 degrees and reported as the correct angle.

Currently the code returns a value of ambiguous if over 100 solutions are found (at 0.001 degree resolution. That's 0.1 degrees of tolerance.)

first fully working function, in test program

I left the resolution at 1/10th of the required resolution to make the speed reasonable. There is an error of 0.01 degress on the very last test case.

g=->(a){
 s=Math::PI/18000
 t=1
 d=r=-1
 c=0
 a=a.map{|e| e-a[0]}

 (0..36000).each{|i|
    b=a.map{|e|(e/Complex.polar(1,i*s)).rect}.transpose

    m=b[0]
    n=b[1]
    x=m.min

    if n.min>=0

       l=[m.max-x,n.max].max
       f=0
       a.each_index{|j|f+=((l-n[j])*(x+l-m[j])*(x-m[j])*n[j])**2}
       q=f/l**8

       if q<1E-9

         j=(i-d)%9000
         c>0&&j>100&&j<8900?(c=9E9):0
         c+=1
         d=i
       end

       if q<t
         r=i
         t=q
       end

     end
  }

 print "t=",t,"   r=",r,"     c=",c,"    d=",d,"\n"
 p c>100||a.size<2?'unknown':c<1? 'impossible':r%9000/100.0
}

#ambiguous
#g.call([Complex(0,0)])
#g.call([Complex(0,0),Complex(1,0)])
#g.call([Complex(0,0),Complex(1,0),Complex(0,1)])
#g.call([Complex(0,0),Complex(1,0),Complex(0,1),Complex(1,1)])
#g.call([Complex(0,1),Complex(0,2),Complex(1,0),Complex(1,3),Complex(2,0),Complex(2,3),Complex(3,1),Complex(3,2)])

#impossible
#g.call([Complex(0,0),Complex(1,0),Complex(2,0),Complex(3,1),Complex(4,2)])
#g.call([Complex(0,0),Complex(1,0),Complex(2,0),Complex(1,1)])
#g.call([Complex(0,1),Complex(0,2),Complex(1,0),Complex(1,3),Complex(2,0),Complex(2,3),Complex(3,1),Complex(3,2),Complex(2,2)])
#g.call([Complex(2,0),Complex(0,1),Complex(2,2),Complex(0,3)])
#g.call([Complex(0,0),Complex(2,1),Complex(0,2),Complex(2,2),Complex(-1,1)])

#possible
g.call([Complex(0,0),Complex(1,0),Complex(2,0)])
g.call([Complex(0,0),Complex(0.3,0.3),Complex(0.6,0.6)]) #(should return 45)
g.call([Complex(0,0),Complex(0.1,0.2),Complex(0.2,0.4)]) #(should return appx 63.435 (the real value is arctan(2)))
g.call([Complex(0,0),Complex(0,1),Complex(2,1),Complex(2,2)])
g.call([Complex(0,1),Complex(0,2),Complex(1,0),Complex(1,4),Complex(2,0),Complex(2,4),Complex(4,1),Complex(4,3)])

golfed version, resolution compliant with spec, takes about a minute per call, in test program.

There's still a pesky error of 0.001 degrees on the last test case. Increasing resolution further would probably eliminate it.

g=->(a){                                                            #take an array of complex numbers as input
  s=Math::PI/18E4                                                   #step size PI/180000
  t=1                                                               #best fit found so far
  d=r=c=0                                                           #angles of (d) last valid result, (r) best fit; c= hit counter
  a=a.map{|e|e-a[0]}                                                #move shape so that first point coincides with origin
  (0..36E4).each{|i|                                                #0..360000
    b=a.map{|e|(e/Complex.polar(1,i*s)).rect}.transpose             #rotate each element by dividing by unit vector of angle i*s, convert to array...
    m=b[0]                                                          #...transpose array [[x1,y1]..[xn,yn]] to [[x1..xn],[y1..yn]]...
    n=b[1]                                                          #...and assign to variables m and n
    x=m.min                                                         #find leftmost point
    if n.min>=0                                                     #if all points are above x axis
       l=[m.max-x,n.max].max                                        #find the sidelength of smallest square in which they will fit
       f=0                                                          #f= accumulator for errors. For each point
       a.each_index{|j|f+=((l-n[j])*(x+l-m[j])*(x-m[j])*n[j])**2}   #...add to f the product of the squared distances from each side of the smallest square containing all points
       q=f/l**8                                                     #q= f normalized with respect to the sidelength.
       if q<1E-9                                                    #consider a hit if <1E-9
         c>0&&(i-d)%9E4%89E3>1E3?(c=9E9):0                          #if at least one point is already found, and the difference between this hit and the last exceeds+/-1 deg (mod 90), set c to a high value
         c+=1                                                       #increment hit count by 1 (this catches infinitely varible cases)
         d=i                                                        #store the current hit in d
       end
       if q<t                                                       #if current fit is better than previous one
        r=i                                                         #store the new angle
        t=q                                                         #and revise t to the new best fit.
       end
    end
  }
  c>100||a.size<2?'unknown':c<1? 'impossible':r%9E4/1.0E3           #calculate and return value, taking special care of case where single point given.
}
#ambiguous
puts g.call([Complex(0,0)])
puts g.call([Complex(0,0),Complex(1,0)])
puts g.call([Complex(0,0),Complex(1,0),Complex(0,1)])
puts g.call([Complex(0,0),Complex(1,0),Complex(0,1),Complex(1,1)])
puts g.call([Complex(0,1),Complex(0,2),Complex(1,0),Complex(1,3),Complex(2,0),Complex(2,3),Complex(3,1),Complex(3,2)])

#impossible
puts g.call([Complex(0,0),Complex(1,0),Complex(2,0),Complex(3,1),Complex(4,2)])
puts g.call([Complex(0,0),Complex(1,0),Complex(2,0),Complex(1,1)])
puts g.call([Complex(0,1),Complex(0,2),Complex(1,0),Complex(1,3),Complex(2,0),Complex(2,3),Complex(3,1),Complex(3,2),Complex(2,2)])
puts g.call([Complex(2,0),Complex(0,1),Complex(2,2),Complex(0,3)])
puts g.call([Complex(0,0),Complex(2,1),Complex(0,2),Complex(2,2),Complex(-1,1)])

#possible
puts g.call([Complex(0,0),Complex(1,0),Complex(2,0)])
puts g.call([Complex(0,0),Complex(0.3,0.3),Complex(0.6,0.6)]) #(should return 45)
puts g.call([Complex(0,0),Complex(0.1,0.2),Complex(0.2,0.4)]) #(should return appx 63.435 (the real value is arctan(2)))
puts g.call([Complex(0,0),Complex(0,1),Complex(2,1),Complex(2,2)])
puts g.call([Complex(0,1),Complex(0,2),Complex(1,0),Complex(1,4),Complex(2,0),Complex(2,4),Complex(4,1),Complex(4,3)])

Note that for about 30% more code this algorithm could be adapted to work fast: it is obvious that in cases with a finite number of solutions, one of the edges lies flat along a a cube, so all we really have to try is those angles that correspond to each pair of vertices.  It would also be necessary to do a bit of wiggling to check there aren't there aren't infinitely many solutions.


Sort numbers represented in an unknown base

Python, 59 108 112

sorted(a,None,lambda x:(-len(x),map(zip(*a)[0].count,x)),1)

Input is provided as the list a, and this expression produces the sorted list (+2 characters to assign to a variable). This sorts the list in reverse by negated length and then by frequency.


Python 2, 91 bytes

s="import md5;print'MD5 sum of my source is: '+md5.new('s=%r;exec s'%s).hexdigest()";exec s

Using the Python quine variant which doesn't require repeating everything twice. Tested on ideone.


Enumerate each series of identical numbers in-place

JavaScript (ES6), 26 bytes
1-indexed.

a=>a.map(o=x=>o[x]=-~o[x])

Try it online!
Commented
a =>                // a[] = input array
  a.map(o =         // assign the callback function of map() to the variable o, so that
                    // we have an object that can be used to store the counters
    x =>            // for each value x in a[]:
      o[x] = -~o[x] //   increment o[x] and yield the result
                    //   the '-~' syntax allows to go from undefined to 1
  )                 // end of map()


Ohm, 2 bytes (CP437)

Accepts and returns a list of strings.

()

Explanation:

()   Main wire, arguments: a

(    Remove the first element of a
 )   ...and then the last element of that
     Implicit output


Python, cracked
Regex: (?!.)
Program: from operator import not_
This is a little easier than my previous one.


Am I divisible by double the sum of my digits?

JavaScript (ES6), 31 29 27 bytes

Takes input as a string. Returns zero for truthy and non-zero for falsy.

n=>n%eval([...n+n].join`+`)

Commented

n => n % eval([...n + n].join`+`)
n =>                                   // take input string n  -> e.g. "80"
                  n + n                // double the input     -> "8080"
              [...     ]               // split                -> ["8", "0", "8", "0"]
                        .join`+`       // join with '+'        -> "8+0+8+0"
         eval(                  )      // evaluate as JS       -> 16
     n %                               // compute n % result   -> 80 % 16 -> 0

Test cases

let f =

n=>n%eval([...n+n].join`+`)

console.log('[Truthy]');
console.log(f("80"))
console.log(f("100"))
console.log(f("60"))
console.log(f("18"))
console.log(f("12"))

console.log('[Falsy]');
console.log(f("4"))
console.log(f("8"))
console.log(f("16"))
console.log(f("21"))
console.log(f("78"))
console.log(f("110"))
console.log(f("111"))
console.log(f("390"))


Jelly, 16 15 14 bytes

÷RĊ,Rµạ/+PỤḢịZ

Try it online! or verify all test cases.

How it works

÷RĊ,Rµạ/+PỤḢịZ  Main link. Argument: n

 R              Range; yield [1, ..., n].
÷               Divide n by each k in [1, ..., n].
  Ċ             Ceil; round the quotients up to the nearest integer.
    R           Range; yield [1, ..., n].
   ,            Pair; yield A := [[ ⌈n ÷ 1⌉, ..., ⌈n ÷ n⌉ ], [ 1, ..., n ]].
     µ          Begin a new, monadic chain. Argument: A
      ạ/        Reduce A by absolute difference.
                This yields [ |⌈n ÷ 1⌉ - 1|, ..., |⌈n ÷ n⌉ - n| ].
         P      Product; reduce A by multiplication.
                This yields [ ⌈n ÷ 1⌉ × 1, ..., ⌈n ÷ n⌉ × n].
       +        Add the results to left and right, element by element. This yields
                [ |⌈n ÷ 1⌉ - 1| + ⌈n ÷ 1⌉ × 1, ..., |⌈n ÷ n⌉ - n| + ⌈n ÷ n⌉ × n ].
          Ụ     Grade up; sort the indices of the list of sums by their values.
           Ḣ    Head; extract the first value, which corresponds to the smallest
                sum. Grading up is stable, so this selects the first index of all
                with the smallest sum in case of a tie. In this event, the first
                index will have the highest absolute difference of all indices
                with the smallest sum, meaning that it has the lowest product and,
                therefore, the lowest number of empty chairs.
             Z  Zip; transpose A's rows and columns.
                This yields [[ ⌈n ÷ 1⌉, 1 ], ..., [ ⌈n ÷ n⌉, n ]].
            ị   Retrieve the pair at that index.


JavaScript - 184 169 (with jQuery)

b="input",a="<input type=checkbox>",c=":checked";$("body").html("SELECT ANY TWO"+a+"FAST"+a+"GOOD"+a+"CHEAP").click(function(){$(b).not(c).attr("disabled",!!$(b+c)[1])})

http://jsfiddle.net/L33JK/16/

EDIT: improved with help from @Daniel Lisik - https://codegolf.stackexchange.com/a/26805/16278


Brain-Flak, 112 bytes

(([]){[{}]<{({}()){{}<>([{}]<([{}])>)(<>)}<>(({}[({})])[({}{})])<>}{}<>>({}<({}())>)<>([])}{})({()<({}()())>}{})

Try it online!

This program uses Green's theorem to compute the area

The current location is stored on the right stack, in a format that depends on the direction faced.

Direction  top  second
north       -x       y
west        -y      -x
south        x      -y
east         y       x

In all instances, the second value on the stack will increase by 1, and the line integral for the area decreases by half the value on the top of the stack.  To compensate, the end of the program divides the running total by -2.

# For each number in input
(([]){[{}]

  # Evaluate turn-handling to zero
  <

    # If turn:
    {

      # If right turn:
      ({}()){{}

        # Negate both values on other stack (reverse direction)
        <>([{}]<([{}])>)

      (<>)}

      # Swap the two stack elements and negate the new top of stack
      # This performs a left turn.
      <>(({}[({})])[({}{})])<>

    }{}

  <>>

  # Evaluate as top of stack and...
  ({}<

    # increment the number below it
    ({}())

  >)<>

([])}{})

# Divide total by -2
({()<({}()())>}{})


Haskell - 35

c n=(iterate(\x->(x+n/x/x)/2)n)!!99

Example runs:

c 27  =>  3.0
c 64  =>  4.0
c 1  =>  1.0
c 18.609625  =>  2.6500000000000004  # only first 4 digits are important, right?
c 3652264  =>  154.0
c 0.001  =>  0.1
c 7  =>  1.9129311827723892
c (-27)  =>  -3.0
c (-64)  =>  -4.0

Moreover, if you import Data.Complex, it even works on complex numbers, it returns one of the roots of the number (there are 3):

c (18:+26)  =>  3.0 :+ 1.0

The :+ operator should be read as 'plus i times'


Pyth, 27 23 bytes

+fg0=-QJc*.n0+18T50)cQJ

Try it online. Test suite.

Explanation

                            Q = input number (implicit)
 f                 )        increment T from 1, for each T:
             +18T             add 18 to T, get radius
         *.n0                 multiply by pi to, get half the circumference
        c        50           divide by 50, get circumference in sheets
       J                      save it to J
    =-Q                       decrement Q by it
  g0                          use this T if Q is now <= 0
+                           add
                     Q        Q (now <= 0)
                    c J       divided by J (the last circumference)
                            and print (implicit)


Haskell, 192 190 187 bytes

unlines.snd.f
f(n:r)|(m,t)<-span(>'9')r,(s,l)<-n#t=(s,n?((n:m):map((' '<$(n:n:m))++)l))
f e=(e,["0"])
'1'?(a:b:r)=(a++drop(length a)b):r
_?s=s
'0'#s=(s,[])
n#s|(r,l)<-f s=(l++)<$>pred n#r

Try it online!

There has to be a better way to handle the arity-1 case, it currently takes up 45 bytes.

Edits:

-2 bytes by switching to a different method of handling 1, though the previous method has probably more optimization potential.
-3 bytes by not converting the character digits to numbers and using pred instead of n-1.

unlines.snd.f
f(n:r)|(m,t)<-span(>'9')r,(s,l)<-read[n]#t,w<-map((' '<$(n:n:m))++)=(s,last$((n:m):w l):[(n:m++' ':h):w t|n<'2',h:t<-[l]])
f e=(e,["0"])
0#s=(s,[])
n#s|(r,l)<-f s=(l++)<$>(n-1)#r

Try it online!


Pyth, 38 34 bytes

j.tm+j\=jL\+C,.u+NYJ.WnsHQ+ZO2Y0J+\=QE
j.tmj\=jL\+.T,.u+NYJ.WnsHQ+ZO2Y0JE

Try it online!


Python 2, 132 129 128
def f(s):w=s.find(' ');E=dict(enumerate(s));return all(E[i]in' X'+`sum(E.get(i+d/3*~w+d%3+w,5)>'O'for d in range(9))`for i in E)

I used enumerate in a golf...and even used range elsewhere in the same program. Clearly something is wrong here.
Edit: Iterate over dict(enumerate(s)) rather than enumerate(s), so enumerate does not need to be called twice.


Raw file, 184 bytes = 173-byte file + 11-byte filename

I hope this does not break any standard loopholes. But the output "has a high   kolmogorov-complexity and the shortest way to produce it would (most likely) be to just print it literally...".

Base 64 of the file:

iVBORw0KGgoAAAANSUhEUgAAAB8AAAAfAQAAAAA31SuUAAAAdElEQVR4XnXOMQ5BQRRA0euVRFgGCq1ubIyJpSh11I
qJWIjo+fnt/JnJe55WornlycXMVAB+Qp49A7U/J8rqlIQReG5Quz6Rx8eA6VaF5R7a5arooXg2LaKvd8KGRyBPJLoy
D640pxZ3pay/creL5KnEvwcfvE46ggJMibIAAAAASUVORK5CYII=

Instead of golfing a program I golfed the resulting PNG image. QR code is a very flexible format, there are many parameters that can be fiddled: the encoding of the input, the error correction level, and the masking image. These will all generate different symbols and thus compressed to files of different sizes.

So I have written a program to generate all these combinations (resulting 6720 files), and then use PNGOUT to pick the one which compressed to the smallest file. It turns out to be a file that:

First write "20" in alphanumeric mode
Then write "1" in numeric mode
Then write "5" in numeric mode
Use the "H" (High) error correction level
Use the "110" data masking

This is called test-3-1-H-Diamonds.bmp if you used the program below. This image is 175-byte long after running PNGOUT. With "high" error correction level in "version 1" QR code, we can modify up to 8 pixels in the data part without ruining the data. With a bit of manual trial-and-error I can reduce it further to 173 bytes presented above. It can probably be smaller but exhausting all combinations requires 208C8 ~ 7.5 × 1013 checks which I'm not going to do ;)

The Rust (0.13.0-nightly (5ba610265)) program that generates all combinations:

/*

Also put these into your Cargo.toml:

[dependencies]
qrcode = "0.0.3"
bmp = "0.0.3"

*/

extern crate qrcode;
extern crate bmp;

use qrcode::bits::Bits;
use qrcode::optimize::Segment;
use qrcode::types::{Version, EcLevel, Mode};
use qrcode::ec::construct_codewords;
use qrcode::canvas::{Canvas, MaskPattern, Module};

use bmp::{Image, Pixel};

use std::num::Int;

const BLACK: Pixel = Pixel { r: 0, g: 0, b: 0};
const WHITE: Pixel = Pixel { r: 255, g: 255, b: 255 };

static SEGMENT_SEPARATIONS: [&'static [(uint, uint)]; 8] = [
    &[(0, 1), (1, 2), (2, 3), (3, 4)],
    &[(0, 1), (1, 2), (2, 4)],
    &[(0, 1), (1, 3), (3, 4)],
    &[(0, 2), (2, 3), (3, 4)],
    &[(0, 1), (1, 4)],
    &[(0, 2), (2, 4)],
    &[(0, 3), (3, 4)],
    &[(0, 4)],
];

const ALL_EC_LEVELS: &'static [EcLevel] = &[EcLevel::L, EcLevel::M, EcLevel::Q, EcLevel::H];
const ALL_MODES: &'static [Mode] = &[Mode::Numeric, Mode::Alphanumeric, Mode::Byte];
const ALL_MASK_PATTERNS: &'static [MaskPattern] = &[
    MaskPattern::Checkerboard,
    MaskPattern::HorizontalLines,
    MaskPattern::VerticalLines,
    MaskPattern::DiagonalLines,
    MaskPattern::LargeCheckerboard,
    MaskPattern::Fields,
    MaskPattern::Diamonds,
    MaskPattern::Meadow,
];

fn run(ec_level: EcLevel, mask_pattern: MaskPattern, segments: &[Segment], filename: &str) {
    let version = Version::Normal(1);
    let mut bits = Bits::new(version);
    if bits.push_segments(b"2015", segments.iter().map(|s| *s)).is_err() {
        return;
    }
    if bits.push_terminator(ec_level).is_err() {
        return;
    }
    let data = bits.into_bytes();
    let (encoded_data, ec_data) = construct_codewords(&*data, version, ec_level).unwrap();
    let mut canvas = Canvas::new(version, ec_level);
    canvas.draw_all_functional_patterns();
    canvas.draw_data(&*encoded_data, &*ec_data);
    canvas.apply_mask(mask_pattern);
    let canvas = canvas;

    let width = version.width();
    let real_image_size = (width + 10) as uint;
    let mut image = Image::new(real_image_size, real_image_size);
    for i in range(0, real_image_size) {
        for j in range(0, real_image_size) {
            image.set_pixel(i, j, WHITE);
        }
    }
    for i in range(0, width) {
        for j in range(0, width) {
            if canvas.get(i, j) == Module::Dark {
                image.set_pixel((i + 5) as uint, real_image_size - (j + 6) as uint, BLACK);
            }
        }
    }
    image.save(filename);
}

fn main() {
    for (z, separations) in SEGMENT_SEPARATIONS.iter().enumerate() {
        let mut segments = separations.iter().map(|&(b, e)| Segment {
            mode: Mode::Numeric, begin: b, end: e
        }).collect::<Vec<_>>();

        let variations_count = ALL_MODES.len().pow(segments.len());
        for i in range(0, variations_count) {
            let mut var = i;
            for r in segments.iter_mut() {
                r.mode = ALL_MODES[var % ALL_MODES.len()];
                var /= ALL_MODES.len();
            }
            for ec_level in ALL_EC_LEVELS.iter() {
                for mask_pattern in ALL_MASK_PATTERNS.iter() {
                    let filename = format!("results/test-{}-{}-{}-{}.bmp", z, i, *ec_level, *mask_pattern);
                    run(*ec_level, *mask_pattern, &*segments, &*filename);
                }
            }
        }
        println!("processed {}/{}", z, 8u);
    }
}


Longest Common Subsequence of Two Strings containing a particular Substring

APL (45)

⌈/0,⍴¨m/⍨∨/¨⍞∘⍷¨m←⊃∩/{/∘⍵¨↓⍉(z/2)⊤⍳2*z←⍴⍵}¨⍞⍞

Explanation:

¨⍞⍞: read two lines. For each of them:

⍳2*z←⍴⍵: get the numbers from 1 up to 2^length.
(z/2)⊤: encode each number as bits
↓⍉: separate each string of bits into its own array
/∘⍵¨: and use each of them as a bitmask on the string, giving the subsequences

m←⊃∩/: take the intersection of the two arrays of subsequences, store in m
∨/¨⍞∘⍷¨: read a third line, and see in which subsequences it occurs
m/⍨: select those elements from m that contained the third line
⍴¨: get the length of each remaining subsequence
0,: add a zero entry in case the resulting list is empty
⌈/: get the highest number in the list

Test cases:

      ⌈/0,⍴¨m/⍨∨/¨⍞∘⍷¨m←⊃∩/{/∘⍵¨↓⍉(z/2)⊤⍳2*z←⍴⍵}¨⍞⍞
ABCDEF
CDEFAB
B
 2
      ⌈/0,⍴¨m/⍨∨/¨⍞∘⍷¨m←⊃∩/{/∘⍵¨↓⍉(z/2)⊤⍳2*z←⍴⍵}¨⍞⍞
HELLO
WORLD
SUCKS
 0
      ⌈/0,⍴¨m/⍨∨/¨⍞∘⍷¨m←⊃∩/{/∘⍵¨↓⍉(z/2)⊤⍳2*z←⍴⍵}¨⍞⍞
ABCXD
BCDEF
CD
 3
      ⌈/0,⍴¨m/⍨∨/¨⍞∘⍷¨m←⊃∩/{/∘⍵¨↓⍉(z/2)⊤⍳2*z←⍴⍵}¨⍞⍞
X
Y
Z
 0


Digital River (Shortest And Fastest Solution)

C, 320 294 bytes

Compile with -std=c99

#include<stdio.h>
int s(int i){for(int j=i;j;j/=10)i+=j%10;return i;}int main(){int c=0,i;while(scanf("%d",&i)){c++;if(!i)continue;int j,o[]={1,3,9},p[]={1,3,9};Q:for(j=0;j<3;j++){if(o[j]==i)goto D;else if(o[j]<i){o[j]=s(o[j]);goto Q;}}i=s(i);goto Q;D:printf("Case #%d\n\nfirst meets river %d at %d\n\n",c,p[j],o[j]);}}

Ungolfed:

#include <stdio.h>

int s(int i)
{
    for(int j = i; j; j /= 10)
        i += j % 10;
    return i;
}

int main()
{
    int c = 0, i;
    while(scanf("%d", &i))
    {
        c++;
        if(!i)
            continue;
        int j,o[]={1,3,9},p[]={1,3,9};
        Q: for(j = 0; j < 3; j++)
        {
            if(o[j] == i)
                goto D;
            else if(o[j] < i)
            {
                o[j] = s(o[j]);
                goto Q;
            }
        }
        i = s(i);
        goto Q;
        D: printf("Case #%d\n\nfirst meets river %d at %d\n\n", c, p[j], o[j]);
    }
}

Try it out!

Essentially, the "target" rivers are increased until they're greater than the river we're testing against, and afterwards the test river is increased. This is repeated until the test river is equal to some other river.

I'm not reading parameters from the command line in this program, and I'm not sure if you're supposed to. Now you can pass parameters to STDIN. You can terminate by passing a non-numeric input.

Also darn, beaten by half an hour.


Algorithm to print the Minimum number of adjacent character swaps necessary to remove all instances of "VK" in a given string?

Japt, 44 bytes

m£Z¯Y cZtY2 Ô cZsY+2Ãrc
®¬ø"VK"
W+VÌ
Ve ?ß:W

Try it online!

It times out on the first test case because it's super inefficient (something like O(n^n)?) but it should be a viable algorithm. Input is weird; it is a singleton list containing the input, but the input itself is formatted as a list of upper-case characters. I think that would typically be valid, but if not let me know.

Explanation:

#Step 1: try all the swaps
m                          #For each string Z reachable with n swaps (n starts at 0)
 £                  Ã      # For each letter Y in Z:
  Z¯Y                      #  Get the letters before it in Z
      c                    #  Concat
       ZtY2 Ô              #  Y swapped with the following character
              c            #  Concat
               ZsY+2       #  The rest of Z
                     rc    #Flatten by one level
                           #Result: A list of all strings reachable with n+1 swaps

#Step 2: Check for "VK"
®¬         #For each string from Step 1:
  ø"VK"    # Check whether it contains "VK"
           #Result: A list where 1 indicates there was "VK" and 0 otherwise

#Step 3: Increment the counter appropriately
W+      #Increase the counter by
  VÌ    #The value for the original string when run through step 2
        #Result: 0 if 0 swaps were required, the current number of swaps otherwise

#Step 4: Iterate or end
Ve ?       #If all the reachable strings contain "VK"
    ß      # Repeat the program with the current values
     :W    #Otherwise return the counter
           #Result: Outputs the counter when a non-"VK" string is found.


Perl 5.10 - 195 198 202 203 characters

Here's an entry that does not require any libraries beyond basic regexp matching.  The encoded string is 131 characters, and the code to decode and print it takes up 64 characters (assuming no newline at the end of the source).  The idea is to represent common 3-character strings by lower case letters.

s!!xfefxxf\t\t\tf efyx
no| cnocfxefxceyxm|xmn
nm|wtnwtgt/uvy \\| 'ym|w`o|
pepyy/o| _ogrr/ _opn (ml
l lbyly|by( )fiihyjm lb,y_
\t\tf |/!;s!\w!substr'(_)\___   \_/|_| |  V \ / _',-95+ord$&,3!eg;say

The encoder is a lot longer and unfortunately not very readable right now.  The basic idea is to use dynamic programming to find the shortest encoding for each line, given a fixed set of string substitutions.  The string of substitutions on the last line was built by trial and error, and it is possible that another string of substitutions might lead to a shorter program than above.

One trick here is that some substitutions are shorter than 3 characters long: due to the way perl substr works, x is replaced by ' _' and y by '_'.  The latter is necessary because \w in the regex matches '_', which is then replaced by '(_)'.


Python 2, 220 bytes

def d(l,n,a=0,b=1.):s=sum(x//b for x in l);return s-n and d(l,n,*[a,b,(a+b)/2,b*2][s>n::2])or b
def f(l,b,n):l=[[x*(x>=b*sum(sum(l,[])))for x in r]for r in l];return[[v//d(x,sum(x)//d(map(sum,l),n))for v in x]for x in l]

Try it online!

Basically just a golf of the reference implementation...


The first, the last, and everything between

R, 39 33 30 bytes

c(a<-scan(),setdiff(a:a[2],a))

Try it online!

Thanks for saved bytes to user2390246 and J.Doe.


Proportion of strings with ascending letters

Jelly, 31 bytes

13 bytes to cater for the truncation requirement!

ØaẊ⁸Ð¡Ḋḣ€3ṢƑƇðL÷+⁵×ȷ2ḞṾs2j”.Ḋṭ⁸

A monadic link which, given an integer, yields a list.

Try it online! (footer joins the list with spaces)

If (1) we remove the truncation requirement and (2) "The letters must come from the English alphabet" implies that we may choose any subset of three or more such letters then this 16 works:

“ḃ»Ẋ⁸Ð¡⁼ƇḢ$ðL÷;⁸

Try this one (only uses A, B, and C)

If we may also avoid the unobservable creation of all the strings as part of of our code. then this 15 works:

6ẋX€ỊƇ“ḃ»ẋðL÷;⁸

Try this one (only uses A, B, and C, and does not create any unordered strings)


Ruby, 180 168 characters
gets
w=1+gets.to_i
f=*(readlines*"").chars
f.zip(f[1..-1]+s=[" "],s+f,s*w+f,f[w..-1]+s*w){|a,*b|$><<"@;V#{a}>bF#{a}<dY#{a*5}"[a>" "?(b.map{|y|y>" "?1:0}*"").to_i(2):3]}

Another Ruby implementation which takes a zip approach. You can see the second example running online.
Edit: Using readlines saves 12 characters.


3 languages (1 byte) - Pyth (A001477), MATL (A000027), Braingolf (A000217)
Q

Try Pyth online!, 0-indexed (non-negative integers)
Try MATL online!, 0-indexes (positive integers)
Try Braingolf online!, 1-indexed (triangular numbers)

How?
Q does the following:

In MATL, it means + 1, so it basically evaluates to input + 1.

In Pyth, it means input, so it just outputs the input.

In Braingolf, it is the built-in for triangular numbers.

Mini-polyglot
Pyth can be replaced by any of the following languages: GolfScript, Pyke, Brachylog or Brain-Flak.


Highest cardinality grouping of contiguous integers with minimum-sum threshold

Java (JDK), 1248 bytes

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
class TestCG{
	public static void main(String [] args) {
		int [] input = new int[] {1,4,12,6,20,10,11,3,13,12,4,4,5};
		int threshold = 12;
		List<List<Integer>> groups = new ArrayList<>();

		int currentGroupSum = 0;
		int previousGroupSum = 0;

		int maxGroupSum = 0;
		int boundaryValue = 0;
		List<Integer> currentGroup =  new ArrayList<>();

		for(int i=0; i<input.length; i++) {
			currentGroup.add(input[i]);
			currentGroupSum+=input[i];

			if(currentGroupSum>=threshold) {
				if(i<input.length-1) {
					boundaryValue = input[i+1];
				}

				if(currentGroupSum>maxGroupSum) {
					maxGroupSum = currentGroupSum;
				}

                if(currentGroupSum > previousGroupSum && (currentGroupSum - boundaryValue)>=threshold) {

                	groups.get(groups.size()-1).add(boundaryValue);
                	currentGroup.remove(0);
                }

				previousGroupSum = currentGroupSum;

				currentGroupSum = 0;
				groups.add(currentGroup);
				currentGroup = new ArrayList<>();
			}
		}
		System.out.println(groups.size());

		for(List<Integer> group : groups) {
			System.out.println(group);
		}
	}

}

Try it online!

Complexity O(n)


Python, 232 213 157 143 135 132 chars (shortest path)

This implementation can handle all of the edge cases described (loops, dead ends, orphan pages etc.) and guarantees that it will find the shortest route to the ending. It is based on Djikstra's shortest path algorithm.

import sys
l=[k.split()for k in sys.stdin]
s={"100":"100"}
while"1"not in s:
 for i,j in l:
    if j in s:s[i]=i+" "+s[j]
print s["1"]