Take It or Leave It II: A Game Show for Computers

Groovy $713337 $817829 $818227

Bootstrap code:

class Instance {
    List values = new ArrayList(1..10000); {
        Collections.shuffle(values)
    }
    int i = 0
    int value = 0
    int max = 0
    int nextOracle = 0

    def pass() {
        if (i >= 10000)
            throw new NoSuchElementException()
        i++
    }

    def take() {
        if (i >= 10000)
            throw new NoSuchElementException()
        int v = values[i]
        if (v > max) {
            max = v
            value += v
        }
        i++
    }

    double oracle(int m) {
        if (m <= 0 || i < nextOracle || i + m >= 10000)
            throw new NoSuchElementException()

        nextOracle = i + m
        values.subList(i + 1, i + m + 1).stream().reduce { l, r -> r+l }.get() / m
    }

    int read() {
        if (i >= 10000)
            throw new NoSuchElementException()
        values[i]
    }
}

Algorithm

double square(double v) { v * v }
final double factor = Math.pow(1.5, 1.1)
int attempts = 5000
(1..attempts).stream().parallel().mapToLong {
    def puzzle = new Instance()

    int[] memory = 1..10000 // We will remember every envelope
    int memStart = 0

    while (memStart < 10000 - 3) {
        int value = puzzle.read()
        int i = Arrays.binarySearch(memory, memStart, 10000, value) - memStart
        if (i < 0) { // We can't use the money
            puzzle.pass()
            continue
        }
        if (i == 0) { // Of course we take the lowest
            puzzle.take()
            memStart++
            continue
        }
        int remaining = Arrays.stream(memory, i + 1 + memStart, 10000).sum() // Money we could win if taken
        int losing = Arrays.stream(memory, memStart, memStart + i).sum() // Money we cna't win if taken
        if (value > losing) { // If we pass, we lose money automatically
            puzzle.take()
            memStart += i + 1
        } else if ((losing - value * 16 / 7) * square(Math.log(i)) > remaining / factor) {
            System.arraycopy(memory, memStart, memory, ++memStart, i)
            puzzle.pass()
        } else {
            puzzle.take()
            memStart += i + 1
        }
    }

    // It's broken down to last three elements
    List values = Arrays.copyOfRange(memory, 10000 - 3, 10000)
    while (!values.contains(puzzle.read())) // Skip values we can't use
        puzzle.pass()
    int value1 = puzzle.read()
    int value2 = puzzle.oracle(1)
    if (value1 == values.max() && (
            values.contains(value2)
            ? (value1 * 2 < values.sum() && values.min() == value2)
            : (value1 < values.min() / 2 + (values - [value1]).max())
            )) {
        puzzle.pass()
    }

    // Finish it
    while (puzzle.i < puzzle.values.size()) {
        puzzle.take()
    }

    puzzle.value as Long
}.sum() / attempts // Sum runs and average

I compare remaining values with possible values. This script is not fast (takes 1-minute per 1000x simulations)... but it will perform the simulations simultaneously.

I have no idea why my algorithm works, but it was just trial and error: lumping mathematical operations together and manipulating the constants. I ran it 5000x for the current score, in an attempt to reduce the score's fluctuations (it's +/- $4000 depending on iteration count).

Even without the oracle at the end, it should still be (barely) beating @orlp's solution for the prior puzzle.


Ruby 319 313 310 304 287 283

F=->s{l=s.split ?\n
b=[]
t={}
[*0...m=l.size].product([*0...n=l[0].size]).map{|y,x|c=l[y][x]
c!=' '&&c>?Z?b<<[c,y,x]:t[c.downcase]=[y,x]}
b.map{|q|c,y,x=q
u,i=t[c]
(m*n).times{|w|e=([u-(y+w)%m,i-(x+w)%n].map &:abs).max
e>c.ord-97||q<<w+e}
q[3]&&[q[3],q[0]]}.compact.sort.map{|a,b|b}}

This is a function that takes as input a string (without trailing newline) and returns an array of the lowercase letters in the correct order.
Here's a version you can run online with tests: http://ideone.com/5jiwLq
I've made a lot of modifications to the code. The history of modifications is available here.
Here's the indented and annotated version to make it easier to see what's going on (also available online):
F=->s{
  l=s.split ?\n
  m=l.size
  n=l[0].size

  # Make an array with lowercase letters and their coords (`b`)
  # Make a hash that for each target (uppercase letter) holds
  # its coordinates
  b=[]
  t={}
  [*0...m].product([*0...n]).map{|y,x|
    c=l[y][x]
    c!=' '&&(c>?Z?b<<[c,y,x]:t[c.downcase]=[y,x])
  }

  # `l` is a function that, given an array of the form
  # [lowercase_letter, y-coord, x-coord] will append to that array
  # the number of steps required for the letter to reach its
  # uppercase correspondent
  l=->q{
    c,y,x=q
    u,i=t[c]
    d=c.ord-97
    (m*n).times{|w|
      e=([u-y,i-x].map &:abs).max
      e<=d&&q<<w+e
      y=(y+1)%m
      x=(x+1)%n
    }
  }

  # apply function `l` to each of the lowercase letters...
  b.map &l

  # ...then sort accordingly and return the array
  b.map{|x|[x[3],x[0]]}.select{|a,b|a}.sort.map{|a,b|b}
}


My first attempt to this, a relatively simple solution. It fires a couple of glider barrels. Each pair of gliders turns into a block, which then form the text. This process takes about 16000 generations (you can set a frame skip or use the superstep button in my simulator).

Direct Link. Move around with right mouse, zoom with mouse wheel.

Link to .rle file (also works with Golly)

Image of the pattern 32:1:


Python 2, 61 bytes

f=lambda n:-~n*(`sorted(`n+1`)`[2::5]in'0123456789')or f(n+1)

Try it online!


JavaScript, 114 bytes

x=>RegExp(`^(?!.*([./](-|(?!xn)[^/]{2}--)|-[./]|-$))https?://${a='[a-zA-Z0-9-]{0,63}'}(?:\\.${a}){0,127}`).test(x)

Hopes it works.

For real URLs, you should use:

x=>eval(`try{new URL(x)}catch(e){}`)

Thanks to ThePirateBay, construct regex from string save 3 bytes.


Draw the Ionising Radiation Hazard Symbol

BBC BASIC, 200 bytes

f=500
g=1/SQR(3)
CIRCLE FILLf,f,f
GCOL15
MOVE-100,f
MOVEf,f
PLOT85,f*(1-g),0
MOVE1100,f
MOVEf,f
PLOT85,f*(1+g),0
MOVEf*(1-g),2*f
MOVEf,f
PLOT85,f*(1+g),2*f
CIRCLE FILLf,f,150
GCOL0
CIRCLE FILLf,f,100

Somehow outgolfing Python, this works by drawing a large black circle, filling in the white triangular sections, drawing a central white circle and finally drawing the central black circle.


J, 12 bytes

|./.&.|:&.|.

Defines an anonymous verb.
Try it online!

Explanation

|./.&.|:&.|.
|.            Reversed
  /.          anti-diagonals
    &.        under
      |:      transpose
        &.    under
          |.  reversal

In J, u &. v (read: u under v) means "v, then u, then inverse of v".
Reversal and transpose are self-inverses, so the program really means "reverse, transpose, extract reversed anti-diagonals, transpose, reverse".

With example input:

abcd
1234
WXYZ

Reverse:

WXYZ
1234
abcd

Transpose:

W1a
X2b
Y3c
Z4d

Extract reversed anti-diagonals (and pad with spaces):

W
X1
Y2a
Z3b
4c
d

Transpose:

WXYZ4d
 123c
  ab

Reverse:

  ab
 123c
WXYZ4d


Enumerate all palindromic numbers (in decimal) between 0 and n

Perl 5.10, 29 (or 39) characters

say for grep$_==reverse,0..<>

Needs the say feature enabled. 29 chars if you consider that to be free,  otherwise 39 to add use 5.010;. Argument on STDIN.

Perl, 35 characters

#!perl -l
print for grep $_==reverse,0..<>

using the old perlgolf convention that #!perl is not counted but any flags following it are.

Perl, 36 characters

print$_,$/for grep $_==reverse,0..<>

If none of the others qualify.


Pyth - 10 bytes
A valid answer. Uses Wilson's Theorem.
.f%h.!tZZQ

Try it online here.

Old answer
Pyth - 6 chars
Uses builtin for prime factorization, not prime checking.
.ftPZQ

Try it online here.
.f  Q         First n that passes filter of lambda Z, uses input for how many
 t            Tail. This makes all that have len-one prime factorization become empty list, and thus falsey.
  P           Prime factorization - primes have a len-one factorization.
   Z          Lambda var


JavaScript (ES6),  46 41  37 bytes

n=>(g=p=>--n?g(g[p]-n|0,g[p]=n):p)(0)

Try it online!
How?
We don't need to store the full sequence. We only need to keep track of the last position of each integer that appears in the sequence. We use the underlying object of the recursive function \$g\$ for that purpose.
For a given term \$p\$, we don't need either to set \$g[p]\$ to its actual absolute position in the sequence because we're only interested in the distance with the current position. That's why we can just store the current value of the input \$n\$, which is used as a decrementing counter in the code.
Therefore, the distance is given by \$g[p]-n\$. Conveniently, this evaluates to NaN if this is the first occurrence of \$p\$, which can be easily turned into the expected \$0\$.
Commented
n => (             // n = input
  g = p =>         // g = recursive function taking p = previous term of the sequence
                   //     g is also used as an object to store the last position of
                   //     each integer found in the sequence
    --n ?          // decrement n; if it's not equal to 0:
      g(           //   do a recursive call:
        g[p] - n   //     subtract n from the last position of p
                   //     if g[p] is undefined, the above expression evaluates to NaN
        | 0,       //     in which case we coerce it to 0 instead
        g[p] = n   //     update g[p] to n
      )            //   end of recursive call
    :              // else:
      p            //   we've reached the requested term: stop recursion and return it
)(0)               // initial call to g with p = 0


Ruby, 266 250 242 bytes

->n,*z{j=(h=1,m=1i,-1,*r=[-m,0]).product h;(r.map{|c|j.map{|v,w|k=r+[v+=c,v+w];k|k==k&&(w=j.map{|y,q|(x=k.map{|v|y*[v,v.conj][q*q]}).map{|g|g-x.map(&:real).min-m*x.map(&:imag).min}.sort_by &:rect})-z==w&&z<<w[0]}};r,*z=z)until r[-n];z.size+1}

Try it online!
Not particularly original, I just recycled my solution to a similar problem, and changed some small details:

start with the basic domino (instead of single tile)
add 2 tiles on each step (instead of one)
check for reflection by using the complex conjugate (instead of only rotation using powers of i)
stop when reaching size 2n (instead of n) -> Accept 2n as input

How it works:
See the linked post for the full explanation. Basically, use complex numbers to make it easier.
Performance:
43 seconds for n=5 (size 10) on TIO
Thanks Dingus for saving some bytes, the function is a mess and could probably be much shorter anyway if implemented properly.


CJam, 31 27 bytes

l:I{mr[_I]{_,((,\f>3f<}/&}g

Test it here.

Same approach as my Mathematica answer. It keeps generating random permutations of the input, until the substring restriction is satisfied. I think this can be golfed a bit further.


SOGL V0.12, 53 bytes

LA0≠?.θ«IA}a∫H.¡*»:B┌* 8+Ƨ<=F2%W+a»b-@*+.0<?↔±}1¼UU░P

Try it Here!


compute number of 1 bits in a binary representation of a number

C/C++
int popcnt(int n)
{
    return __builtin_popcount(n);
}

For some CPUs __builtin_popcount compiles to a single instruction (e.g. POPCNT on x86).
Note: requires gcc or gcc-compatible compiler (e.g. ICC).


Python 2, 204 202 bytes

def f(l,s=''):
 if all(w in s for w in l):return s
 for i,w in enumerate(l):
	a=next((s+w[i:]for i in range(len(w)-1,0,-1)if s[-i:]==w[:i]),0)if s else w;x=a and f(l[:i]+l[i+1:]+[l[i]],a)
	if x:return x

Try it online!

Saved

-2 bytes, thanks to recursive


BASH, 396 - 11 = 385 bytes

E='echo -en';$E "\e[2J\e[99A";while :;do sleep 0.01;for i in `seq $((($1+1)/2)) -1 1`;do p=$(((($1+1)/2 - $i)));[ $p -lt 0 ]&&p=$((-$p));p=$((2**(p+1)));if [ $RANDOM -lt $((32768/$p)) ];then [ $(($RANDOM%2)) -eq 1 ]&&i=$((($1+1)-i));sector=$(((i*2-1)-1));C=`tput cols`;R=`tput lines`;SS=$((C/($1*2-1)));SX=$((SS*sector));X=$((SX+(RANDOM%SS)));Y=$((RANDOM%R));$E "\e[$Y;${X}H*";break;fi;done;done

Unfortunately I cannot demonstrate this on TryItOnline because of the endless loop & ANSI escape sequences that move cursor, but you can still copy-paste it into your terminal!

Unminified version:

E='echo -en'
$E "\e[2J\e[99A"

while :
do
    sleep 0.01
    for i in `seq $((($1+1)/2)) -1 1`
    do
        p=$(((($1+1)/2 - $i)))
        [ $p -lt 0 ] && p=$((-$p));
        p=$((2**(p+1)))
        if [ $RANDOM -lt $((32768/$p)) ]
        then
            [ $(($RANDOM%2)) -eq 1 ] && i=$((($1+1)-i));
            sector=$(((i*2-1)-1))
            C=`tput cols`
            R=`tput lines`
            SS=$((C/($1*2-1)))
            SX=$((SS*sector))
            X=$((SX+(RANDOM%SS)))
            Y=$((RANDOM%R))
            $E "\e[$Y;${X}H*"
            break
        fi
    done
done


Mathematica, 220 218 bytes

For[n=1,1>0,n++,For[m=1,1>0,m++,x=Array[a,{m,n}];d=Table[(Norm[x[[i]]-x[[j]]]^2-1)*(Norm[x[[i]]-x[[j]]]^2-y)==0,{i,1,m-1},{j,i+1,m}];If[Not[CylindricalDecomposition[Flatten@{d,y>0},Flatten@{y,x}]],Break[]]];Print[m-1]]

Try it online! Un-golfed version:

For[ n = 1, 1>0, n++,
  For[ m = 1, 1>0, m++,
   x = Array[a, {m, n}];
   d = Table[(Norm[x[[i]] - x[[j]]]^2 - 1)*(Norm[x[[i]] - x[[j]]]^2 -
         y) == 0, {i, 1, m - 1}, {j, i + 1, m}];
   If[Not[
      CylindricalDecomposition[Flatten@{d, y > 0}, Flatten@{y, x}]],
      Break[]]
  ];
  Print[m - 1]
]

In this code, we apply a key tool from real algebraic geometry. A semialgebraic set is a subset of \$\mathbb{R}^d\$ defined by polynomial equalities and inequalities. We may identify the set of 2-distance subsets of \$\mathbb{R}^n\$ of cardinality \$m\$ with a semialgebraic subset of \$\mathbb{R}^{mn+2}\$. We force one of the distances to equal 1 without loss of generality, which means our semialgebraic set is a subset of \$\mathbb{R}^{mn+1}\$. We denote the other distance (squared) by \$y\$.

For which values \$Y\subseteq\mathbb{R}\$ of \$y\$ does there exists a size-\$m\$ subset of \$\mathbb{R}^n\$ with squared distances \$\{1,y\}\$? This can be answered with the help of Tarski--Seidenberg, which says that the projection of any semialgebraic set is semialgebraic. In our case, this means there is some univariate polynomial \$p\$ and relation \$*\in\{=,<,\leq\}\$ such that \$Y=\{y\in\mathbb{R}:p(y)*0\}\$. This projection may be accomplished using cylindrical algebraic decomposition (CAD), which enjoys an implementation in Mathematica.

Given a set of polynomial equalities and inequalities, as well as an ordered list of variables, Mathematica's implementation returns either an explicit description of every point in the corresponding semialgebraic set, or False if the set is empty. In the above code, we run CAD for increasingly larger values of \$m\$ until we get False, at which point we know that \$s_n=m-1\$. Sadly, the runtime of CAD is doubly exponential in the number of variables, and so we shouldn't expect this approach to determine \$s_9\$ any time soon. In fact, a minute of runtime only gives \$s_1=3\$.


Tips for golfing javascript code, especially converting while loop to expression

I think the best way to get rid of the curly brackets is to go recursive.

Original function (46 bytes)

t.s=_=>{o="";while(i=t.o()){o+=i+","}return o}

Recursive version (29 bytes)

t.s=_=>(i=t.o())?i+[,t.s()]:i

The i+[,t.s()] trick saves a byte over i+','+t.s().

Because you stop when t.o() returns null, the result of your original version always ends with a comma. In the new version, we actually append null at the end (that's the :i) but it's coerced to an empty string because of the above trick, leading to the same behavior.


Mathematica - 81 78 75 72 67 65 62 56 bytes

I haven't golfed anything in Mathematica before, so I suppose there's room for improvement. This one doesn't quite conform to the rules due to the Partition and Tally functions, but it's quite neat so I thought I'd post it anyway.

f=N@Tr[-Log[p=#2/Length@b&@@@Tally[b=##~Partition~1]]p]&

This works with any set of symbols, and can be used like

sequence = {2, 3, 4, 1, 2, 3, 0, 0, 3, 2, 3, 0, 2, 2, 4, 4, 4, 1, 1,
   1, 0, 4, 1, 2, 2, 4, 0, 1, 2, 3, 0, 2, 3, 2, 3, 2, 0, 1, 3, 4, 4,
   0, 2, 1, 4, 3, 0, 2, 4, 1, 0, 4, 0, 0, 2, 2, 0, 2, 3, 0, 0, 4, 4,
   2, 3, 1, 3, 1, 1, 3, 1, 3, 1, 0, 0, 2, 2, 4, 0, 3, 2, 2, 3, 0, 3,
   3, 0, 0, 4, 4, 1, 0, 2, 3, 0, 0, 1, 4, 4, 3};
f[sequence, 3]

> 4.06663

Here is a somewhat ungolfed version:

f[sequence_, m_] := (
    blocks = Partition[sequence, m, 1];
    probabilities = Apply[#2/Length[blocks] &, Tally[blocks], {1}];
    N[Tr[-Log[probabilities]*probabilities]]
)

It will probably run faster if I apply N directly to the result of Tally.

By the way, Mathematica does actually have an Entropy function, that reduces this to 28 bytes, but that's definitely against the rules.

f=N@Entropy@Partition[##,1]&

On the other hand, here is a 128 byte version that reimplements Partition and Tally:

f=N@Tr[-Log[p=#2/n&@@@({#[[i;;i+#2-1]],1}~Table~{i,1,(n=Length@#-#2+1)}//.{p___,{s_,x_},q___,{s_,y_},r___}:>{p,{s,x+y},q,r})]p]&

Ungolfed:

f[sequence_, m_] := (
    n = Length[sequence]-m+1; (*number of blocks*)
    blocks = Table[{Take[sequence, {i, i+m-1}], 1},
                   {i, 1, n}];
    blocks = b //. {p___, {s_, x_}, q___, {s_, y_}, r___} :> {p,{s,x+y},q,r};
    probabilities = Apply[#2/n &, blocks, {1}];
    N[Tr[-Log[probabilities]*probabilities]]
)


Perl, 47 43 41 + 1 = 42 bytes
-4 bytes thanks to @Sunny Pun.  -2 bytes thanks to @Brad Gilbert b2gills and @Downgoat
Run with the -n flag.
say!/^(s(in?)?|co?|t(an?)?|ln?|log?|e)+$/

It can definitely be golfed futher, but in the spirit of competition, I'm leaving the mostly-original regex I came up with at the beginning.
Returns nothing if true, 1 if false.
Try it online!
I downloaded a dictionary file, and the longest word I found was 11 letters -- tattletales


Linear interpolation of the Fibonacci sequence

Jelly, 5 bytes
_Ḟ1+¡

This is an iterative solution without built-ins. It uses the same indexing as the challenge spec.
Try it online!
Background
Let f be the function defined in the challenge spec and F the Fibonacci function defined as usual (i.e., with F(0) = 0). For a non-negative integer n, we have f(n) = F(n + 1). When 0 ≤ x < 1, the challenge spec defines f(n + x) as f(n) + (f(n + 1) - f(n))x.
Clearly, this just affects the base cases, but not the recursive formula, i.e., f(n) = f(n - 1) + f(n - 2) holds as it would for F. This means we can simplify the definition for non-integer arguments to the easier f(n) = f(n) + f(n - 1)x.
As others have noted in their answers, the recursive relationship also holds for non-integer arguments. This is easily verifiable, as

Since f(0) = f(1) = 1, f in constant in the interval [0, 1] and f(0 + x) = 1 for all x. Furthermore, f(-1) = F(0) = 0, so f(-1 + x) = f(-1) + (f(0) - f(-1))x = 0 + 1x = x. These base cases cover in [-1, 1), so together with the recursive formula, they complete the definition of f.
How it works
As before, let n + x be the only argument of our monadic program.
¡ is a quick, meaning that it consumes some links to its left and turns them into a quicklink. ¡ in particular consumes either one or two links.

<F:monad|dyad><N:any> calls the link N, returning r, and executes F a total of r times.

<nilad|missing><F:monad|dyad> sets r to the last command-line argument (or an input from STDIN in their absence) and executes F a total of r times.

Since 1 is a nilad (a link without arguments), the second case applies, and +¡ will execute + n times (a non-integer argument is rounded down). After each call to +, the left argument of the quicklink is replaced with the return value, and the right argument with the previous value of the left argument.
As for the entire program, Ḟ floors the input, yielding n; then _ subtract the result from the input, yielding **x, which becomes the return value.
1+¡ then calls +¡ – as described before – with left argument 1 = f(0 + x) and right argument x = f(-1 + x), which computes the desired output.


Jelly, 20 bytes

ASŒRḅ@Ðḟ
J’U×µṖÇḅ@€³

Try it online!

Explanation

ASŒRḅ@Ðḟ     Helper Function; find all integer solutions to a polynomial
             All integer roots are within the symmetric range of the sum of the absolute values of the coefficients
A            Absolute Value (Of Each)
 S           Sum
  ŒR         Symmetric Range; `n -> [-n, n]`
      Ðḟ     Filter; keep elements where the result is falsy for:
    ḅ@       Base conversion, which acts like the application of the polynomial
J’U×µṖÇḅ@€³  Main Link
J                             Range of length
 ’                    Lowered
  U          Reversed
   ×         Multiplied with the original list (last value is 0)
    µ        Begin new monadic chain
     Ṗ       Pop; all but the last element
      Ç      Apply last link (get all integer solutions of the derivative)
       ḅ@€³  Base conversion of the polynomial into each of the solutions; apply polynomial to each solution of the derivative.

The helper function in this program was taken from Mr. Xcoder's answer
here which was based off of Luis's answer here


GolfScript, 19 characters
n%{'aeiouy'&,6=},n*

Usage:
golfscript vowels.gs < wordlist.txt

Output:
abstemiously
authoritatively
behaviourally
[...]
uninformatively
unintentionally
unquestionably
unrecognisably

If you also want to output the count at the end you can use
n%{'aeiouy'&,6=},.n*n@,

which is four characters longer.


Python 3, Unhexseptium (167) bytes

h=x='';r=str.replace
for i in input():s=r('nubtqphsoeinirueeecnl  ianxptn    dt t'[int(i)::10],' ','');h+=s;x+=s[0]
print(r(r(h+'ium\n','ii','i'),'nnn','nn')+x.title())

These are the results when the program is run on every number from 1 to 999 (inclusive)


Range interval insert which should split into unique ranges

Japt, 44 bytes

rò
íU c ò@Vc øX ©X¥YÃke@V®ròÃc øXÃ®gJõ0ÃcV n

Try it online!

Reworked it, at the cost of 1 byte.
Now handles the [[2,2]],[1,3] test case properly.

Explanation:

rò                                           #Turn the second input into a range
íU c                                         #Duplicate each item in that range
     ò@      ©X¥YÃ                           #Split in the middle of the duplicates that:
       Vc øX                                 # Appear in the first input
                  k                          #Remove the segments where:
                   e@       øXÃ              # Every item in the segment is in...
                     V®ròÃc                  # A range from the first input
                               ®    Ã        #For the remaining segments:
                                gJõ0         # Get the first and last items
                                     cV      #Add those pairs to the first input
                                        n    #Sort the whole thing

Worked Example:

Input: [[2,2],[5,7]],[1,8]

Second input as a range: [1,2,3,4,5,6,7,8]

Duplicate each item: [1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8]

Numbers that appear in the first input: [2,5,7]

After splitting: [[1,1,2],[2,3,3,4,4,5],[5,6,6,7],[7,8,8]]

Numbers within the first input's ranges: [2,5,6,7]

Segments using only those numbers:[[5,6,6,7]]

Remaining segments after those are removed: [[1,1,2],[2,3,3,4,4,5],[7,8,8]]

First and last item of each: [[1,2],[2,5],[7,8]]

Merge with the first input: [[1,2],[2,5],[7,8],[2,2],[5,7]]

Sort it: [[1,2],[2,2],[2,5],[5,7],[7,8]]

Which matches the actual output of the code


Java 8, 505 bytes
Golfed (with help from @masterX244 for shaving a big chunk off)
class f{static boolean T(String u,String v){return u.equals(v);}public static void main(String[]a){java.util.Scanner q=new java.util.Scanner(System.in);String s=q.nextLine();int x=0;int y=0;int d=0;int[][]v={{0,1},{-1,0},{0,-1},{1,0}};int b=1;for(String r:s.split(",")){if(T(r,"o/")||T(r,"-/"))b=~1;if(b<0){if(T(r,"~-"))d=(d+3)%4;if(T(r,"-~"))d=(d+1)%4;if(T(r,"~~")){x+=v[d][0];y+=v[d][1];}if(T(r,"::")){x-=v[d][0];y-=v[d][1];}}}System.out.println("("+x+","+y+","+"NWSE".charAt(d)+")");}}

More readable
class f {
    static boolean T(String u,String v){return u.equals(v);}
    public static void main(String[] a) {
        java.util.Scanner q=new java.util.Scanner(System.in);
        String s=q.nextLine();
        int x=0;
        int y=0;
        int d=0;
        int[][] val = {
                {0,1},  // N
                {-1,0}, // W
                {0,-1}, // S
                {1,0}   // E
        };
        int b=1;
        for (String r: s.split(",")) {
            // toggle b if either start or stop engine
            if(T(r,"o/") || T(r,"-/"))
                b=~1;
            if(b<0){
                // right
                if(T(r,"~-")) d=(d+3)%4;
                // left
                if(T(r,"-~")) d=(d+1)%4;
                // come forward
                if(T(r,"~~")) {
                    x+=val[d][0];
                    y+=val[d][1];
                }
                // move back
                if(T(r,"::")) {
                    x-=val[d][0];
                    y-=val[d][1];
                }
            }
        }
        System.out.print("("+x+","+y+","+"NWSE".charAt(d)+")");
    }
}


C - 144 characters

main(c){putch((c=getch())>33?c:"_#$%&-()*}w[vz0123456789SsW]VZ@AXJE>UIDCHTNMBRL\"POYGK<QF:/\\
=^{`axje.uidchtnmbrl'poygk,qf?|+~"[c-34]);main(0);}


JavaScript (Node.js), 74 bytes

n=>Buffer("BKMMOMOMMLMKMMOMOMNKLKLMKLKIKKJHJKJIEDDE").every(c=>(n-=c)>0)-n

Try it online!
Commented
n =>              // n = input year
  Buffer(         // build a buffer consisting of
    "BKMM...EDDE" // the year deltas encoded as ASCII codes
  )               // 'B' -> 66, + 'K' (75) -> 141, etc.
  .every(c =>     // for each value c in there:
    (n -= c)      //   subtract c from n
    > 0           //   and go on while the result is positive
  )               // end of every(), which yields false
  - n             // return -n


Haskell, 48 38 29 bytes

-10 bytes due to TFeld's gcd trick!
-7 bytes thanks to HPWiz for improving the co-primality test and spotting a superfluous space!
-2 bytes thanks to nimi for suggesting an infix-operator!
(a!b)c=a<b&&a+b==c&&gcd a b<2

Try it online!
Explanation
The first two conditions a < b and a + b == c are fairly obvious, the third one uses that \$\gcd(a,b) = \gcd(a,c) = \gcd(b,c)\$:
Writing \$\gcd(a,c) = U \cdot a + V \cdot c\$ using Bézout's identity and substituting \$c = a + b\$ gives:
$$
U \cdot a + V \cdot (a + b) = (U + V) \cdot a + V \cdot b
$$
Since the \$\gcd\$ is the minimal positive solution to that identity it follows that \$\gcd(a,b) = \gcd(a,c)\$. The other case is symmetric.


CJam, 11 bytes
rr{irie\r}h

How it works
This is a slightly different approach, in which I simply run a do-while loop till I have pairs of numbers left in the input.
r                 e# Read the first string
 r                e# Read the first number of the first number pair in the input
  {      }h       e# Do a do-while loop
   i              e# Convert the first number from the pair to integer
    ri            e# Read the second number from the pair and convert to intger
      e\          e# String X Y e\ works by swapping the Xth index with the Yth index in the
                  e# String
        r         e# This is our exit condition of the do-while loop. If we still have
                  e# a number on the input left, that means there are more pairs to swap.
                  e# Otherwise, we exit the loop and the result is printed automatically

Try it online here


Find the number of x-digit numbers whose product of digits is N

Golfscript 42 31

~10\?.10/\,>{10base{*}*1$=},,\;

Input: Expects the numbers N and x as command line arguments (separated by space).

The program can be tested here.


type in a random mess of capital letters

Python 3, 59 bytes

i=input()
while i:print(end={i,i.upper()}.pop()[0]);i=i[1:]

Try it online!

-4 bytes thanks to Chas Brown

Uses set.pop() to randomize.


Husk, 18 bytes

m←ġ(←►Lk=mȯmLgpṫ)N

Try it online!
This prints the infinite list.
The link truncates the result to the first 7 values, since the program is quite inefficient and times out after that on TIO.

The parentheses are ugly, but I don't know how to get rid of them.

Explanation

m←ġ(←►Lk=mȯmLgpṫ)N  No input.
                 N  The list of natural numbers [1,2,3,4,..
  ġ(            )   Group into slices according to this function.
                    Each slice corresponds to a run of numbers with equal return values.
    ←►Lk=mȯmLgpṫ    Function: from n, compute the reduced factorization leader in [1..n].
                     As an example, take n = 12.
               ṫ     Reversed range: [12,11,10,9,8,7,6,5,4,3,2,1]
         m           Map over this range:
              p       Prime factorization: [[2,2,3],[11],[2,5],[3,3],[2,2,2],[7],[2,3],[5],[2,2],[3],[2],[]]
             g        Group equal elements: [[[2,2],[3]],[[11]],[[2],[5]],[[3,3]],[[2,2,2]],[[7]],[[2],[3]],[[5]],[[2,2]],[[3]],[[2]],[]]
          ȯmL         Take length of each run: [[2,1],[1],[1,1],[2],[3],[1],[1,1],[1],[2],[1],[1],[]]
       k=            Classify by equality: [[[2,1]],[[1],[1],[1],[1],[1]],[[1,1],[1,1]],[[2],[2]],[[3]],[[]]]
                     The classes are ordered by first occurrence.
     ►L              Take the class of maximal length: [[1],[1],[1],[1],[1]]
                     In case of a tie, ► prefers elements that occur later.
    ←                Take first element, which is the reduced factorization leader: [1]
                    The result of this grouping is [[1,2],[3,4,..,57],[58,59,60],[61,62,63,64],..
m←                  Get the first element of each group: [1,3,58,61,65,73,77,..


Need help golfing Python 3 code to calculate volume & surface of spheroids in <150 bytes

122 bytes

from cmath import*
def golf(C,A):e=sqrt(1-A*A/C/C);return round(pi/6*A*A*C,2),round(pi*A*abs(A+(e and C*asin(e)/e-A)/2),2)

The sphere can be special-cased by returning surface area πA² if e = 0.

While there are two different formulae for oblate and prolate spheroids, they are mathematically equivalent. If the involved operations support complex numbers, each formula can be used for both cases.

Since asin(e)/e will return a complex number of the form x+0j for prolate spheroids, abs can be used to turn it into the float x.


(GolfScript, 15 13 characters)
:;{.;?);>?)},

GolfScript is not one of the top 20, but a codegolf without GolfScript... (run it yourself)
Previous Version:
(run script)
1/:;{;\-,;,(<},


add commas to Numbers without String manipulation

You weren't very specific on the output format...

Haskell, 56

reverse.takeWhile(>0).map(`mod`1000).iterate(`div`1000)

example:

GHCi> reverse.takeWhile(>0).map(`mod`1000).iterate(`div`1000)$93842390862398
[93,842,390,862,398]


JavaScript (ES6), 225 212 bytes
Saved 4 bytes thanks to @l4m2
s=>`#${s}#`.replace(/./g,c=>'0202020202'.replace(/./g,(j,k)=>[C='█',C+C+C,' ','   '][(i="%+/$U1AKV2BLW3CMX4DNY5EOZ6FP-7GQ.8HR 9IS#0JT".indexOf(c),[170,257,260,5,272,17,20,320,65,68,80][i>>2]^2<<i%4*2)>>k&1|j]))

Try it online!
How?
The table can be rearranged such that the 9-bit binary mask of the character is quickly deduced from its row and column using the following formula:
n = m XOR (2 << k)

with:
  m  | k: 0   2   4   6
-----+------------------      Examples:
 170 |    %   +   /   $
 257 |    U   1   A   K         'G' = 320 XOR (2 << 4) = 320 XOR 32 = 352
 260 |    V   2   B   L
   5 |    W   3   C   M         '+' = 170 XOR (2 << 2) = 170 XOR 8  = 162
 272 |    X   4   D   N
  17 |    Y   5   E   O
  20 |    Z   6   F   P
 320 |    -   7   G   Q
  65 |    .   8   H   R
  68 |   spc  9   I   S
  80 |    #   0   J   T


Python 2, 123 122 bytes

def f(p,P):R=[[[a/-~b,b+1]for a,b in F]for F in P];a,b=map(lambda F,x:sum(a*x**b for a,b in F),R,p);R[1]+=[a-b,0],;print R

Try it online!

Straight-forward implementation. A function that takes arguments in the form (y, x), (N, M), and prints the resulting 2 polynomials to STDOUT.


Recursively count lines of code, excluding empty lines and comments

PowerShell, 47 46 bytes

ls *.sh -r|gc|%{$o+=!($_-match'^\s*(#|$)')};$o

Try it online! (will always return 0 since there aren't any files)

Try it online! (here's a link that populates a dummy file so you can see the process)

-1 byte thanks to Neil

ls is alias for Get-ChildItem, specifying *.sh with the -recurse parameter, then we get-content of files. For each of those lines |%{...}, we accumulate into our $output a one if the Boolean !(...) statement is truthy. Inside the statement is a simple regex -match against the whitespace-only/comment/blank lines. Finally we leave $o on the pipeline.

The implicit Write-Output that happens at program completion adds a trailing newline, but that shouldn't matter in this case because the variable $o itself doesn't have a trailing newline nor does the actual return variable. It's a quirk of the shell, not a quirk of the program. For example, saving this to a script and executing that script in a pipeline will not have a newline.


Haskell: 291 chars

Another solution which terminate only if there is a solution without any collision (5 and 6). It is also very fast:

import System.Environment
import Data.List
a n=[(x,y)|x<-[1..n],y<-[1..n],x<y]
s []=[[]]
s (m:[])=[[m]]
s ((x,y):(x',y'):xs )
 |(x==x')||(x==y')||(y==x')||(y==y')=s((x,y):xs++[(x',y')])
 |0<1=[(x,y):ys|ys<-s((x',y'):xs)]
main=do
 args <- getArgs
 print $ head $ s $ a (read(head args)::Int)


05AB1E, 20 bytes

WU|vy#Â‚ø€¥˜Ä2ä`OX*,

Explanation

WU                    # store minimum cost in X
  |v                  # for each testcase
    y#                # convert to list split on spaces
      Â‚ø             # zip with its own reverse
         €¥           # deltas of each pair
           ˜Ä         # deep flatten and take absolute value
             2ä       # split into 2 pieces
               `      # flatten (leaves the smaller piece on top of the stack)
                O     # sum
                 X*   # multiply with minimum cost
                   ,  # print

Try it online!


Shortest code - Finding the kth good cipher

Perl, 75 74 characters

map{map{1while++$n=~/[13579]|(.+)(?(?{$^N<1|$^N%11})!)/}1..<>;$n=say$n}1..<>

I should point out that the character count is taking advantage of Perl's bizarre feature of allowing a special variable of the form $^X to be spelled with a literal ctrl-X character.

The regex extensions being utilized are also terrifying, but boy do they come in handy.


Python 2, 133 bytes
I used binary operations to keep track. I had if(i<1)*b:... but I think that's an off-by-one error. Not sure.

from random import*
L=2**99-1
b=l=c=0
while l<99:
    i=randint(0,99)
    if(i>98)*b:b=0;l+=1
    elif(L&1<<i)*(b<1):b=1;L|=1<<i
    c+=1
print c

Try it online
Less golfed:
from random import*
L=[1for _ in range(100)]
b=l=c=0
while l<99:                         # check leader's count of prisoners
    i=randint(0,99)
    if b and i==99:b=0;l+=1         # if light on and leader, turn off and count
    elif L[i] and b<1:b=1;L[i]=0    # else if new prisoner and light off, turn on
    c+=1                            # iterations
print c


Jelly, 14 12 bytes

J’Æ²œṗZ⁻¦µU⁼

Try it online!

Background

We start by looking at the 0-based indices of the input string.

 H  H  e  H  H  e  l  e  H  H  e  l  l  l  e  H  H  e  l  l  o  l  l  e  H
 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

To get the rows of the triangle, we can split the string before the indices 1, 1 + 3 = 4, 1 + 3 + 5 = 9, and 1 + 3 + 5 + 7 = 16. Since (n + 1)² = n² + (2n + 1), these sums are precisely the positive, perfect squares in the index list. If we also split the string before 0, this is as simple as splitting before all 0-based indices that are perfect squares.

After splitting, we get the following strings.

""
"H"
"HeH"
"HeleH"
"HellleH"
"HellolleH"

Next, we replace the empty string at the beginning with all the characters in the first column.

"HHHHH"
"H"
"HeH"
"HeleH"
"HellleH"
"HellolleH"

The task is now reduced to checking whether reversing all strings yields the same string array.

How it works

First J generates all 1-based indices of the input string J, then decrements them with ’ to yield all 0-based indices. Æ² tests all 0-based indices for squareness. For our example from above, this yields the following Boolean array.

 1  1  0  0  1  0  0  0  0  1  0  0  0  0  0  0  1  0  0  0  0  0  0  0  0

Next, we call œṗ to partition the input string, e.g.,

 H  H  e  H  H  e  l  e  H  H  e  l  l  l  e  H  H  e  l  l  o  l  l  e  H

before all 1's (actually, all truthy elements). For our example, this yields the following string array.

['',
 'H',
 'HeH',
 'HeleH',
 'HellleH',
 'HellolleH'
]

Z⁻¦ is arguably the most interesting part of this answer. Let's analyze the more straightforward Z1¦ first.

¦ is the sparse quick. It consumes two links from the stack, specifically 1 and Z in this case. First Z is applied to its argument: the string array from before. Z is the zip atom and reads the string array / 2D character array by columns, yielding

['HHHHH',
 'eeee',
 'Hlll',
 'ell',
 'Hlo',
 'el',
 'Hl',
 'e',
 'H'
]

What used to be left side of the input string and the first column of the string array now becomes the first string.

Now ¦ peeks at 1 and finds a single index: 1. Thus the first string in the original string array is replaced with the first string in the return value of Z; strings at other indices remain unaffected.

['HHHHH',
 'H',
 'HeH',
 'HeleH',
 'HellleH',
 'HellolleH'
]

Let's call this array A.

We used Z⁻¦ instead of Z1¦, but this makes no difference: ⁻ compares the string array with the input string for inequality, yielding 1 since they're not equal. The difference between the two is that Z⁻¦ is dyadic because ⁻ is, allowing us to write œṗZ⁻¦ instead of œṗ¹Z1¦. This is because a dyad (œṗ) followed by a monad (œṗ¹Z1¦) is a fork (the monad is applied to the chain's argument / the input string, and the returned value is passed as the right argument to œṗ), while a dyad followed by another dyad (or at the end of the chain) is a hook, i.e., its right argument is the chain's argument.

All that's left to do is check for palindromicness. µ begins a new (monadic) chain who's argument is A. The upend atom U reverses all strings in A (but not A itself), then ⁼ compares the result with A for equality. The returned Boolean 1 indicates a fully-palindromic triangle; other strings would return 0.


C, 134

n,m,c,p;
main(r){
for(scanf("%d",&n),m=--n?n*2:1;n+r--;puts(""))
for(c=-1,p=1;c++<25;)
p+=(c-n-r)%m*((c-n+r)%m)?1:1-printf("%*c",p,c+65);
}

Compiles on gcc with a few warnings. Newlines aren't included in the character count.

122 characters if the input is already stored in n.

Thanks to user2992539, tolos and edc65 for improvements.


Python 3.5, 118 113 164 bytes:

from re import*
def R(U):Z='(?<!\d)-\d+|\d+|[()]';O=sub(Z,'',U);print(eval(sub(Z,'%s',U).translate(str.maketrans(O,O[::-1])).replace('^','**')%tuple(findall(Z,U))))

A named function. Can probably be golfed down more. This will take quite a while and apparently plenty of memory to compute the solution for the input:

((22^22)+2*2^2^2^2*2-2+222222+22222*-2222-2*222*2*2+2^-2+(2+2+2+2+2)+222/222+2+22*2*2)*2*2*2

I started processing this with my program about 30 minutes ago as of the time of this edit (9:52 PM on July 27, 2016) and it is still going. EDIT: Well, it eventually started to take up too much memory, so I had to stop it at around 1 hour after I started, at around 10:52 PM on July 7, 2016.

EDIT # 2: Well, even for the updated last test case it's pretty much the same thing, as it takes quite a while for my program to start finding the answer before it eventually quits out on me with error code 137.

Try It Online for the Rest of the Test Cases! (Ideone)


Processing 2, 448-25=423 bytes

int x,y,w,b,v,c,m;color g;PImage i;void setup(){i=loadImage("f.png");w=i.width;size(w,w);g=#00ff00;image(i,0,0);b=v=x=y=c=m=0;loadPixels();while(y*w+x<w*w){if(pixels[y*w+x]==g){f(y,x);if(v>=0)c+=v;else m++;}v=-1;x++;if(x==w){x=0;y++;}}println(c+" "+m);}void f(int k,int l){pixels[k*w+l]=color(0);if(pixels[(k+1)*w+l]==g)f(k+1,l);if(pixels[k*w+l+1]==g)f(k,l+1);if(pixels[k*w+l-1]==g)f(k,l-1);k-=w/2;l-=w/2;b=10-(int)(sqrt(k*k+l*l)/(w/20));if(b>v)v=b;}

Reads in an image file f loops through the pixels until it finds green then flood fills the circle determining the point that is closest to the center. Then adds that score to a total.  if the score is negative, it is added to a miss counter.

The program will output 2 numbers, the first is the score and the second is the number of misses.

  int x,y,w,b,v,c,m;
  color g;
  PImage i;
void setup()
{
  i=loadImage("f.png");
  w=i.width;
  size(w,w);
  g=#00ff00;
  image(i,0,0);
  b=v=x=y=c=m=0;
  loadPixels();
  while(y*w+x<w*w)
  {
    if(pixels[y*w+x]==g)
    {
      f(y,x);
      if(v>=0)c+=v;
      else m++;
    }
    v=-1;
    x++;
    if(x==w){x=0;y++;}
  }
  print(c+" "+m);
}

void f(int k,int l)
{
  pixels[k*w+l]=color(0);
 if(pixels[(k+1)*w+l]==g)f(k+1,l);
 if(pixels[k*w+l+1]==g)f(k,l+1);
 if(pixels[k*w+l-1]==g)f(k,l-1);
 k-=w/2;
 l-=w/2;
 b=10-(int)(sqrt(k*k+l*l)/(w/20));
 if(b>v)v=b;
}

you can get processing here


Python 2, 30 bytes

lambda a,b:a in(b,5-b,b-5,b+5)

Try it online!

One byte saved by Arnauld

Three bytes saved by alephalpha


Ruby 1.9 (235) (225) (222) (214)

I don't know if this is shorter than a program based on Dijkstra, but I figured I would try a different approach. This uses regex in a loop to mark each space with the minimal number of walls required to reach it.

w=".{#{/\s/=~s=$<.read}}?"
j="([.x])"
s[0]=v=s[0]<?x??0:?1
(d=v[-1];n=v.succ![-1]
0while(s.sub!(/#{j}(#{w+d})/m){($1<?x?d: n)+$2}||s.sub!(/(#{d+w})#{j}/m){$1+($2<?x?d: n)}))while/#{j}/=~q=s[-2]
p v.to_i-(q==n ?0:1)

Input is specified as a file on the command line, i.e.

> ruby1.9.1 golf.rb maze.txt

Ungolfed:

# read in the file
maze = $<.read

# find the first newline (the width of the maze)
width = /\s/ =~ maze

# construct part of the regex (the part between the current cell and the target cell)
spaces = ".{#{width}}?"

# construct another part of the regex (the target cell)
target = "([.x])"

# set the value of the first cell, and store that in the current wall count
maze[0] = walls = (maze[0] == "x" ? "1" : "0")

# loop until the goal cell is not "." or "x"
while /#{target}/ =~ (goal = s[-2])

  # store the current wall count digit and the next wall count digit, while incrementing the wall count
  current = walls[-1]; next = walls.succ![-1]

  # loop to set all the reachable cells for the current wall count
  begin

    # first regex handles all cells above or to the left of cells with the current wall count
    result = s.sub!(/#{target}(#{spaces + current})/m) {
      ($1 == 'x' ? next : current) + $2
    }

    # second regex handles all cells below or to the right of cells with the current wall count
    result = result || s.sub!(/(#{current + spaces})#{target}/m) {
      $1 + ($2 == 'x' ? next : current)
    }
  end while result != nil
end

# we reached the goal, so output the wall count if the goal was a wall, or subtract 1 if it wasn't
puts walls.to_i - (goal == next ? 0 : 1)


Haskell, 57 bytes

c=[1]:[x++[a+b]|x<-c,a<-x,b<-x]
f n=[x|x<-c,last x==n]!!0

A brute force solution.
Try it online!

Explanation

The infinite list c contains all addition chains, ordered by length.
It is defined inductively in terms of itself, by taking a list x from c and two elements from x, and appending their sum to x.
The function f finds the first list in c that ends with the desired number.

c=            -- c is the list of lists
 [1]:         -- containing [1] and
 [x           -- each list x
  ++[a+b]     -- extended with a+b
 |x<-c,       -- where x is drawn from c,
  a<-x,       -- a is drawn from x and
  b<-x]       -- b is drawn from x.
f n=          -- f on input n is:
 [x           -- take list of those lists x
 |x<-c,       -- where x is drawn from c and
  last x==n]  -- x ends with n,
 !!0          -- return its first element.


Pyth, 51 46 45 43 41 40 bytes
I remove the curly braces and split at \, just like Reto Koradi's CJam answer does. The codes bar, dot and hat are recognized simply by the last decimal digit of the character code of the first character, modulo 3. I just add barf (RIP) """" to the first part and remove it in the end to save the code for handling the first part specially.
jtMsMCm,+@".^_"eChd*\ -ld4>d3c-+*4Nz`H\\

Try it online. Test suite.


Scan dactylic hexameter in a unique puzzle

sed, 402 392 374 359 363 334 333 bytes

  “Sing, goddess, the anger of Peleus’ son Achilleus
  and its devastation, which put pains thousandfold upon the Achians,
  hurled in their multitudes to the house of Hades strong souls
  of heroes, but gave their bodies to be the delicate feasting
  of dogs, of all birds, and the will of Zeus was accomplished
  since that time when first there stood in division of conflict
  Atreus’ son the lord of men and brilliant Achilleus.”

— Homer (The Iliad); confused why this quote is here? check the rules.

sed -E 's/[AEIOU]M? H?([AEIOU])/\1/g;s/X/cc/g;s/(^|[ AEIOU])I([AEIOU])/\1c\2/g;s/QUE( |$)/cv/g;s/A[EU]|E[IU]|OE|UI/-/g;s/[CPT]H|[BCDGPT][LR]|QU|[^-vAEIOU ]/c/g;s/ //g;s/ucc+/-/g;s/c//g;s/^[-u]([-u]|[vu]{2})[-u]([-u]|[vu]{2})[-u]([-u]|[vu]{2})[-u]([-u]|[vu]{2})[-u]([-u]|[vu]{2})[-u].$/-\1|-\2|-\3|-\4|-\5|-x/;s/[uv]/-/g;s/---/-vv/g'

Not exactly golfed, but this implements all the given rules in the form of regular expressions, which sed just runs one-by-one to reach the solution. This handles each line independently, so can process an entire multi-line input.

Usage:

printf 'ARMA VIRUMQUE CANO TROIAE QUI PRIMUS AB ORIS
ITALIAM FATO PROFUGUS LAVINIAQUE VENIT
LITORA MULTUM ILLE ET TERRIS IACTATUS ET ALTO
VI SUPERUM SAEVAE MEMOREM IUNONIS OB IRAM
MULTA QUOQUE ET BELLO PASSUS DUM CONDERET URBEM
INFERRETQUE DEOS LATIO GENUS UNDE LATINUM
ALBANIQUE PATRES ATQUE ALTAE MOENIA ROMAE' | sed -E '<...>';

Breakdown:

sed -E "
# Apply Elision
 s/[AEIOU]M? H?([AEIOU])/\1/g;

# Convert into vowels (u, v or -) and consonants (c) according to the rules given
 s/X/cc/g;
 s/(^|[ AEIOU])I([AEIOU])/\1c\2/g;
 s/QUE( |\$)/cv/g;
 s/A[EU]|E[IU]|OE|UI/-/g;
 s/[CPT]H|[BCDGPT][LR]|QU|[^-vAEIOU ]/c/g;
 s/[A-Z]/u/g; # all remaining vowels are unknown

# Remove all spaces
 s/ //g;

# A vowel followed by 2 consonants before the next vowel is long
# (and we don't care if the last vowel is long or short)
 s/ucc+/-/g;

# Remove all consonants
 s/c//g;

# Look for a matching dactylic hexameter and insert pipe separators
 s/^\
[-u]([-u]|[vu]{2})\
[-u]([-u]|[vu]{2})\
[-u]([-u]|[vu]{2})\
[-u]([-u]|[vu]{2})\
[-u]([-u]|[vu]{2})\
[-u].\$/-\1|-\2|-\3|-\4|-\5|-x/;

# Substitute identified feet with the necessary long/short vowels
 s/[uv]/-/g;
 s/---/-vv/g
"

Results for test cases:

-vv|-vv|--|--|-vv|-x
-vv|-vv|--|-vv|-vv|-x
-vv|--|--|--|-vv|-x
-vv|--|-vv|-vv|--|-x
-vv|--|--|--|-vv|-x
--|-vv|-vv|-vv|-vv|-x
--|-vv|--|--|-vv|-x


Wolfram Language (Mathematica), score 849/101 = 8.406

g@n_:=f@n<>"망히"
f@n_:=f@n=Switch[n,-1,"밯",1,"반반나",9,"밞",8,"밣",7,"밝",6,"밦",5,"발",4,"밗",3,"받",2,"박",
_,mn@{m@n,a@n,s@n}]
m@n_:=m@n=f@#<>If[# #==n,"빠",f[n/#]]<>"따"&/@Select[Divisors@n,1<# #<=n&]//mn
a@n_:=a@n=f@#<>f[n-#]<>"다"&/@Range[⌈n/2⌉-1]//mn
s@n_:=s@n=m[n+#]<>f@#<>"타"&/@Range[n-1]//mn
mn=First@*MinimalBy[StringLength[""<>#]&]

Try it online!

Builds numbers with 다 (+) 따 (*) 타 (-), and 빠 (duplicate), in addition to literals for 2..9. Doesn't actually make use of 밯=-1.

Paste the tio output (Unicode character codes) into Mathematica to see the result:

100 -> 밗발빠따따망히
101 -> 박밞박밞다따다망히
102 -> 밦밣밞다따망히
103 -> 받밗발빠따따다망히
104 -> 밣밗밞다따망히
105 -> 받발밝따따망히
106 -> 박밗밝빠따다따망히
107 -> 박받발밝따따다망히
108 -> 박밦밞따따망히
109 -> 밗받발밝따따다망히
110 -> 박발박밞다따따망히
111 -> 받박발밝따다따망히
112 -> 박밝밣따따망히
113 -> 발박밦밞따따다망히
114 -> 박받밦밞따다따망히
115 -> 발박받밝따다따망히
116 -> 박박밝밣따다따망히
117 -> 밞밗밞다따망히
118 -> 박받밝밣따다따망히
119 -> 밝밣밞다따망히
120 -> 받발밣따따망히
121 -> 박밞다빠따망히
122 -> 박발밝밣따다따망히
123 -> 받발밗밞따다따망히
124 -> 박밦밝밣따다따망히
125 -> 발발빠따따망히
126 -> 박밝밞따따망히
127 -> 박발발빠따따다망히
128 -> 박밣빠따따망히
129 -> 받받발밣따다따망히
130 -> 박발밗밞다따따망히
131 -> 받박밣빠따따다망히
132 -> 박밦박밞다따따망히
133 -> 밝박밣밞다다따망히
134 -> 박받밣빠따다따망히
135 -> 받발밞따따망히
136 -> 밣밣밞다따망히
137 -> 박받발밞따따다망히
138 -> 박발밣빠따다따망히
139 -> 받밣밣밞다따다망히
140 -> 밗발밝따따망히
141 -> 받박발밞따다따망히
142 -> 박밝밣빠따다따망히
143 -> 박밞다밗밞다따망히
144 -> 박밣밞따따망히
145 -> 발박받밞따다따망히
146 -> 박밞밣빠따다따망히
147 -> 받밝빠따따망히
148 -> 박박밣밞따다따망히
149 -> 박받밝빠따따다망히
150 -> 발발밦따따망히
151 -> 밗받밝빠따따다망히
152 -> 박밗밣밞따다따망히
153 -> 밞밣밞다따망히
154 -> 박밝박밞다따따망히
155 -> 발받밗밝따다따망히
156 -> 박밦밗밞다따따망히
157 -> 밗밞밣밞다따다망히
158 -> 박밝밣밞따다따망히
159 -> 받밗밝빠따다따망히
160 -> 밗발밣따따망히
161 -> 밝박받밝따다따망히
162 -> 박밞빠따따망히
163 -> 받밗발밣따따다망히
164 -> 밗발밗밞따다따망히
165 -> 받발박밞다따따망히
166 -> 박박밞빠따다따망히
167 -> 발박밞빠따따다망히
168 -> 받밝밣따따망히
169 -> 밗밞다빠따망히
170 -> 박발밣밞다따따망히
171 -> 받받밦밞따다따망히
172 -> 박발밞빠따다따망히
173 -> 밗밗밞다빠따다망히
174 -> 박밦밞빠따다따망히
175 -> 발발밝따따망히
176 -> 박밣박밞다따따망히
177 -> 받받밝밣따다따망히
178 -> 박밣밞빠따다따망히
179 -> 밗발발밝따따다망히
180 -> 밗발밞따따망히
181 -> 밦발발밝따따다망히
182 -> 박밝밗밞다따따망히
183 -> 받발밝밣따다따망히
184 -> 밗밗밦밝따다따망히
185 -> 발박발밝따다따망히
186 -> 받밦밝밣따다따망히
187 -> 박밞다밣밞다따망히
188 -> 밗박발밞따다따망히
189 -> 받밝밞따따망히
190 -> 발박밗밞따다따망히
191 -> 박받밝밞따따다망히
192 -> 받밣빠따따망히
193 -> 밗받밝밞따따다망히
194 -> 박받밣빠따따다망히
195 -> 받발밗밞다따따망히
196 -> 밗밝빠따따망히
197 -> 발받밣빠따따다망히
198 -> 박밞박밞다따따망히
199 -> 받밗밝빠따따다망히
200 -> 발발밣따따망히

The lowest number that improves with 타 is 211, with 받밣밞따따발타 (3*8*9-5) beating out 발밠밝따따반반나다 (5*6*7+2/2).

The next lowest, 239 (받밞빠따따밗타=3*9*9-4), didn't require 반반나 in its 다/따-only construction (받밣밞따밝다따박다=3*(8*9+7)+2).

An earlier version of this program generated 다/따-only constructions.

With 밯=-1 (score unchanged)

g@n_:=f@n<>"망히"
f@n_:=f@n=Switch[n,1,"밯",9,"밞",8,"밣",7,"밝",6,"밦",5,"발",4,"밗",3,"받",2,"박",
_,mn@{m@n,a@n,s@n}]
m@n_:=m@n=f@#<>If[# #==n,"빠",f[n/#]]<>"따"&/@Select[Divisors@n,1<# #<=n&]//mn
a@n_:=a@n=f@#<>f[n-#]<>If[#==1,"타","다"]&/@Range[⌈n/2⌉-1]//mn
s@n_:=s@n=m[n+#]<>f@#<>If[#==1,"다","타"]&/@Range[n-1]//mn
mn=First@*MinimalBy[StringLength[""<>#]&]

Try it online!

If the program is given no input, 밯 (read a character from input) returns -1, which allows for a one-character 1 literal.

The lowest number that benefits from this is 269, which improves to 발밦밞따따밯다 (5*6*9+(-1)) from 박받밣밞빠따다따다 (2+3*(8+9*9)).


Jelly, 15 bytes

LŒ!ðŒcIṠ;ị"Pð€S

Try it online!

How it works

LŒ!ðŒcIṠ;ị"Pð€S   input
L                 length
 Œ!               all_permutations
   ð        ð€    for each permutation:
    Œc                take all unordered pairs
      I               calculate the difference between
                      the two integers of each pair
       Ṡ              signum of each difference
                      (positive -> 1, negative -> -1)
        ;             append:
         ị"             the list of elements generated by taking
                        each row according to the index specified
                        by each entry of the permutation
           P          product of everything
              S   sum

Why it works -- mathy version

The operator det takes a matrix and returns a scalar. An n-by-n matrix can be thought of as a collection of n vectors of length n, so det is really a function that takes n vectors from ℤn and returns a scalar.

Therefore, I write det(v1, v2, v3, ..., vn) for det [v1 v2 v3 ... vn].

Notice that det is linear in each argument, i.e. det(v1 + λw1, v2, v3, ..., vn) = det(v1, v2, v3, ..., vn) + λ det(w1, v2, v3, ..., vn). Therefore, it is a linear map from (ℤn)⊗n to ℤ.

It suffices to determine the image of the basis under the linear map. The basis of (ℤn)⊗n consists of n-fold tensor products of the basis elements of ℤn, i.e. e.g. e5 ⊗ e3 ⊗ e1 ⊗ e5 ⊗ e1. Tensor products that include identical tensors must be sent to zero, since the determinant of a matrix in which two columns are identical is zero. It remains to check what the tensor products of distinct basis elements are sent to. The indices of the vectors in the tensor product form a bijection, i.e. a permutation, in which even permutations are sent to 1 and odd permutations are sent to -1.

For example, to find the determinant of [[1, 2], [3, 4]]: note that the columns are [1, 3] and [2, 4]. We decompose [1, 3] to give (1 e1 + 3 e2) and (2 e1 + 4 e2). The corresponding element in the tensor product is (1 e1 ⊗ 2 e1 + 1 e1 ⊗ 4 e2 + 3 e2 ⊗ 2 e1 + 3 e2 ⊗ 4 e2), which we simplify to (2 e1 ⊗ e1 + 4 e1 ⊗ e2 + 6 e2 ⊗ e1 + 12 e2 ⊗ e2). Therefore:

det [[1, 2], [3, 4]]
= det(1 e1 + 3 e2, 2 e1 + 4 e2)
= det(2 e1 ⊗ e1 + 4 e1 ⊗ e2 + 6 e2 ⊗ e1 + 12 e2 ⊗ e2)
= det(2 e1 ⊗ e1) + det(4 e1 ⊗ e2) + det(6 e2 ⊗ e1) + det(12 e2 ⊗ e2)
= 2 det(e1 ⊗ e1) + 4 det(e1 ⊗ e2) + 6 det(e2 ⊗ e1) + 12 det( e2 ⊗ e2)
= 2 (0) + 4 (1) + 6 (-1) + 12 (0)
= 4 - 6
= -2

Now it remains to prove that the formula for finding the parity of the permutation is valid. What my code does is essentially find the number of inversions, i.e. the places where an element on the left is bigger than an element on the right (not necessarily consecutively).

For example, in the permutation 3614572, there are 9 inversions (31, 32, 61, 64, 65, 62, 42, 52, 72), so the permutation is odd.

The justification is that each transposition (swapping two elements) either adds one inversion or takes away one inversion, swapping the parity of the number of inversions, and the parity of the permutation is the parity of the number of transpositions needed to achieve the permutation.

Therefore, in conclusion, our formula is given by:

Why it works -- non-mathy version

where σ is a permutation of n the group of all permutations on n letters, and sgn is the sign of the permutation, AKA (-1) raised to the parity of the permutation, and aij is the (ij)th entry in the matrix (i down, j across).


J, 32 31 26 bytes
j.&<.+((1<:+)*0j1^<)&(1|])

Try it online!
-5 thanks to Razetime for pointing out I could take real and imag parts as left and right args.
Obligatory J answer.
For reference, per the link in the OP, Eugene McDonnell's  algorithm is:

The algorithm for the determination of g , the floor of a complex number z , may be explained informally as follows:

Let b be the point at the lower left corner of the unit square containing z . Let x and y be the fractional parts of the real and imaginary parts of z .
Then:

Let g = b if 1 > (x + y) ,
Let g = (b + 1) if (1 ≤ x + y) and x ≥ y ,
Let g = (b + 0i1) if (1 ≤ x + y) and x < y .

We take the real and imaginary parts as left and right args.
We note that the answer is:
b + (0 or 1 or i)

depending on the case.

j.&<.+ Floors both parts and converts back to complex j.&<./, then adds everything
to the right +.  This gives us the b + part.
(...)&(1|]) Get fractional parts of real/imag pieces, and feed those as
left and right args to everything in parens.  This gives us x and y.
(1<:+) Is x + y greater than or equal to 1?  Returns 0 or 1. Multiply that
by...
0j1^< \$i\$ raised to "is x < y?" -- gives us \$i\$ if true, 1 otherwise.


Jelly,  187  166 bytes

ḣ9;⁾| ṁ5¤oµ€“µ½¿‘¦
“ _/ |/|”;€⁶;”_ṁ"“¡ẇḞ6’D¤ṃ@“Ė⁸ġṾṗ¢œƝṇRK⁹ṄẸŒÐ¤ɓḂı)ḥṆqƓị¹÷ḄƝṁPʠVW1JĊTc;[¤ÆWŒṠṬ#ʋÆ6ẉ⁷ZḷƊḤƑẹẠGḊ|qi×Ƭ®ÐėƁ1(⁸ṪU¹Bgoƭ<Gḋ×c:ȦṚƇĊ¬e*⁽%ḷİ°U’Fs27Ç¹⁸?x€15¦€19Y

A full program.

Try it online!

How?

103 bytes are a 101 digit base 250 number, which is a base-8 compression of a possible cube, with trailing spaces added to equalise the row-lengths, without new lines, and without 18 characters from the middle of each row, like this, but without newlines:

         _________________
        / _____________  /|
       / / ___________/ / |
      / / /| |       / /  |
     / / / | |      / /   |
    / / /| | |     / / /| |
   / / / | | |    / / / | |
  / / /  | | |   / / /| | |
 / /_/___|_|_|__/ / / | | |
/________________/ /  | | |
| ______________ | |  | | |
| | |    | | |_| | |__| | |
| | |    | |___| | |____| |
| | |   / / ___| | |_  / /
| | |  / / /   | | |/ / /
| | | / / /    | | | / /
| | |/ / /     | | |/ /
| | | / /      | |   /
| | |/_/_______| |  /
| |____________| | /
|________________|/

The 8 base-8 digits represent the strings of characters:

1      2    3    4    5    6        7        0
"   ", "_", "/", " ", "|", "/ / /", "| | |", "_____"

So the compression is then like the below where 1s, 6s, 7s and 0s are to be replaced by the strings shown above:

111000__111/ 00___  /|11 / / 00_/ / |116| |11 / /  |1  6 | |11/ /1|1 671  6| |16 71 6 | |  6  7167 6___|_|_|__6 7/000_/ /  7| 00____ | |  771 7_7__771 | |___7____| |71/ / ___7_  / / 7  6176  7 61 7 / /1761  7/ /1 7 / /11| |1/1  7/_/0__| |  /11| |00__| | /11 |000_|/11

The program reverses the process and changes the characters that need changing if the cube should be an impossible one:

“ _/ |/|”;€⁶;”_ṁ"“¡ẇḞ6’D¤ṃ@“ ... ’Fs27Ç¹⁸?x€15¦€19Y  Main link: V
                                                     ...splitting this up...
                                                     ...Main link part 1:
“ _/ |/|”;€⁶;”_ṁ"“¡ẇḞ6’D¤ - make the list of strings of characters
“ _/ |/|”                 - list of characters = " _/ |/|"
           ⁶              - literal space character
         ;€               - concatenate €ach -> ["  ","_ ","/ ","  ","| ","/ ","| "]
             ”_           - literal = '_'
            ;             - concatenate -> ["  ","_ ","/ ","  ","| ","/ ","| ", '_']
                        ¤ - nilad followed by link(s) as a nilad:
                 “¡ẇḞ6’   -   base 250 literal = 31111555
                       D  -   convert to decimal list -> [3,1,1,1,1,5,5,5]
                "         - zip with:
               ṁ          -   mould like
                          -   -> ["   ","_","/"," ","|","/ / /","| | |","_____"]

                                                     ...Main link, part 2:
...ṃ@“ ... ’Fs27 - make the rows of a possible cube without the middle repetitions:
...              - part 1, above
     “ ... ’     - the 101 digit base 250 number
   ṃ@            - base decompression with swapped @rguments
            F    - flatten (because the digit values we are using are actually lists)
             s27 - split into chunks of length 27 (into the rows)

                                                     ...Main link part 3:
...Ç¹⁸?x€15¦€19Y - make "impossible" if need be, add the row middles and output
...              - part 2, above
       ?         -  if:
      ⁸          -    chain's left argument = V
   Ç             - ...then: call last link (1) as a monad
                 -          (make it an impossible cube - see link 1, below)
    ¹            - ...else: identity (do nothing)
            €    - for €ach
         ¦       - apply sparsely:
       15        - ...to index: 15
     x€    19    - ...this: repeat €ach nineteen times
               Y - join with newlines
                 - implicit print

ḣ9;⁾| ṁ5¤oµ€“µ½¿‘¦  Link 1, replace characters to make impossible: rows
                 ¦  apply sparsely:
            “µ½¿‘   ...to indexes: code-page indexes = [9,10,11]
                    ...this:
          µ€          for €ach:
ḣ9                      head to index 9
        ¤               nilad followed by link(s) as a nilad:
   ⁾|                     list of characters = ['|',' ']
      ṁ5                  mould like 5 = ['|',' ','|',' ','|']
  ;                     concatenate
         o              logical or (vectorises) with the row
                          (which has the effect of appending the rest of the row)


Python 2, 150 196 206 bytes

def f(p):
 c=48;s=[l*'.'for l in p];m=2**len(bin(l))
 while m:
  if sum(m*'.'in l for l in s)>1:
   for i,l in enumerate(s):s[i]=l.replace('.'*m,chr(c)*m,`s`.count(chr(c)*m)<2)
   c+=1
  else:m/=2
 return s

Try it online!


R, 70 bytes

function(s)sub("e","*10^",format(eval(parse(t=s)),sc=!grepl("\\^",s)))

Try it online!

An anonymous function. Takes input as a string and outputs as a string.

This function evaluates the string eval(parse(t=s)), then formats it, with the flag scientific set to whether the string contains a ^ or not. Then it replaces e with *10^ to match the right output spec.


V, 37, 35 bytes

ç^</dj
H3xf]x3Ji[`A`]Jd2/:
xr(A)

Try it online!


Haskell, 118 112 107 bytes

Here I use the numbers \$n= 0,1,2,\ldots,8\$ to represent the field elements. Internally these are converted to a list \$[a,b]\$ that represents a polynomial \$aX+b\$, (using \$a = \lfloor n/3 \rfloor\$ and \$b = n \mod 3 \$, or \$n=3a+b\$), and we then proceed using the usual arithmetic using these polynomials in \$(\mathbb  Z / 3\mathbb Z)[X]/(X^2+1)\$. In this case we have

$$(aX+b) + (cX+d) = (a+c)X + (b+d)$$

and similarly

$$\begin{align*}
(aX+b) \cdot (cX+d) &= acX^2+(ad+bc)X + bd
\\
& \equiv ac(-1) +(ad+bc)X + bd \mod X^2+1\\
& \equiv (ad+bc)X+(bd-ac)
\end{align*}$$

Thanks for -6 bytes @WheatWizard!

i x=[div x 3,x]                --conert integer to polynomial/list representation
j[a,b]=mod(a*3+mod b 3)9       --inverse of i
s=(.i).(j.).zipWith(+).i       --"sum"
m[a,b][c,d]=j[a*d+b*c,b*d-a*c] --core function of "product"
p=(.i).m.i                     --"product"

Try it online!


05AB1E, 23 bytes

Online compiler can't show all terms for high N but it works fine offline.

Lvy2°*>F„0.0N×yJ,¼¾¹Qiq

Explanation

                          # implicit input X
Lv                        # for each y in range [1 .. X]
  y2°*>F                  # for each N in range [0 .. y*100+1)
        „0.               # push the string "0."
           0N×            # push 0 repeated N times
              y           # push current y
               J,         # join and print
                 ¼¾¹Qiq   # quit the program after X terms printed

Try it online!


Perl, 32 chars

s/((.)(?1)\2|.?)$/$&.reverse$`/e

Needs Perl 5.10 or later for regex features, but no special command-line switch.

Sample use:

$ perl -pe 's/((.)(?1)\2|.?)$/$&.reverse$`/e' << EOT
> 12
> 232
> 2323
> 1012121
> EOT
121
232
23232
101212101

Uses Perl 5.10's recursive regex extensions to match the longest trailing palindrome as such:

m/
    (      # paren 1 - a palindrome is either:
      (.)  # paren 2 - a character
      (?1) # a palindrome as defined in paren 1
      \2   # the same character as in paren 2
    |        # or:
      .?   # a 0- or 1-character string
    )
    $      # at end of string
/x

It then replaces it with itself ($&) and appends whatever the string started with ($`), reversed.


Find every digit from the largest column

Haskell, 63 bytes

import Data.Lists
argmax sum.transpose.map(map(read.pure).show)

Usage example: argmax sum.transpose.map(map(read.pure).show) $ [12,304,506] -> [4,6].

How it works:

                     map                       -- for each number
                         map(read.pure).show   -- turn into list of digits
           transpose                           -- transpose the list of list
argmax sum                                     -- find the element with the
                                               -- largest sum


OEIS A000041, cracked by ETHproductions
Let's try it the other way around: golflang generates non-golflang.

a(n) = number of partitions of n (the partition numbers).

a(n) (0-indexed) is returned by a JavaScript function (ES6)
The program that outputs the JS function is written in Jelly
The length of the Jelly program is 35 bytes

Intended solution

    Jelly: “¦ṚoIwƭ- ḊFæSḂ¥¶Ẉ|ḊJƓƝʋnrB⁾’b28+40Ọ

    which outputs

    JS: C=(A,B=A)=>A<0?0:A?B?C(A,B-1)+C(A-B,B):0:1


Python 3, 190 bytes

def f(F):s="".join(hex(k)[2]for k in F);F[1:]in[[4,4],[3]*3]or{s,s[::-1]}&{*"555 333 366 388 3aa 466 566 468 46a 3434 3444 3454 3535 33333 33334 33335".split()}and max(F)<16or f(F[1:]+F[:1])

Try it online!
Takes input as a list of integers representing the vertex figure. The function errors (RecursionError) if the vertex figure is not a uniform polyhedron, otherwise there is no error.
I tried several schemes of organizing the finite classes into a smart way that takes advantage of patterns, but hardcoding all possibilities reigned superior since it is a relatively small set.
Explanation
def f(F):
    # F is a rotation of the input vertex figure; initially is the input vertex figure
    # Convert to string for easier comparison later in the code
    s="".join(hex(k)[2]for k in F)
    # Test true if the permutation is N.4.4.4 or N.3.3.3
    (F[1:]in[[4,4],[3]*3]or
    # Test truthy if permutation (or its reverse) is in
    #   3.3.3, 3.6.6, 3.8.8, 3.10.10, 4.6.6, 5.6.6, 4.6.8, 4.6.10,
    #   3.3.3.N, 3.4.3.4, 3.4.4.4, 3.4.5.4, 3.5.3.5
    #   3.3.3.3.3, 3.3.3.3.4, 3.3.3.3.5
    {s,s[::-1]}&{*"555 333 366 388 3aa 466 566 468 46a 3434 3444 3454 3535 33333 33334 33335".split()}
    # Numbers greater than 15 would convert into the most-significant hexit when converted to a string,
    # causing 0x43 to match the same as 0x4,
    # so we need to check that none of this happened if we want a bugfree string search
    and max(F)<16
    # If we tested truthy, then terminate
    # Otherwise, recurse with the vertex figure cyclically rotated left one
    or f(F[1:]+F[:1]))


C#, 259421/734078 ~= 0.3534

Methods

I finally found a more-or-less readable explanation of the projective field method (Singer's method) in Constructions of Generalised Sidon Sets, although I still think it can be improved slightly. It turns out to be more similar to the affine field method (Bose's method) than the other papers I read had communicated.

This assumes knowledge of finite fields. Consider \$q = p^a\$ is a prime power, and let \$F(q)\$ be our base field.

The affine field method works over \$F(q^2)\$. Take a generator \$g_2\$ of \$F(q^2)\$ and a non-zero element \$k\$ of \$F(q)\$ and consider the set $$\{a : g_2{}^a - k g_2 \in F_q\}$$ Those values form a modular Golomb ruler mod \$q^2 - 1\$. Further rulers can be obtained by multiplying modulo \$q^2 - 1\$ by any number which is coprime with the modulus.

The projective field method works over \$F(q^3)\$. Take a generator \$g_3\$ of \$F(q^3)\$ and a non-zero element \$k\$ of \$F(q)\$ and consider the set $$\{0\} \cup \{a : g_3{}^a - k g_3 \in F_q\}$$ Those values form a modular Golomb ruler mod \$q^2 + q + 1\$. Further rulers can be obtained by modular multiplication in the same way as for the affine field method.

Note that these methods between them give the best known values for every length greater than 16. Tomas Rokicki and Gil Dogon are offering a $250 reward for anyone who beats them for lengths 36 to 40000. Therefore anyone who beats this answer is in for a monetary prize.

Code

The C# isn't very idiomatic, but I need it to compile with an old version of Mono. Also, despite the argument checking, this is not production quality code. I'm not happy with the types, but I don't think there's a really good solution to that in C#. Maybe in F# or C++ with insane templating.

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

namespace Sandbox {
    class Program {
        static void Main(string[] args) {
            var winners = ComputeRulerRange(50, 100);
            int total = 0;
            for (int i = 50; i <= 100; i++) {
                Console.WriteLine("{0}:\t{1}", i, winners[i][i - 1]);
                total += winners[i][i - 1];
            }
            Console.WriteLine("\t{0}", total);
        }

        static IDictionary<int, int[]> ComputeRulerRange(int min, int max) {
            var best = new Dictionary<int, int[]>();

            var naive = Naive(max);
            for (int i = min; i <= max; i++) best[i] = naive.Take(i).ToArray();

            var finiteFields = FiniteFields(max * 11 / 10).OrderBy(x => x.Size).ToArray();

            // The projective plane method generates rulers of length p^a + 1 for prime powers p^a.
            // We can then look at subrulers for a reasonable range, say down to two prime powers below.
            for (int ppi = 0; ppi < finiteFields.Length; ppi++) {
                // Range under consideration
                var field = finiteFields[ppi];
                int q = field.Size;
                int subFrom = Math.Max(min, ppi >= 2 ? finiteFields[ppi - 2].Size : 1);
                int subTo = Math.Min(max, q + 1);
                if (subTo < subFrom) continue;

                int m = q * q + q + 1;
                foreach (var ruler in ProjectiveRulers(field)) {
                    for (int sub = subFrom; sub <= subTo; sub++) {
                        var subruler = BestSubruler(ruler, sub, m);
                        if (subruler[sub - 1] < best[sub][sub - 1]) best[sub] = subruler;
                    }
                }
            }

            // Similarly for the affine plane method, which generates rulers of length p^a for prime powers p^a
            for (int ppi = 0; ppi < finiteFields.Length; ppi++) {
                // Range under consideration
                var field = finiteFields[ppi];
                int q = field.Size;
                int subFrom = Math.Max(min, ppi >= 2 ? finiteFields[ppi - 2].Size : 1);
                int subTo = Math.Min(max, q);
                if (subTo < subFrom) continue;

                int m = q * q - 1;
                foreach (var ruler in AffineRulers(field)) {
                    for (int sub = subFrom; sub <= subTo; sub++) {
                        var subruler = BestSubruler(ruler, sub, m);
                        if (subruler[sub - 1] < best[sub][sub - 1]) best[sub] = subruler;
                    }
                }
            }

            return best;
        }

        static int[] BestSubruler(int[] ruler, int sub, int m) {
            int[] expand = new int[ruler.Length + sub - 1];
            for (int i = 0; i < ruler.Length; i++) expand[i] = ruler[i];
            for (int i = 0; i < sub - 1; i++) expand[ruler.Length + i] = ruler[i] + m;

            int best = m, bestIdx = -1;
            for (int i = 0; i < ruler.Length; i++) {
                if (expand[i + sub - 1] - expand[i] < best) {
                    best = expand[i + sub - 1] - expand[i];
                    bestIdx = i;
                }
            }

            return expand.Skip(bestIdx).Take(sub).Select(x => x - ruler[bestIdx]).ToArray();
        }

        static IEnumerable<int[]> ProjectiveRulers(FiniteField field) {
            var q = field.Size;
            var fq3 = PowerField.Create(field, 3);
            var m = q * q + q + 1;
            var g = fq3.Generators.First();

            // Define the set T<k> = {0} \union {a \in [q^3-1] : g^a - kg \in F(q)} for 0 != k \in F(q)
            // This could alternatively be T<k> = {0} \union {log_g(b - kg) : b in F(q)} for 0 != k \in F(q)
            // Then T<k> % (q^2 + q + 1) gives a Golomb ruler.
            // For a given generator we seem to get the same ruler for every k.
            var t_k = new HashSet<int>();
            t_k.Add(0);
            var ga = fq3.One;
            for (int a = 1; a < fq3.Size; a++) {
                ga = ga * g;
                if (fq3.Convert(ga + g) < q) t_k.Add(a % m);
            }

            // TODO: optimise by detecting duplicates
            for (int s = 1; s < m; s++) {
                if (Gcd(s, m) == 1) yield return t_k.Select(x => x * s % m).OrderBy(x => x).ToArray();
            }
        }

        static IEnumerable<int[]> AffineRulers(FiniteField field) {
            var q = field.Size;
            var fq2 = PowerField.Create(field, 2);
            var m = q * q - 1;
            var g = fq2.Generators.First();

            // Define the set T<k> = {0} \union {a \in [q^2-1] : g^a - kg \in F(q)} for 0 != k \in F(q)
            // Then T<k> % (q^2 - 1) gives a Golomb ruler.
            var t_k = new HashSet<int>();
            var ga = fq2.One;
            for (int a = 1; a < fq2.Size; a++) {
                ga = ga * g;
                if (fq2.Convert(ga + g) < q) t_k.Add(a % m);
            }

            // TODO: optimise by detecting duplicates
            for (int s = 1; s < m; s++) {
                if (Gcd(s, m) == 1) yield return t_k.Select(x => x * s % m).OrderBy(x => x).ToArray();
            }
        }

        static int Gcd(int a, int b) {
            while (a != 0) {
                var t = b % a;
                b = a;
                a = t;
            }

            return b;
        }

        static int[] Naive(int size) {
            if (size == 0) return new int[0];
            if (size == 1) return new int[] { 0 };

            int[] ruler = new int[size];
            var diffs = new HashSet<int>();
            int i = 1, c = 1;
            while (true) {
                bool valid = true;
                for (int j = 0; j < i; j++) {
                    if (diffs.Contains(c - ruler[j])) { valid = false; break; }
                }

                if (valid) {
                    for (int j = 0; j < i; j++) diffs.Add(c - ruler[j]);
                    ruler[i++] = c;
                    if (i == size) return ruler;
                }

                c++;
            }
        }

        static IEnumerable<FiniteField> FiniteFields(int max) {
            bool[] isComposite = new bool[max + 1];
            for (int p = 2; p < isComposite.Length; p++) {
                if (!isComposite[p]) {
                     FiniteField baseField = new PrimeField(p); yield return baseField;
                    for (int pp = p * p, pow = 2; pp < max; pp *= p, pow++) yield return PowerField.Create(baseField, pow);
                    for (int pq = p * p; pq <= max; pq += p) isComposite[pq] = true;
                }
            }
        }
    }

    public abstract class FiniteField {
        private Lazy<FiniteFieldElement> _Zero;
        private Lazy<FiniteFieldElement> _One;

        public FiniteFieldElement Zero { get { return _Zero.Value; } }
        public FiniteFieldElement One { get { return _One.Value; } }
        public IEnumerable<FiniteFieldElement> Generators {
            get {
                for (int _g = 1; _g < Size; _g++) {
                    int pow = 0;
                    FiniteFieldElement g = Convert(_g), gpow = One;
                    while (true) {
                        pow++;
                        gpow = gpow * g;
                        if (gpow == One) break;
                        if (pow > Size) {
                            throw new Exception("Is this really a field? " + this);
                        }
                    }
                    if (pow == Size - 1) yield return g;
                }
            }
        }

        public abstract int Size { get; }
        internal abstract FiniteFieldElement Convert(int i);
        internal abstract int Convert(FiniteFieldElement f);

        internal abstract bool Eq(FiniteFieldElement a, FiniteFieldElement b);
        internal abstract FiniteFieldElement Negate(FiniteFieldElement a);
        internal abstract FiniteFieldElement Add(FiniteFieldElement a, FiniteFieldElement b);
        internal abstract FiniteFieldElement Mul(FiniteFieldElement a, FiniteFieldElement b);

        protected FiniteField() {
            _Zero = new Lazy<FiniteFieldElement>(() => Convert(0));
            _One = new Lazy<FiniteFieldElement>(() => Convert(1));
        }
    }

    public abstract class FiniteFieldElement {
        internal abstract FiniteField Field { get; }

        public static FiniteFieldElement operator -(FiniteFieldElement a) {
            return a.Field.Negate(a);
        }

        public static FiniteFieldElement operator +(FiniteFieldElement a, FiniteFieldElement b) {
            if (a.Field != b.Field) throw new ArgumentOutOfRangeException("b");
            return a.Field.Add(a, b);
        }

        public static FiniteFieldElement operator *(FiniteFieldElement a, FiniteFieldElement b) {
            if (a.Field != b.Field) throw new ArgumentOutOfRangeException("b");
            return a.Field.Mul(a, b);
        }

        public static bool operator ==(FiniteFieldElement a, FiniteFieldElement b) {
            if (Equals(a, null)) return Equals(b, null);
            else if (Equals(b, null)) return false;

            if (a.Field != b.Field) throw new ArgumentOutOfRangeException("b");
            return a.Field.Eq(a, b);
        }

        public static bool operator !=(FiniteFieldElement a, FiniteFieldElement b) { return !(a == b); }

        public override bool Equals(object obj) {
            return (obj is FiniteFieldElement) && (obj as FiniteFieldElement).Field == Field && this == (obj as FiniteFieldElement);
        }

        public override int GetHashCode() { return Field.Convert(this).GetHashCode(); }

        public override string ToString() { return Field.Convert(this).ToString(); }
    }

    public class PrimeField : FiniteField {
        private readonly int _Prime;
        private readonly PrimeFieldElement[] _Featherweight;

        internal int Prime { get { return _Prime; } }
        public override int Size { get { return _Prime; } }

        public PrimeField(int prime) {
            if (prime < 2) throw new ArgumentOutOfRangeException("prime");

            // TODO A primality test would be nice...

            _Prime = prime;
            _Featherweight = new PrimeFieldElement[Math.Min(prime, 256)];
        }

        internal override FiniteFieldElement Convert(int i) {
            if (i < 0 || i >= _Prime) throw new ArgumentOutOfRangeException("i");
            if (i >= _Featherweight.Length) return new PrimeFieldElement(this, i);
            if (Equals(_Featherweight[i], null)) _Featherweight[i] = new PrimeFieldElement(this, i);
            return _Featherweight[i];
        }

        internal override int Convert(FiniteFieldElement f) {
            if (f == null) throw new ArgumentNullException("f");
            if (f.Field != this) throw new ArgumentOutOfRangeException("f");

            return (f as PrimeFieldElement).Value;
        }

        internal override bool Eq(FiniteFieldElement a, FiniteFieldElement b) {
            if (a.Field != this) throw new ArgumentOutOfRangeException("a");
            if (b.Field != this) throw new ArgumentOutOfRangeException("b");

            return (a as PrimeFieldElement).Value == (b as PrimeFieldElement).Value;
        }

        internal override FiniteFieldElement Negate(FiniteFieldElement a) {
            if (a.Field != this) throw new ArgumentOutOfRangeException("a");
            var fa = a as PrimeFieldElement;
            return fa.Value == 0 ? fa : Convert(_Prime - fa.Value);
        }

        internal override FiniteFieldElement Add(FiniteFieldElement a, FiniteFieldElement b) {
            if (a.Field != this) throw new ArgumentOutOfRangeException("a");
            if (b.Field != this) throw new ArgumentOutOfRangeException("b");

            return Convert(((a as PrimeFieldElement).Value + (b as PrimeFieldElement).Value) % _Prime);
        }

        internal override FiniteFieldElement Mul(FiniteFieldElement a, FiniteFieldElement b) {
            if (a.Field != this) throw new ArgumentOutOfRangeException("a");
            if (b.Field != this) throw new ArgumentOutOfRangeException("b");

            return Convert(((a as PrimeFieldElement).Value * (b as PrimeFieldElement).Value) % _Prime);
        }

        public override string ToString() { return string.Format("F({0})", _Prime); }
    }

    internal class PrimeFieldElement : FiniteFieldElement {
        private readonly PrimeField _Field;
        private readonly int _Value;

        internal override FiniteField Field { get { return _Field; } }
        internal int Value { get { return _Value; } }

        internal PrimeFieldElement(PrimeField field, int val) {
            if (field == null) throw new ArgumentNullException("field");
            if (val < 0 || val >= field.Prime) throw new ArgumentOutOfRangeException("val");

            _Field = field;
            _Value = val;
        }
    }

    public class PowerField : FiniteField {
        private readonly FiniteField _BaseField;
        private readonly FiniteFieldElement[] _Polynomial;

        internal FiniteField BaseField { get { return _BaseField; } }
        internal int Power { get { return _Polynomial.Length; } }
        public override int Size { get { return (int)Math.Pow(_BaseField.Size, Power); } }

        public PowerField(FiniteField baseField, FiniteFieldElement[] polynomial) {
            if (baseField == null) throw new ArgumentNullException("baseField");
            if (polynomial == null) throw new ArgumentNullException("polynomial");
            if (polynomial.Length < 2) throw new ArgumentOutOfRangeException("polynomial");
            for (int i = 0; i < polynomial.Length; i++) if (polynomial[i].Field != baseField) throw new ArgumentOutOfRangeException("polynomial[" + i + "]");

            // TODO Check that the polynomial is irreducible over the base field.

            _BaseField = baseField;
            _Polynomial = polynomial.ToArray();
        }

        internal override FiniteFieldElement Convert(int i) {
            if (i < 0 || i >= Size) throw new ArgumentOutOfRangeException("i");

            var vec = new FiniteFieldElement[Power];
            for (int j = 0; j < vec.Length; j++) {
                vec[j] = BaseField.Convert(i % BaseField.Size);
                i /= BaseField.Size;
            }

            return new PowerFieldElement(this, vec);
        }

        internal override int Convert(FiniteFieldElement f) {
            if (f == null) throw new ArgumentNullException("f");
            if (f.Field != this) throw new ArgumentOutOfRangeException("f");

            var pf = f as PowerFieldElement;
            int i = 0;
            for (int j = Power - 1; j >= 0; j--) i = i * BaseField.Size + BaseField.Convert(pf.Value[j]);
            return i;
        }

        internal override bool Eq(FiniteFieldElement a, FiniteFieldElement b) {
            if (a.Field != this) throw new ArgumentOutOfRangeException("a");
            if (b.Field != this) throw new ArgumentOutOfRangeException("b");

            var fa = a as PowerFieldElement;
            var fb = b as PowerFieldElement;
            for (int i = 0; i < Power; i++) if (fa.Value[i] != fb.Value[i]) return false;
            return true;
        }

        internal override FiniteFieldElement Negate(FiniteFieldElement a) {
            if (a.Field != this) throw new ArgumentOutOfRangeException("a");
            return new PowerFieldElement(this, (a as PowerFieldElement).Value.Select(x => -x).ToArray());
        }

        internal override FiniteFieldElement Add(FiniteFieldElement a, FiniteFieldElement b) {
            if (a.Field != this) throw new ArgumentOutOfRangeException("a");
            if (b.Field != this) throw new ArgumentOutOfRangeException("b");

            var fa = a as PowerFieldElement;
            var fb = b as PowerFieldElement;
            var vec = new FiniteFieldElement[Power];
            for (int i = 0; i < Power; i++) vec[i] = fa.Value[i] + fb.Value[i];
            return new PowerFieldElement(this, vec);
        }

        internal override FiniteFieldElement Mul(FiniteFieldElement a, FiniteFieldElement b) {
            if (a.Field != this) throw new ArgumentOutOfRangeException("a");
            if (b.Field != this) throw new ArgumentOutOfRangeException("b");

            var fa = a as PowerFieldElement;
            var fb = b as PowerFieldElement;

            // We consider fa and fb as polynomials of a variable x and multiply modulo (x^Power - _Polynomial).
            // But to keep things simple we want to manage the cascading modulo.
            var vec = Enumerable.Repeat(BaseField.Zero, Power).ToArray();
            var fa_xi = fa.Value.ToArray();
            for (int i = 0; i < Power; i++) {
                for (int j = 0; j < Power; j++) vec[j] += fb.Value[i] * fa_xi[j];
                if (i < Power - 1) ShiftLeft(fa_xi);
            }

            return new PowerFieldElement(this, vec);
        }

        private void ShiftLeft(FiniteFieldElement[] vec) {
            FiniteFieldElement head = vec[vec.Length - 1];
            for (int i = vec.Length - 1; i > 0; i--) vec[i] = vec[i - 1] + head * _Polynomial[i];
            vec[0] = head * _Polynomial[0];
        }

        public static FiniteField Create(FiniteField baseField, int power) {
            if (baseField == null) throw new ArgumentNullException("baseField");
            if (power < 2) throw new ArgumentOutOfRangeException("power");

            // Since the field is cyclic, there is only one finite field of a given prime power order (up to isomorphism).
            // For most practical purposes that means that we can pick any arbitrary monic irreducible polynomial.
            // We can abuse PowerField to do polynomial multiplication in the base field.
            var fakeField = new PowerField(baseField, Enumerable.Repeat(baseField.Zero, power).ToArray());
            var excluded = new HashSet<FiniteFieldElement>();
            for (int lpow = 1; lpow <= power / 2; lpow++) {
                int upow = power - lpow;
                // Consider all products of a monic polynomial of order lpow with a monic polynomial of order upow.
                int xl = (int)Math.Pow(baseField.Size, lpow);
                int xu = (int)Math.Pow(baseField.Size, upow);
                for (int i = xl; i < 2 * xl; i++) {
                    var pi = fakeField.Convert(i);
                    for (int j = xu; j < 2 * xu; j++) {
                        var pj = fakeField.Convert(j);
                        excluded.Add(-(pi * pj));
                    }
                }
            }

            for (int p = baseField.Size; true; p++) {
                var pp = fakeField.Convert(p) as PowerFieldElement;
                if (!excluded.Contains(pp)) return new PowerField(baseField, pp.Value.ToArray());
            }
        }

        public override string ToString() {
            var sb = new System.Text.StringBuilder();
            sb.AppendFormat("GF({0}) with primitive polynomial x^{1} ", Size, Power);
            for (int i = Power - 1; i >= 0; i--) sb.AppendFormat("+ {0}x^{1}", _Polynomial[i], i);
            sb.AppendFormat(" over base field ");
            sb.Append(_BaseField);
            return sb.ToString();
        }
    }

    internal class PowerFieldElement : FiniteFieldElement {
        private readonly PowerField _Field;
        private readonly FiniteFieldElement[] _Vector; // The version of Mono I have doesn't include IReadOnlyList<T>

        internal override FiniteField Field { get { return _Field; } }
        internal FiniteFieldElement[] Value { get { return _Vector; } }

        internal PowerFieldElement(PowerField field, params FiniteFieldElement[] vector) {
            if (field == null) throw new ArgumentNullException("field");
            if (vector == null) throw new ArgumentNullException("vector");
            if (vector.Length != field.Power) throw new ArgumentOutOfRangeException("vector");
            for (int i = 0; i < vector.Length; i++) if (vector[i].Field != field.BaseField) throw new ArgumentOutOfRangeException("vector[" + i + "]");

            _Field = field;
            _Vector = vector.ToArray();
        }
    }
}

Results

Unfortunately adding the rulers would take me about 15k characters past the post size limit, so they're on pastebin.


Python - 125 points

304 chars
follows steps 1-5 (works for me on irc.freenode.net:6667. if you try there, remember IDENT might take a while, so give it 20+ seconds to connect and speak)
follows 4 restrictions (assuming the NOTICE restriction which is a bit unclear. the UTF restriction counts because python won't choke if it doesn't need to parse any UTF).

score math (python):

bonus = 1 # connects to channel
bonus *= 2 # steps 1-5
for i in xrange(4):
    bonus *= 1.05 # 4 restrictions

int(304.0/bonus)
> 125

code:

import socket
i=raw_input
u=i('user# ')
n=i('nick# ')
h,p=i('host:port# ').split(':',1)
p=int(p)
c='#'+i('chan# ')
z=0
while 1:
 try:
  def s(m): z.send(m+'\r\n')
  z.recv(9)
 except:
  z=socket.socket();z.connect((h,p));s('USER '+n+' 0 * :'+n);s('NICK '+n);s('JOIN '+c);s('PRIVMSG '+c+' :Hello, world!')


Is the cake a lie?

As there has been much debate over whether the cake is or is not a lie, I wrote this program to answer this contentious question.

#include <stdio.h>

// checks if two things are equal
#define EQUALS(a,b) (sizeof(a)==sizeof(b))

struct Cake{int Pie;}; // the cake is a pie!
typedef struct Cake Lie;
main(){
    struct CakeBox{
        struct Cake{ // the cake contains lies!
            Lie Lies[2];
        };
    };
    typedef struct Cake Cake;

    printf("The cake is ");
    if(EQUALS(Cake, Lie)){
        printf("a LIE!\n");
    }else{
        printf("..not a lie?\n");
    }
    return 0;
}

What will the outcome be?

C:

   The cake is ..not a lie?

C++:

   The cake is a LIE!


Python, 100

s="IVXLCDM"
r=raw_input()
a=""
i=2
u=0
for c in s:r+=u/i*c;i=7-i;u=r.count(c);a+=u%i*c
print a[::-1]

Takes one string from input (e.g. VIII + XII or VIII + XII =).


Synergistic

I'm not really a Python guy, but wanted to give this a go. This builds the set of playable cards at each turn, and assigns each of them a simple static score. The card with the highest score is played (assuming any playable card exists).

def synergistic(cards_in_hand, played_cards):
    def list2dict(lst):
        d = {}
        for val, suit in lst:
            if suit in d:
                d[suit].append(val)
            else:
                d[suit] = [val]
        return d
    def play_card(card):
        cards_in_hand.remove(card)
        played_cards.append(card)

    hand = list2dict(cards_in_hand)
    if not played_cards:
        if 7 in hand['hearts']:
            play_card([7, 'hearts'])
        return (cards_in_hand, played_cards)
    table = list2dict(played_cards)

    playable_cards = {}
    for suit in hand:
        if 7 in hand[suit]:
            playable_cards[(7, suit)] = -1

        if suit not in table:
            continue
        visible = set(table[suit] + hand[suit])
        opp_hand = set(range(1,14)) - visible
        highcard = max(table[suit]) + 1

        if highcard in hand[suit]:
            if highcard+1 in opp_hand:
                playable_cards[(highcard, suit)] = 1
            else:
                playable_cards[(highcard, suit)] = 2

        lowcard = min(table[suit]) - 1
        if lowcard in hand[suit]:
            if lowcard - 1 in opp_hand:
                playable_cards[(lowcard, suit)] = 0
            else:
                playable_cards[(lowcard, suit)] = 1

    if not playable_cards:
        return (cards_in_hand, played_cards)

    best_card = list(max(playable_cards, key=playable_cards.get))
    #print(hand, "\n", table, "\n", best_card)
    play_card(best_card)

    return (cards_in_hand, played_cards)

By the way, the controller seemed to have several issues, including in score calculation and comparison. I made some changes to the controller here, please take a look  and update your version if this seems right.

Two things I haven't fixed in the controller:

why is the loop condition (win2 <= 50) and (win1 <= 100) ? This should probably be symmetrical, it should exit the loop whenever either of the players has 100 consecutive wins.
trying some runs of the controller locally, with the same function for both players, Player 2 seems to win most of the time - it can't be inherent to the game since the initial 7H requirement would smooth that out (as @Veskah mentioned in the comments), so, yet undetected controller bugs? Or my player code somehow maintaining state and having a bias this way? Per-game, it's not like Player 2 dominates heavily (from the results output txt), but somehow the overall score per controller run ends up favouring player 2 much more than random (Player 1's total scores are often more than 2x that of Player 2).


Implement bit-wise matrix multiplication

APL, 28 characters
f←{2⊥,↑≠.×/{8 8⍴(64⍴2)⊤⍵}¨⍵}

Usage:
> f 12345678 87654321
3977539

You can read it almost literally if you go right-to-left. (64⍴2)⊤ transforms each argument into 64 bit representation and 8 8⍴ makes an 8x8 matrix out of the results. ≠.×/ then applies the inner product to both arguments, where multiplication × and xor ≠ is used. The matrix is then transformed back to vector form ,↑, before 2⊥ undoes the basis transformation.


APL (Dyalog Unicode), 39 bytesSBCS

Anonymous prefix function. Call by spawning on the dummy argument ⍬ (empty numeric vector), i.e. f&⍬. Query currently running threads with ⎕TNUMS and kill one or more threads with ⎕TKILL n. Threads output changes in [own number, total number] as soon as they get processor time, i.e. pretty much instantly.

{⍵≡n←n[⍋n←⎕TNUMS~0]:∇n⋄∇n⊣⎕←n⍳⎕TID,⊢/n}

Try it online!

{…} anonymous lambda where ⍵ is the argument (initially ⍬, the empty numeric vector)

 n[…] index n (to be defined) with:

  ⎕TNUMS~0 all Thread Numbers except number 0 (the REPL)

   n← store as n

   ⍋ permutation which would sort ascending

  now we have the active threads in order

  ⍵≡ if the argument is identical to that…

  : then:

   ∇⍵ tail recurse on the argument

  ⋄ else:

   ⊢/n the rightmost thread number

   ⎕TID, this Thread's ID (thread number) prepended to that

   n⍳ find the ɩndices of those two

   ⎕← print that to STDOUT

   n⊣ discard that in favour of n

   ∇ recurse on that


Bash, 48 46 bytes

cd `mktemp -d`
xargs -d\\n tee
stty cols $1
ls

Guaranteed to work like ls.


Capitalize first letter of each word of input

CJam, 15 13 bytes

Lq{_eu?_S-}/;

Try it online in the CJam interpreter.

Pseudocode

L             e# B := ""
 q            e# Q := input()
  {       }/  e# for C in Q:
   _eu?       e#     C := B ? C : uppercase(C)
       _S-    e#     B := string(C).strip(" ")
            ; e# discard(B)

All modified characters C are left on the stack and, therefore, printed when exiting.


Python,  54  52 bytes

lambda a,b:[v for v in(a,b,a*b%-~99)if'd'>chr(v)][2]

An unnamed function raising an error if either of the inputs are fake otherwise returning the product of the inputs modulo 100 (always real and correct if the product itself is real).

Try it online!

How?

First creates a tuple of the inputs and their product modulo 100 using (a,b,a*b%-~99) where ~x computes -1-x and % is the modulo operator.

Then traverses that tuple creating a list of those values which are real numbers.

The test for real-ness is performed by first attempting to cast each value, v, to characters with chr(v) - which will raise a ValueError if v is not a non-negative integer less than 256, then checking the value is less than 100 by a less-than-comparison, <, to the 100th character, 'd'.

If both a and b are real the list will have three entries (the product modulo 100 is alway real), otherwise it will have less. The [...][2] attempts to get the item at the second index (third item), raising an IndexError if it does not exist.

Thus either input being fake results in either a ValueError or IndexError, while both inputs being real always succeeds and returns a real number, and if that product is itself real it is the returned value.


Print the sizes of intervals inside of a piece of music


Haskell, 92 90 86 84 114 110 99 98
the requirement of a full program is so annoying. I wonder why would anyone require this.
m(n:s)=all(<1)$foldl(\r@(p:s)n->reverse(take n s)++(p*r!!n):drop n s)[0..n]s
main=readLn>>=print.m

this solution works by representing the pile of pancakes by a list of the sides, when adjacent pancakes share the same side. every side is a number, and a side is coated if it has a zero value.
run as:
*Main> main
[2,1,1,2,2]
True


Partition a square grid into parts of equal area

JavaScript (ES7), 166 bytes
Outputs a matrix of integers that describe the partition, or \$false\$ if there's no solution.

a=>(m=a.map(_=>[...a]),g=(n,X,Y,j=0,i)=>a[n]?a[j]?m.some((r,y)=>r.some((v,x)=>++v|(X-x)**2+(Y-y)**2-1?0:g(r[x]=n,x,y,j+1,i|x+[,y]==a[n])?1:r[x]=v)):i&&g(n+1):1)(0)&&m

Try it online!
How?
We first build a square matrix \$m\$ of size \$N\times N\$, where \$N\$ is the length of the input:
m = a.map(_ => [...a])

Each row of \$m\$ consists of a copy of the input, i.e. an array of \$N\$ coordinate pairs. The important point here is that all cells of \$m\$ are initialized to non-numeric values. We'll be able to detect them by applying the prefix increment operator ++.
The recursive function \$g\$ takes a pointer \$n\$ into the input, the coordinates \$(X,Y)\$ of the previous cell, a counter \$j\$ that holds the number of filled cells in the current area, and a flag \$i\$ that is set when the marked cell is found in the area:
g = (n, X, Y, j = 0, i) => a[n] ? a[j] ? ... : i && g(n + 1) : 1

We test \$a[n]\$ to know if all areas have been processed and we test \$a[j]\$ to know if enough cells have been filled in the current area.
The main part of \$g\$ looks for the next cell of \$m\$ to fill by iterating on all of them:
m.some((r, y) =>          // for each row r[] at position y in m[]:
  r.some((v, x) =>        //   for each cell of value v at position x in r[]:
    ++v |                 //     if this cell is already filled (i.e. v is numeric)
    (X - x) ** 2 +        //     or the squared Euclidean distance between
    (Y - y) ** 2 -        //     (X, Y) and (x, y)
    1 ?                   //     is not equal to 1:
      0                   //       this is an invalid target square: do nothing
    :                     //     else:
      g(                  //       do a recursive call to g:
        r[x] = n,         //         pass n unchanged and fill the cell with n
        x, y,             //         pass the coordinates of the current cell
        j + 1,            //         increment j
        i |               //         update i:
        x + [,y] == a[n]  //         set it if (x, y) = a[n]
      ) ?                 //       if the result of the call is truthy:
        1                 //         return 1
      :                   //       else:
        r[x] = v          //         reset the cell to NaN
  )                       //   end of inner map()
)                         // end of outer map()


Retina, 51 bytes

.*[aeio]$
1
A`en$|ch|ei|au
^$
2
A`[jkz]|gy|m$
\D+
4

I came up with the regexes and @MartinBüttner did the conversion to/golfing in Retina so ... hurray for team effort?

The mapping is 1 -> Italian, 2 -> German, (empty) -> Hungarian, 4  -> English, with the amount classified in each category being 4506 + 1852 + 2092 + 3560 = 12010.

Try it online! | Modified multiline version

Explanation

First off, the equivalent Python is something like this:

import re
def f(s):
  if re.search("[aeio]$", s):
    return 1
  if re.search("en$|ch|ei|au", s):
    return 2
  if re.search("[jkz]|gy|m$", s):
    return ""
  return 4

Let me just say that o$ is an excellent indicator of Italian.

The Retina version is similar, with pairs of lines forming replacement stages. For example, the first two lines

.*[aeio]$
1

replaces matches of the first line with the contents of the second.

The next three lines do the same, but using Retina's anti-grep mode - anti-grep (specified with A`) removes the line if it matches the given regex, and the following two lines is a replacement from an empty line to the desired output.

A`en$|ch|ei|au
^$
2

The following line uses anti-grep again, but doesn't replace the empty line, giving the fixed output for Hungarian.

A`[jkz]|gy|m$

Finally, the last two lines

\D+
4

replaces a non-empty non-digit line with 4. All of the substitutions can only happen if no previous substitution activated, simulating an if/else if chain.