text:
Multiply Quaternions
Write a named function or program that computes the quaternion product of two quaternions. Use as few bytes as possible.
Quaternions
Quaternions are an extension of the real numbers that further extends the complex numbers. Rather than a single imaginary unit i, quaternions use three imaginary units i,j,k that satisfy the relationships.
i*i = j*j = k*k = -1
i*j =  k
j*i = -k
j*k =  i
k*j = -i
k*i =  j
i*k = -j

(There's also tables of these on the Wikipedia page.)
In words, each imaginary unit squares to -1, and the product of two different imaginary units is the remaining third one with a +/- depending on whether the cyclic order (i,j,k) is respected (i.e., the right-hand-rule). So, the order of multiplication matters.
A general quaternion is a linear combination of a real part and the three imaginary units. So, it is described by four real numbers (a,b,c,d).
x = a + b*i + c*j + d*k
So, we can multiply two quaternions using the distributive property, being careful to multiply the units in the right order, and grouping like terms in the result.
(a + b*i + c*j + d*k) * (e + f*i + g*j + h*k)
= (a*e - b*f - c*g - d*h)    +
  (a*f + b*e + c*h - d*g)*i  +
  (a*g - b*h + c*e + d*f)*j  +
  (a*h + b*g - c*f + d*e)*k

Seen this way, quaternion multiplication can be seen as a map from a pair of 4-tuples to a single 4-tuples, which is what you're asked to implement.
Format
You should write either a program or named function. A program should take inputs from STDIN and print out the result. A function should take in function inputs and return (not print) an output.
Input and output formats are flexible. The input is eight real numbers (the coefficients for two quaternions), and the output consists of four real numbers. The input might be eight numbers, two lists of four numbers, a 2x4 matrix, etc. The input/output format don't have to be the same.The ordering of the (1,i,j,k) coefficients is up to you.
The coefficients can be negative or non-whole. Don't worry about real precision or overflows.
Banned: Function or types specifically for quaternions or equivalents.
Test cases
These are in (1,i,j,k) coefficient format.
[[12, 54, -2, 23], [1, 4, 6, -2]]
 [-146, -32, 270, 331]

[[1, 4, 6, -2], [12, 54, -2, 23]]
 [-146, 236, -130, -333]

[[3.5, 4.6, -0.24, 0], [2.1, -3, -4.3, -12]]
 [20.118, 2.04, 39.646, -62.5]

Reference Implementation
In Python, as function:
#Input quaternions: [a,b,c,d], [e,f,g,h]
#Coeff order: [1,i,j,k]

def mult(a,b,c,d,e,f,g,h):
    coeff_1 = a*e-b*f-c*g-d*h
    coeff_i = a*f+b*e+c*h-d*g
    coeff_j = a*g-b*h+c*e+d*f
    coeff_k = a*h+b*g-c*f+d*e

    result = [coeff_1, coeff_i, coeff_j, coeff_k]
    return result

CJam, 49 45 39 bytes
"cM-^\M-^G-^^KM-zP"256bGbq~m*f{=:*}4/{:-W*}/W*]`

The above uses caret and M notation, since the code contains unprintable characters.
At the cost of two additional bytes, those characters can be avoided:
6Z9C8 7YDXE4BFA5U]q~m*f{=:*}4/{:-W*}/W*]`

You can try this version online: CJam interpreter
Test cases
To calculate (a + bi + cj + dk) * (e + fi + gj + hk), use the following input:
[ d c b a ] [ h g f e ]

The output will be
[ z y x w ]

which corresponds to the quaternion w + xi + yj + zk.
$ base64 -d > product.cjam <<< ImOchy0eS/pQIjI1NmJHYnF+bSpmez06Kn00L3s6LVcqfS9XKl1g
$ wc -c product.cjam
39 product.cjam
$ LANG=en_US cjam product.cjam <<< "[23 -2 54 12] [-2 6 4 1]"; echo
[331 270 -32 -146]
$ LANG=en_US cjam product.cjam <<< "[-2 6 4 1] [23 -2 54 12]"; echo
[-333 -130 236 -146]
$ LANG=en_US cjam product.cjam <<< "[0 -0.24 4.6 3.5] [-12 -4.3 -3 2.1]"; echo
[-62.5 39.646 2.04 20.118]

How it works
6Z9C8 7YDXE4BFA5U]  " Push the array [ 6 3 9 12 8 7 2 13 1 14 4 11 15 10 5 0].         ";
q~                  " Read from STDIN and interpret the input.                         ";
m*                  " Compute the cartesian product of the input arrays.               ";
f                   " Execute the following for each element of the first array:       ";
{                   " Push the cartesian product (implicit).                           ";
    =               " Retrieve the corresponding pair of coefficients.                 ";
    :*              " Calculate their product.                                         ";
}                   "                                                                  ";
4/                  " Split into chunks of 4 elements.                                 ";
{:-W*}/             " For each, subtract the first element from the sum of the others. ";
W*                  " Multiply the last integers (coefficient of 1) by -1.             ";
]`                  " Collect the results into an array and stringify it.              ";

Python (83)
r=lambda A,B,R=range(4):[sum(A[m]*B[m^p]*(-1)**(14672>>p+4*m)for m in R)for p in R]

Takes two lists A,B in [1,i,j,k] order and returns a result in the same format.
The key idea is that with [1,i,j,k] corresponding to indices [0,1,2,3], you get the product's index (up to sign) by XOR'ing the indices. So, the terms that get placed in index p are those who indices XOR to p, and are thus the products A[m]*B[m^p].
It only remains to make the signs work out. The shortest way I found was to simply code them into a magic string. The 16 possibilities for (m,p) are turned into numbers 0 to 15 as p+4*m. The number 14672 in binary has 1's at the places where -1 signs are needed. By shifting it the appropriate number of places , a 1 or 0 winds up at the last digit, making the number odd or even, and so (-1)** is either 1 or -1 as needed.

The XOR part is pure genius.

Python - 90 75 72 69
Pure Python, no libraries - 90:
m=lambda a,b,c,d,e,f,g,h:[a*e-b*f-c*g-d*h,a*f+b*e+c*h-d*g,a*g-b*h+c*e+d*f,a*h+b*g-c*f+d*e]

It's probably pretty hard to shorten this "default" solution in Python. But I'm very curious as to what other might come up with. :)

Using NumPy - 75 72 69:
Well, since the input and output are rather flexible, we can use some NumPy functions and exploit the scalar-vector representation:
import numpy
m=lambda s,p,t,q:[s*t-sum(p*q),s*q+t*p+numpy.cross(p,q)]

Input arguments s and t are the scalar parts of the two quaternions (the real parts) and p and q are the corresponding vector parts (the imaginary units). Output is a list containing scalar part and vector part of the resulting quaternion, the latter being represented as NumPy array.
Simple test script:
for i in range(5):
    a,b,c,d,e,f,g,h=np.random.randn(8)
    s,p,t,q=a, np.array([b, c, d]), e, np.array([f, g, h])
    print mult(a, b, c, d, e, f, g, h), "\n", m(s,p,t,q)

(mult(...) being the OP's reference implementation.)
Output:
[1.1564241702553644, 0.51859264077125156, 2.5839001110572792, 1.2010364098925583]
[1.1564241702553644, array([ 0.51859264,  2.58390011,  1.20103641])]
[-1.8892934508324888, 1.5690229769129256, 3.5520713781125863, 1.455726589916204]
[-1.889293450832489, array([ 1.56902298,  3.55207138,  1.45572659])]
[-0.72875976923685226, -0.69631848934167684, 0.77897519489219036, 1.4024428845608419]
[-0.72875976923685226, array([-0.69631849,  0.77897519,  1.40244288])]
[-0.83690812141836401, -6.5476014589535243, 0.29693969165495304, 1.7810682337361325]
[-0.8369081214183639, array([-6.54760146,  0.29693969,  1.78106823])]
[-1.1284033842268242, 1.4038096725834259, -0.12599103441714574, -0.5233468317643214]
[-1.1284033842268244, array([ 1.40380967, -0.12599103, -0.52334683])]

Mathematica 83 50
Probably can be golfed more..
p = Permutations;
f = #1.(Join[{{1, 1, 1, 1}}, p[{-1, 1, -1, 1}][[1 ;; 3]]] p[#2][[{1, 8, 17, 24}]]) &

Spaces and newlines not counted & not needed.
Usage:
f[{a,b,c,d},{e,f,g,h}]        (* => {x,w,y,z}   *)

EDIT
How this works.
The Mathematica function Permutations makes all possible permutations of #2 (the second argument). There are 24 permutations, but we only need {e,f,g,h}, {f,e,h,g}, {g,h,e,f}, and {h,g,f,e}. These are the first, 8th, 17th and 24th permutations. So the code
p[#2][[{1,8,17,24}]]

exactly selects these from the permutations of the second argument and returns them as a matrix. But then they don't have the correct sign yet. The code p[{-1,1,-1,1}][[1;;3]] returns a 3x4 matrix with the correct sign. We prepend it with {1,1,1,1} by using Join, and making a normal multiplication (Times, or as is the case here by just writing them after each other) between two matrices makes an element-by-element multiplication in Mathematica.
So finally, the result of
(Join[{{1, 1, 1, 1}}, p[{-1, 1, -1, 1}][[1 ;; 3]]] p[#2][[{1, 8, 17, 24}]])

is the matrix
 e  f  g  h
-f  e -h  g
-g  h  e -f
-h -g  f  e

Making a matrix multiplication between {a,b,c,d} (the first argument #1) and the former matrix gives the desired result.

EDIT 2 Shorter code
Inspired by the Python code of Falko, I split up the quaternion in a scalar and a vector part, and use Mathematica's built in command Cross to calculate the cross product of the vector parts:
f[a_, A_, b_, B_] := Join[{a*b - A.B}, a*B + b*A + Cross[A, B]]

Usage:
f[a,{b,c,d},e,{f,g,h}]        (* => {x,w,y,z}   *)

Could you explain how this works?  What are 1, 8, 17, 24?

Haskell, 85
m a b c d e f g h=[a*e-b*f-c*g-d*h,a*f+b*e+c*h-d*g,a*g-b*h+c*e+d*f,a*h+b*g-c*f+d*e]

Porting it to Haskell saves us a few chars ;)

Python, 58 56 chars
m=lambda x,y,z,w:(x*z-y*(2*w.real-w),x*w+y*(2*z.real-z))

I take very liberal use of the input/output format wiggle room.  The inputs are 4 complex numbers, encoded thusly:
x = a+b*i
y = c+d*i
z = e+f*i
w = g+h*i

It outputs a pair of complex numbers in a similar format, the first of the pair encodes the real and i part, the second encodes the j and k parts.
To see this works, note that the first quaternion is x+y*j and the second is z+w*j.  Just evaluate (x+y*j)*(z+w*j) and realize that j*t = conj(t)*j for any imaginary number t.

Very clever! Do you know why the quaternions seem to multiply like complex numbers with complex coefficients, as it looks from your expression?

Never mind, I now understand from your explanation how i and j act like as inner and outer complex coefficients. How fascinating!

It's funny how the conj calls take up more than 2/5 of your chars. I think you can shave a char each using (2*w.real-w). abs(w)**2/w would work but for 0. Maybe even exec with string substitution would be worth it? `

Python, 94
The most straightforward way isn't too long.
def m(a,b,c,d,e,f,g,h):return[a*e-b*f-c*g-d*h,a*f+b*e+c*h-d*g,a*g-b*h+c*e+d*f,a*h+b*g-c*f+d*e]

JavaScript ES6 - 86
f=(a,b,c,d,e,f,g,h)=>[a*e-b*f-c*g-d*h,a*f+b*e+c*h-d*g,a*g-b*h+c*e+d*f,a*h+b*g-c*f+d*e]

Lua - 99
Might as well.
_,a,b,c,d,e,f,g,h=unpack(arg)print(a*e-b*f-c*g-d*h,a*f+b*e+c*h-d*g,a*g-b*h+c*e+d*f,a*h+b*g-c*f+d*e)

Lua's "unpack()" frees the elements of a table. So the table 'arg' is where all the command line input is stored (including arg[0] which is the program's file name, it gets discarded).

Whispers v2, 396 bytes
> 1
> 2
> 0
> 4
> Input
> Input
>> 6ᶠ2
>> 6ᵗ2
>> 7ⁿ3
>> 7ⁿ1
>> 10‖9
>> 8ⁿ3
>> 8ⁿ1
>> 13‖12
>> 7‖8
>> 11‖14
>> 8‖7
>> 14‖11
>> 15‖16
>> 19‖17
>> 20‖18
>> 4⋅5
>> L⋅R
>> Each 23 22 21
> [1,-1,-1,-1,1,1,1,-1,1,-1,1,1,1,1,-1,1]
>> Each 23 24 25
>> 26ᶠ4
>> 26ᵗ4
>> 28ᶠ4
> 8
>> 26ᵗ30
>> 31ᶠ4
>> 31ᵗ4
>> ∑27
>> ∑29
>> ∑32
>> ∑33
>> Output 34 35 36 37

Try it online!
Takes input in the form
[a, b, c, d]
[e, f, g, h]

and outputs as
w
x
y
z

to represent \$q = w + xi + yj + zk\$
The structure tree of this answer is:

A good chunk of this answer comes from two main faults in Whispers:

No function to reverse an array
The usage of sets in the computation of the Cartesian product

Therefore, we can split the code into 3 sections.
How it works
We'll use the following definitions for clarity and conciseness:
$$q = a + bi + cj + dk$$
$$p = e + fi + gj + hk$$
$$r = w + xi + yj + zk, \: (q \cdot p = r)$$
$$A = [a, b, c, d]$$
$$B = [e, f, g, h]$$
$$C = [w, x, y, z]$$
Section 1: Permuting \$A\$ and \$B\$
The first section is by far the longest, stretching from line 1 to line 22:
> 1
> 2
> 0
> 4
> Input
> Input
>> 6ᶠ2
>> 6ᵗ2
>> 7ⁿ3
>> 7ⁿ1
>> 10‖9
>> 8ⁿ3
>> 8ⁿ1
>> 13‖12
>> 7‖8
>> 11‖14
>> 8‖7
>> 14‖11
>> 15‖16
>> 19‖17
>> 20‖18
>> 4⋅5

The main purpose of this section is to permute \$B\$ so that simple element-wise multiplication between \$A\$ and \$B\$ is possible. There are four different arrangements of \$B\$ to multiply the elements of \$A\$ with:
$$B_1 = [e, f, g, h]$$
$$B_2 = [f, e, h, g]$$
$$B_3 = [g, h, e, f]$$
$$B_4 = [h, g, f, e]$$
The second input, \$B\$, is stored on line 6. We then split \$B\$ down the middle, as each possible arrangement of \$B\$ is grouped in pairs. In order to reverse these pairs (to get the correct orders in \$B_2\$ and \$B_4\$), we take the first and last element, then concatenate them in reverse order:
>> 7ⁿ3
>> 7ⁿ1
>> 10‖9

(forming \$[f, e]\$) and
>> 8ⁿ3
>> 8ⁿ1
>> 13‖12

(forming \$[h, g]\$). We now have all the halves needed to form the arrangements, so we concatenate them together to form \$B_1, B_2, B_3\$ and \$B_4\$. Finally, we concatenate these four arrangements together to form \$B_T\$. We then quickly make \$A_T\$, defined as \$A\$ repeated \$4\$ times:
$$A_T = [a, b, c, d, a, b, c, d, a, b, c, d, a, b, c, d]$$
$$B_T = [e, f, g, h, f, e, h, g, g, h, e, f, h, g, f, e]$$
When each element of \$B_T\$ is multiplied by the corresponding element in \$A_T\$, we get the (signless) values in \$q \cdot p\$
Section 2: Signs and products
As said in Section 1, the values in \$A_T\$ and \$B_T\$ correspond to the signless (i.e. positive) values of each of the coefficients in \$q \cdot p\$. No obvious pattern is found in the signs that would be shorter than simply hardcoding the array, so we hardcode the array:
> [1,-1,-1,-1,1,1,1,-1,1,-1,1,1,1,1,-1,1]

We'll call this array \$S\$ (signs). Next, we zip together each element in \$A_T, B_T\$ and \$S\$ and take the product of each sub-array e.g. \$[[a, e, 1], [b, f, -1], \dots, [e, f, -1], [d, e, 1]] \to D = [ae, -bf, \dots, -ef, de]\$.
Section 3: Partitions and final sums.
Once we have the array of coefficients of \$q \cdot p\$, with signs, we need to split it into 4 parts (i.e. the four factorised coefficients of \$q \cdot p\$), and then take the sums. This leads us to the only golfing opportunity found: moving the
> 4

to line 4 rather than 26, as it is used 6 times, each time saving a byte by moving it. Unfortunately, this costs a byte changing the 9 to a 10, so only \$5\$ bytes are saved. The next section takes slices of size \$4\$ from the front of \$D\$, saving each slice to the corresponding row and passing on the shortened list of \$D\$. Once 4 slices are taken, we the take the sum of each, before outputting them all.

Sidef, 10 bytes
{|a,b|a*b}

Sidef has a built-in Quaternion type, as does Odin. Neither language versions used by TIO support this, however.
var f = {|a,b|a*b}
say f(Quaternion(12, 54, -2, 23), Quaternion(1, 4, 6, -2))
#=> Quaternion(-146, -32, 270, 331)

say f(Quaternion(1, 4, 6, -2), Quaternion(12, 54, -2, 23))
#=> Quaternion(-146, 236, -130, -333)

say f(Quaternion(3.5, 4.6, -0.24, 0), Quaternion(2.1, -3, -4.3, -12))
#=> Quaternion(10059/500, 51/25, 19823/500, -125/2)

Go, 119 bytes
type F=float64
func f(a,b,c,d,e,f,g,h F)[]F{return[]F{a*e-b*f-c*g-d*h,a*f+b*e+c*h-d*g,a*g-b*h+c*e+d*f,a*h+b*g-c*f+d*e}}

Attempt This Online!
The very straightforward solution

Mathematica, 2 bytes
**

Definitely Mathematica has NonCommutativeMultiply for quaternions.
Reference: Official Documentation
Needs["Quaternions`"];

q1 = Quaternion[12, 54, -2, 23];
q2 = Quaternion[1, 4, 6, -2];
q3 = Quaternion[3.5, 4.6, -0.24, 0];
q4 = Quaternion[2.1, -3, -4.3, -12];

q1 ** q2
q2 ** q1
q3 ** q4

Quaternion[-146, -32, 270, 331]
Quaternion[-146, 236, -130, -333]
Quaternion[20.118, 2.04, 39.646, -62.5]

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

all_licenses: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
Find a thumbnail in a mosaic
After the last Ludum Dare (LD) game programming contest a friend of mine made a nice mosaic of all the LD game thumbnails:

After searching for my own game I quickly gave up and decided to solve it like a real programmer... by writing code that finds my game thumbnail.
This is the thumbnail of my game:

More examples can be found by going to the Ludum Dare list of games.
So what is the challenge? Write a program that has the following input:
<filename_mosaic> <amount_of_tiles_x> <amount_of_tiles_y> <filename_target>

For example using the images above:
mosaic.jpg 59 43 target.png

The output should be the index of the target image. For the mosaic and screenshot above the correct index is:
48,18

The following (non-golfed) code provides a working example:
public class MosaicFinder {

    //Start with java MosaicFinder mosaic.jpg  59 43 target.png
    public static void main(String[] args)  throws Exception {
        String mosaicFilename = args[0];
        int tilesX = Integer.parseInt(args[1]);
        int tilesY = Integer.parseInt(args[2]);
        String targetFilename = args[3];

        BufferedImage mosaic = ImageIO.read(new File(mosaicFilename));
        int tileHeight = mosaic.getHeight()/tilesY;
        int tileWidth = mosaic.getWidth()/tilesX;

        BufferedImage tofind = ImageIO.read(new File(targetFilename));

        //Translate target.png to correct size:
        BufferedImage matchCanvas = new BufferedImage(tileWidth, tileHeight, BufferedImage.TYPE_INT_RGB);
        AffineTransform at = AffineTransform.getScaleInstance((tileWidth*1.0)/tofind.getWidth(), (tileHeight*1.0)/tofind.getHeight());
        ((Graphics2D)matchCanvas.getGraphics()).drawRenderedImage(tofind, at);

        int bestIndexX = 0, bestIndexY = 0;
        BigInteger lowest = null;
        for(int x = 0; x<tilesX;x++) {
            for(int y = 0; y<tilesY;y++) {
                //For all tiles:
                BigInteger error = BigInteger.ZERO;
                for(int x1 = 0; x1<tileWidth;x1++) {
                    for(int y1 = 0; y1<tileHeight;y1++) {
                        int rgb1 = matchCanvas.getRGB(x1, y1);
                        int rgb2 = mosaic.getRGB((x*tileWidth)+x1, (y*tileHeight)+y1);
                        int r1 = (rgb1 >> 16) & 0xFF;
                        int r2 = (rgb2 >> 16) & 0xFF;
                        error = error.add(BigInteger.valueOf(Math.abs(r1-r2)));

                        int g1 = (rgb1) & 0xFF;
                        int g2 = (rgb2) & 0xFF;
                        error = error.add(BigInteger.valueOf(Math.abs(g1-g2)));

                        int b1 = rgb1 & 0xFF;
                        int b2 = rgb2 & 0xFF;
                        error = error.add(BigInteger.valueOf(Math.abs(b1-b2)));
                    }
                }
                if(lowest == null || lowest.compareTo(error) > 0) {
                    lowest = error;
                    bestIndexX = (x+1);
                    bestIndexY = (y+1);
                }
            }
        }
        System.out.println(bestIndexX+","+bestIndexY);
    }
}

This is a visual example of the code running:

This contest is a code-golf contest, the shortest code wins the challenge.
Update: It seems stackexchange messes up the images a bit, on my blog you can find the source images for the examples in correct resolution.
Also: I've fixed the amount of images from 42 to 43
Current best: David Carraher, Mathematica (280)

Mathematica - 280 247
No need to scale the target to the tile size.  The key is to match the average color for the target and for each tile.  Closest match wins.
In principle, it would be possible for the routine to choose the wrong match, but the test case suggests that this approach is surprisingly robust. The mean colors of target and selected tile were almost a perfect match: a distance of 0.00296966 away from the target mean color in RGB colorspace "cube" with edges of length 1.
Ungolfed 364 chars
f[{m_, tilesx_, tilesy_, targ_}] :=
 Module[{mosaic = Import[m],target = Import[targ], mDim = ImageDimensions[mosaic],

 (* find the average RGB colors for the target *)
 meanTargetPixelColor = Mean[Flatten[ImageData[target], 1]], m, t},
 m = ImagePartition[mosaic, {mDim[[1]]/tilesx, mDim[[2]]/tilesy}];

 (*Find the color distances between target mean rob and each mosaic tile
 Select the tile that best matches the average pixel color.*)
 t = SortBy[{#, EuclideanDistance[Mean[Flatten[ImageData[#], 1]],
 meanTargetPixelColor]} & /@ Flatten[m], Last][[1, 1]];
 Reverse[Position[m, t][[1]]]]

Example
Assuming that mosaic and targethold the respective filenames.
f[{mosaic, 59, 43, target}]

{48,18}

Golfed 247
f@{p_,x_,y_,s_}:=Module[{k=Flatten,i=Import,z=i@p,w,m,t,r},r=ImageDimensions@z;
w=Mean[k[ImageData[i@s],1]];m=ImagePartition[z,{r[[1]]/x,r[[2]]/y}];
Reverse[Position[m,SortBy[{#,EuclideanDistance[Mean[k[ImageData@#,1]],w]}&/@k@m,Last][[1,1]]][[1]]]]

in principal, the solution in the original post can return the wrong result as well. Even if he used the identical scaling algorithm as the original creator used, 2 different images can scale to the same image (pigeon hole principal). In this case, I guess you'd be unable to discern the difference as a human as well though, so the answer would effectively still be right.

Cruncher, Interesting point.  I was wondering about that.

I like this approach, and just want to comment generally on using a single average colour.  When I was placing the tiles to make the mosaic, I found using MSE greatly improved the patterns.  You actually see tiles chosen that match detail within the original image too.  There were other ideas I didn't explore, such as lab colour, gamma corrected scaling, SSIM, PSE etc.  But per-pixel was, generally, very important.

Python (360)
I seem to have broken PIL somehow, so load PPMs instead.  For this reason, I insist that the thumbnail is already scaled correctly to the size of the tile in the mosaic.  Its my first ever codegolf submission and I'm unsure the leeway I can expect in this regard.
import sys
I=int
R=range
O=open
M=map
N='\n'
A=ord
S=sum
# parse arguments
_,m,c,r,t=sys.argv
c=I(c)
r=I(r)
# load mosaic ppm
_,w,_,m=O(m).read().split(N,3)
w,h=M(I,w.split())
u=w/c
v=h/r
m=M(A,m)
# load thumbnail ppm
t=M(A,O(t).read().split(N,3)[3])
# make a list of the MSE of each tile in the mosaic, sort it, print the best
print sorted((S(S((p-q)**2 for p,q in zip(t[(y*u+x)*3:][:3],
m[((i*v+y)*w+j*u+x)*3:][:3])) for x in R(u) for y in R(v)),
j+1,i+1) for j in R(c) for i in R(r))[0][1:]

Its really slow because of the m[ofs*3:][:3] to get the channels for each pixel; that's creating a list of the remainder of the pixels, and then slicing just the first three... horrid performance :)

because you nerd-sniped me, Roy, and you know it ;)

Java (551) (523)
public class F{
    public static void main(String[]j)throws Exception{
        BufferedImage m=read(new File(j[0])),c;
        int x=parseInt(j[1]),a=parseInt(j[2]),
        w=m.getWidth()/x,h=m.getHeight()/a,
        b=0;
        c=new BufferedImage(w,h,1);
        c.getGraphics().drawImage(read(new File(j[3])).getScaledInstance(w,h,Image.SCALE_SMOOTH),0,0,null);
        for(int d=1<<30,y=x*a,e;--y>0;) {
            e=0;
            for(int z=w*h;z-->0;)
                for(int i=0,l=c.getRGB(z/h,z%h),k=m.getRGB(y/a*w+z/h,y%a*h+z%h);++i<3;l>>=8,k>>=8)
                    e+=pow((l&255)-(k&255),2);
            if(d>e){d=e;b=y;}
        }
        out.print(b/a+1+","+(b%a+1));
    }
}

Whitespace added to make it a bit clearer.
Based on Roy's, but using a MSE, which is I believe a much superior metric.  And less characters.
Java is really verbose :/
Imports etc are:
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import static javax.imageio.ImageIO.*;
import static java.lang.System.*;
import static java.lang.Math.*;
import static java.lang.Integer.parseInt;

Java (707)
My example code in golfed mode, removing spaces and using small variable names, without the needed imports:
public class F{public static void main(String[]j)throws Exception{BufferedImage m=read(new File(j[0]));int M=0xFF,x=parseInt(j[1]),a=parseInt(j[2]),w=m.getWidth()/x,h=m.getHeight()/a,b=0,n=0;BufferedImage u=read(new File(j[3])),c=new BufferedImage(w,h,1);((Graphics2D)c.getGraphics()).drawRenderedImage(u,getScaleInstance((w*1.0)/u.getWidth(),(h*1.0)/u.getHeight()));BigInteger d=null;for(;x-->0;)for(int y=a;y-->0;){BigInteger e=ZERO;for(int z=w;z-->0;)for(int v=h;v-->0;){int l=c.getRGB(z,v),k=m.getRGB(x*w+z,y*h+v);e=e.add(valueOf(abs(((l>>16)&M)-((k>>16)&M)))).add(valueOf(abs(((l>>8)&M)-((k>>8)&M)))).add(valueOf(abs((l&M)-(k&M))));}if(d==null||d.compareTo(e)>0){d=e;b=x+1;n=y+1;}}out.print(b+","+n);}}

The imports are:
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.math.BigInteger;
import static javax.imageio.ImageIO.*;
import static java.awt.geom.AffineTransform.*;
import static java.lang.System.*;
import static java.lang.Math.*;
import static java.lang.Integer.parseInt;
import static java.math.BigInteger.*;

Java is horrible for code golf, but at least it is below 1000.

source: Stack Exchange

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/3.0/

sort: votes


text:
Put together cut strips of paper to get original message
This question is from a programming challenge (not DARPA) which has ended. A sheet of paper consists of message, which has been shredded into vertical strips. Given the vertical strips and a dictionary of valid words, the goal is to put together the original message.
The vertical strips contain only one character from a line. The input to the program is the number of vertical strips (N), number of lines in the original message (K) and a string containing the characters in each vertical strip. Then the number of words in the dictionary and the list of valid words.
EXAMPLE INPUT
10
3
"MrM"
"ak "
"Gaa"
"oM "
" d "
"t 3"
" aP"
"nt "
"ont"
"ie "
15
1
2
3
4
5
AND
AM
AT
GO
IN
Main
Market
ON
PM
TO

OUTPUT
Go to Main
and Market
at 3 PM

Description of the input above
10 - number of vertical strips
3 - number of lines in the original message corresponds to number of characters in each string of the veritcal strips
{actual strings} - pay careful attention to spaces in strings
15 - number of words in the dictionary
{valid words}
I was able to create a map of characters -> count of each character, for each line from the vertical strips. Then parsing the dictionary and looking at the character map, you can recreate words in each line. Looks like finding the order of words is the difficult problem. What is the best approach to finding the correct message?

You'll need to specify an objective winning criterion, from your question you seem to be looking for fastest-algorithm, but I would suggest code-golf.

I would suggest to remove the codegolf tag if you don't want brute-force answers. Also you should format the input and output example using code block to align characters.

Dupe?

Python 3 - Trie and DFS
Trie is a tree shape data structure. If we build a trie from a collection of words, then each path from the root to a leaf node will represent a word from the collection.
To solve this problem, first we build a trie using the valid words. Suppose the original text has n rows and m columns, then we will have m strips to put together. We try to reconstruct the original text from left to right, column by column, using a recursive depth-first search. To perform branch elimination, we also maintain a list of heads on the trie, name it heads. Each head points to a node on the trie and point to the root at first. We will need n heads, each correspond to a row. Each time after a column(strip) is appended, heads[i] will be moved according to the character strip[i]. If we found any head that cannot be moved, then we know the column just appended is incorrect. After putting m columns, we get the original text.
I implemented this algorithm using Python. It is fast enough to solve a 40x80 case with 10000 valid word in instant.
I use this python 3 script to generate test cases. Run it with:
python3 make_script.py {dict path} {n rows} {n cols} > intput.txt

The following is a 40 x 80 case. The dictionary file can be found here, which has 10000 words.
80
40
c el efp e otl  desaiweseeme  jomp ebc g
synwds  irnsatseityl rkutpsiysei ssraat
gvmjewrell fclpadrll nbsvwiwteqdeniditba
uet criderndm eesih dalbrcra d iacnnoi e
lbipoeivedrwddivensne aeihrpaa eicangpni
 gontgtulvcbatdo glunsniiguoleu eigtbelh
xmsyyu ereio edvrttdonure tpselriniipnxs
ssdieop bgkg  wu  eloyr dllrhza t hic af
rttruminetnt rcu rasa ogosrywrnietvldgod
lpe aritour alolt yeomlpimmxryftenen  sn
cneregsc igodbsigeca r kbhiiisoss eagglp
crm nhdreh raokdtr rcfiotpsfgtjanotaaiaf
s pntenpnmv plemiaaxeeittgtg ncnaooaou a
srrganeu ut toaantetedccnr seiise eur ni
 xpndg psafl ooemlusof nba pauosina esnb
ge du  tbfe  spuoeuesen o s um ldsted  w
eto rs l nhuc caexr bsoptwcrrnaennrasary
e  maldneg nep nmaid isie ko ctedh necaa
esoeisi u ifran  rgirrts ntipuneccnvftrp
gui oeriwraisc og vsepharn latotts aenra
eenylorobneyrem nwtefrasdeoeet ot  osdsr
abia e i iwrcneaaiaeeu lie oihotgdicntdi
euugmjsdfcamazndei e yoagaserxatrultoaio
tamdfesgtitc xseuegs  fene thatfueo l ut
ocn sdrtn mai aerwmimoss te  oceorrit el
netbu wymsrfobelltemetrisioao uri  l ce
deaa ee e aadrgcoln cnto semroi  ofdnanu
aeaunrmvonirieaxapicnaioxaoromeviiuaeoou
 oaodtb hpretdarie n e recei etunsrsedal
ejht n jy ees tnr gsegr s  e jhb ayegup
ohids bi g iesiogs rytimtorrsab pnirwlc
ieuereaklieapeatlan sdeeg e lasedaob  be
rihbegaisvdtrprnatservaraco na imtcgplna
denrdnnelymisenimi gnfw bssalupcnansu et
itsrwnbeclwfmstasg craaim ei  atrifvpr
ubksogxernu auletinieo krte cgmltiliioir
atnhndcutigiasuir ntsaiauem usiireg idms
yniis ssle aisicsngqseazdifiertercaauvoc
ds prcatnoiaafsiopiratdrrmksnfidakr  gon
p ngaoolyeolg nep oae dnsnln srfcontsrve
boges massscgss arsobod ierseh rnivtagsp
nlstadhndnroieecntc slhoucbrcouo uohtiis
ltainnpif nfrn tinrdoi ninsanteu n   aeb
oun htoioaftupedsmowtmeatanyi sltnh ftto
a emgrasancass oelrefddy alacinsut n s
kgttnltednrmea t yhug welentn tu fsneeah
yia bilgwybnisgfrmidlh t rssnaiultgagk a
  iaeeorega sdbhc otadiresdagcipcuet rde
tygui artnsot le wtes etrracm pde oev e
cvrpsabemddamylpeiscdmktpnnolbsesardlwro
rnirmestiwntlrfresosedlvshydrsrrucnntr a
nans hinslmoxenfeolo cxeeneosgrphantiuyg
m dans llnrtlav ensptun acfaev s gtesfad
litl gonungirgk pioeutvinsstgintpsmbrdsu
altpjretooode rtnseeyepdrotllxric s rice
aikaunnskdoh agtnl cuegoacwhnsx esrurgg
ef drant  rsaaeymreleiiessmniesdoeeroeer
eereozurmoicueeegtcolbeioteodocrsnaeaatt
 h cre g  snsihssatlunisi odeelcpminoeba
oisstnirhpmnaybaertcnenhdnondsunaaprlipr
vetou egriemerpicacb  ygmiaw rrrocnisecm
ibs tara  neeiaqlbbtsgegcs sooeoeuel ten
blrkqaiacortqmn ien ylrrrnecieircs qeind
en s e ieu cnaiscikuirocnr hlnpfjooimohs
dctlehtr ntlgpddeoipmog elllrnncnkgcseeu
o  aaet henyaue mbntgeeselsws   mmawnwve
lns e xoorail yn  eesnee uctaud nrasenha
swydiecacaefolsenmttnsoer ohmahttpt radc
yvltaxin pgrauluktystkmot mrf aluuiepl
b sea usksoim hr idhtttd e owrn cnferevc
lstsibaocesfsmbejsdaellmepmbdedoffdbrtmq
axou nlnae ise gn esse  ihbstgsfmeteestf
yeaasra oopaeaildkiynteteidilnuenec vral
msylcdecsy  lkgr  icdkxrmie strle fei sz
 rdae gde al ngswsc soaru  tlsrtg durfne
 rrpodl i asg  essvuo aeaaheenaloe  geru
grus nbrls eqme ydioradhsoolmdiouoggnssv
 tfirotrkdnnnrtmwenan   abs cfcigscmpsed
 a soteiicdero nsaeuisrmisntau iirammlyi
anroiim tsiiaarrhoyaimdo oera dblogysmr

Solved:
lacerated deliberateness canvas gould scold sexually piggyback obey agrimony moe
seventy except fixates warble shrubbery instrumenting beveling convolute hairs j
tarring aptness homotopy misted unkindness frustrations marketing latitudinary h
superhumanly redbud bends atomics sprawls piggy oiling djakarta estop reads plat
insomnia delaware fruition auger hooded terramycin statuesqueness adjourns boca
brazed leghorn agnes seethed roentgen sen conjuring goa wrangled extremes hidden
ambuscade tribunals winced heap boxing fixates impostor rainstorm iberia billet
overturn protestingly pairings grieved protruded insulate ascertain tinkling c j
committees bock sat muncie drab lorelei honk fretfully block dense howell swishy
endowing annuls veins machining sandy reproducers neve flooding supportingly ye
sidings afterword thrived wrecks furman maintaining cone programs groaner mba ne
fractionally fisticuff ferromagnet wilsonian modifiable fathom accreditations ye
simulated grammars corporacies squads atalanta marriage ceq designates plexiglas
meyers propels apex ballooners impudently froze angst islamabad saud creases ku
baleful godmother scenes keep wheelings bystander kidnappings basilar caving get
experienced laryngeal mendacious devise animadvert coequal tithe surtout offer n
jaeger moments manuel instance systemwide ownerships plodding cracking legers mr
spits wallow girt extramarital administer petitioning berkeley writes ransoms b
discontinuity desegregate accretions cysteine thyroglobulin chomsky evans living
accosted speechless mixture bellowing lacerated adequately cautiousness products
endless comforters berenices fourteens insane odiousness nyu gambit yeasty lodge
lambda informative stressful dynamo forwent dynamites gentler doorkeep dutch keg
likeliest galatia fortiori hydride awakened could vandenberg wisdom phoenix axer
motivation spider epistemology shake rusher carbonizing strokers cordage meters
exposure bedim saints tritium distributed ranger indiscoverable interrogate ames
panther salem eschewing special oaths penumbra consigns winchester cons conrail
moneymake lome mob cottons ballooners smocks stressful sidewinder met refreshes
brood complexion straightforwardly patients separations wichita shrilly arose we
doldrum rarer winthrop magic chemically dancers angel outlining elf lawlessness
emboss county reagan unauthorized gauss suffixed tiresomeness cohn extravagant j
description fans staunch journalism prejudicial denture quixotic patrons briar h
override scott differentiators collection distribute folder superfluities pull b
fissured intercommunicating outputting managerial precedences conjuncted phloem
fiance honk nineteen coproduct monica sparks unconsciousness furious stagnate ma
durango fag effector notation highlands parceling magnetic reservoirs voting fay
baden end converge alva machining insurers mutiny battled quantities alberta ewe
relativeness propels formants configurable propos rubs diverge tampered swigging
toward cased reels actualities estop facings animadvert trigger golding fluke wu
mort meanness venturer dyadic abstinent phoenix resolve bangladesh acrobacy rsvp
quotas auburn crafty pacifism favorite grandiose buchenwald phelps leaded gauze

Code
def build_trie(words):
    root = {}
    for word in words:
        node = root
        for c in word:
            if c in node:
                node1 = node[c]
            else:
                node1 = node[c] = {}
            node = node1
    return root

def search_origins(root, strips):
    n_rows = len(strips[0])
    n_cols = len(strips)
    ordered = [None] * n_cols
    heads = [root] * n_rows
    used = set()

    def get_next(node, c):
        if c == ' ':
            return root
        return node.get(c, None)

    def search(col_id, heads):
        if col_id == n_cols:
            yield transpose(ordered)
            return
        for i in range(n_cols):
            if i in used:
                continue
            heads1 = [get_next(head, c) for c, head in zip(strips[i].lower(), heads)]
            if any(x is None for x in heads1):
                continue
            used.add(i)
            ordered[col_id] = strips[i]
            yield from search(col_id + 1, heads1)
            used.remove(i)
    yield from search(0, heads)

def transpose(cols):
    return '\n'.join(map(''.join, zip(*cols)))

def parse():
    m = int(input())
    n = int(input())
    strips = []
    for i in range(m):
        strip = input()
        if strip[0] == '"':
            strip = strip[1:1 + n]
        strips.append(strip)
    n_words = input()
    if n_words:
        words = [input() for _ in range(int(n_words))]
    else:
        dict_path = input()
        words = list(map(str.rstrip, open(dict_path)))
    return words, strips

def main():
    words, strips = parse()
    words = list(map(str.lower, words))
    # print(words, strips)
    root = build_trie(words)
    for i, result in enumerate(search_origins(root, strips)):
        print('#{}{}'.format(i, '-' * 80))
        print(result)
        # Uncomment next line if you want only one result
        # break

if __name__ == '__main__':
    main()

Groovy 311
i=(args[0]as File).readLines()
(a,b)=i[0..1]*.toShort()
j=2
s=[]
a.times{s<<i[j++]-'"'-'"'}
d=[]
i[j++].toLong().times{d<<i[j++].toLowerCase()}
f={(0..<b).collect{c->it.collect{it[c]}.join()}.join("\n")}
o=0;l=0
z=s.permutations().each{x=f(it);c=d.count{x.toLowerCase().contains(it)};if(c>l){l=c;o=x}}
print o

let's start the bidding and just go brute force; return the first result with the most matches against the dictionary by checking all permutations
Here is a shorter example helloworld.txt
5
2
"HW"
"eo"
"lr"
"ll"
"od"
2
hello
world

run as
% groovy destriper.groovy helloworld.txt


text:
Decipher a Code Stick
Introduction
You're an American spy during the heat of the Cold War and you've managed to intercept a Russian message. Immediately you recognise it as a code stick cipher and wrap it around a pencil. Looking at the paper on the pencil, you don't see anything. Then you try a bigger pencil, and you see it.
Challenge
You have to write a program that deciphers a code stick. As this is code golf, the shortest program wins.
You may use any English dictionaries for looking up words. Some examples of dictionaries include:

Querying a text file of words
Using an inbuilt OS dictionary
Querying an online dictionary (screen scraping etc.)
Using an external lib

All words MUST be valid English words
Your pencils
Each of your pencils has four equally sized faces and are infinitely long. You have five differently sized pencils:
Pencil 1: Shows 1 character on each face
Pencil 2: Shows 2 characters on each face
Pencil 3: Shows 4 characters on each face
Pencil 4: Shows 6 characters on each face
Pencil 5: Shows 8 characters on each face

All ciphers can be deciphered by placing the start of the paper at the top of the pencil and wrapping it down.
Examples
The following is an example of a cipher:
Hepoge slljghadso bvvbgh

This can be deciphered by wrapping it around Pencil 2:
Side 1 | Side 2 | Side 3 | Side 4
-------+--------+--------+-------
He     | po     | ge     |  s
ll     | jg     | ha     | ds
o      | bv     | vb     | gh

So now you have four combinations:
Hello , pojgbv, gehavb,  sdsgh

You can now perform a dictionary lookup and see that Hello is the only valid word. Therefore, Hello is the cracked cipher.
Note: Deciphered codes may have spaces in. Example: Hello World
Test cases
Ciphers can be inputted in any way apart from being hardcoded. The following are a few test cases. You will not be given the pencil size.
boasonespetrabbittonespongomezesray long
lsbvmii derfghthstthasinlomnrtk fg dndthugssawerpoloasefnxafqeormnaqwge padhndi mbavwgam
lipois lisptloopoolsisp lortfippinglthe asse rtedgoodcodeis the best  of enlymoolfangthe  leamingsoulsgodsingering
antidisebd sldkfdw sld sja dmddystablishjzkapxmjhavzlx dld slzbfmentariabahdjdlljagzlxbxlffnd ldnism is hdbsh spjalcpdhstd flcnda very cbd skd alsbfo kfvwfd xlconvolutehs ska ckw dlc fjzlxbckxd word  hs sla k dk skdnlcjcu dk

Any more test cases would be appreciated
Answers to the test cases

 1: astronomy
2: i think therefore i am
3: is lisp the code of the gods
4: antidisestablishmentarianism is a very convoluted word

Script to generate code stick ciphers:
import string, random, math

word = input('Word:\t')
n = int(input('Pencil:\t'))
pencil = int(-((4*(17*n-77))/((n**4)-(19*n**3)+(136*n**2)-(444*n)+566)))

alpha = string.ascii_lowercase+' '
cipher = ''

side = random.randint(1, 4)
sides =['','','','']

for j in range(len(sides)):
    if j+1 == side:
        sides[j] = word
        if len(word)%pencil != 0:
            sides[j] += ' '*(len(word)%pencil)
    else:
        for k in range(math.ceil(len(word)+(len(word)%pencil))):
              sides[j]+=random.choice(alpha)

for l in range(0, math.ceil(len(word)/pencil)*pencil, pencil):
    for m in sides:
        cipher += m[l:l+pencil]

print('Cipher:\t'+cipher)
print('Side:\t'+str(side))

Your second test case has at least four perfectly meaningful decryptions. This question is also incomplete in that it says "You can now perform a dictionary lookup" but doesn't provide a dictionary.

The first example uses Pencil 2, not Pencil 1.

The new third test case is wrong: the closest candidate decryption to the claimed one is is lisp the codeof the gods (sic). Also it's apparently not clear what the output should be. Am I correct to understand that it should be the (assumed unique) candidate decryption which doesn't contain any non-words? (See comment thread on David Carraher's answer).

Python - 219 178 172 175
First crack at it.  I'm sure there's room for improvement.
edit1: After suggestions, and copying words file to local file named 'w'
edit2: Fixed a bug where it wasn't using the right number of letters per side.  Added 3 chars :(
r=range
s=raw_input()
print[a for a in(''.join(s[m:m+n]for m in r(o*n,len(s),4*n))for o in r(4)for n in(1,2,4,6,8))if not set(a.lower().split())-set(map(str.strip,open('w')))]

you can save 1 char by removing the space after print, i.e. print[a...

Defining and using a synonym r=range should save a couple more characters. And similar to the morse code golf question it is shorter to load the dictionary where needed (same for raw_input), even though it might increase the computing time dramatically.

I don't think I can do the same thing with raw_input due to the fact that I use it in two places, and it loops many times.

This only works for single word ciphers, not with the other multi-word test cases

After making sure that my dictionary had all the words (it was missing "gods" and "antidisestablishmentarianism"), this script works properly for all 4 of the test cases.  Not sure why you thought it wasn't working, maybe you can explain?

I was wrong, there is definitely something wrong.  It's not multi-words, but I was not using the correct number of letters per side.  I'm fixing.

Alright, I fixed it.  There is a problem with the 3rd example that makes it indecipherable.

Prehaps instead of [a for a in (''.join... it can just be list(''.join... ?  And perhaps instead of if not set( it could be if(set...)-1 ?

Mathematica 270 230 251

This now requires that all parsed words be found in a dictionary.
f@q_:=
Module[{c=Characters@q,wd,u=DictionaryLookup},
j@d_:=Union[u@d,u[ToLowerCase@d],WordData@d];
Flatten@Select[Flatten[Table[
StringSplit[""<>Flatten@#]&/@Transpose@ArrayReshape[c,{Round[Length@c/(4 m)],4,m},""],{m,{1,2,4,6,8}}],1],!MemberQ[j/@#,{}]&]]

Test Cases
f["boasonespetrabbittonespongomezesray long"]
f["Hepoge slljghadso bvvbgh"]
f["lsbvmii derfghthstthasinlomnrtk fg dndthugssawerpoloasefnxafqeormnaqwge padhndi mbavwgam"]

{"astronomy"}
{"Hello"}
{"i", "think", "therefore", "i", "am"}

I think you're probably supposed to filter the possibilities to only the ones which don't contain non-words rather than to the ones which do contain words, but the spec could certainly be clearer.

Peter T, Yes, but the non-word may actually be a legitimate word that the dictionary for one reason or another does not recognize. In such a case, it's better to return the words that are identified as valid.

license: Creative Commons - Attribution Share-Alike - https://creativecommons.org/licenses/by-sa/4.0/


text:
What's wrong with public variables?
Code Bots
I hate private and protected variables.  I just want to access anything and everything!
If you are like me, then this challenge is for you!
Write a bot that works together in harmony with other bots makes other bots do what you want.  You are a programmer, and you know how things are supposed to work.  Your job is to convert as many other bots to your ways as possible.
The Code
You will have 24 lines of code to write your bot.  Each turn, every bot will execute 1 line sequentially.
Each bot stores 5 variables A through E.  A and B are for personal use, C stores the next line to execute, D stores the current direction, and E is a random number.  The variables start at 0, except for D, which will start at a random value.  All variables have only store 0-23.  Numbers larger or smaller will be modulated by 24.
In this post, I will use opponent to be the adjacent bot you are facing
Each line must contain one of the following 5 commands:

Flag does nothing.  Except it's how you win
Move moves your bot in the Dth direction.  If a bot already occupies the space, no move will happen
Copy Var1 Var2 copies the contents of Var1 into Var2
If Condition Line1 Line2 If Condition is true, executes Line1, else Line2
Block Var1 blocks the next write on a variable

A variable can be used as follows:
#Var will use the variable as a line number.  If A is 17, Copy #8 #A will copy the contents of line 8 onto line 17.
*Var will use the variable of your opponent.  Copy 5 *C will set the opponent's C variable to 5
Var+Var will add the two variables.  Copy D+1 D will rotate the bot to the right
When D is used as a direction, [North, East, South, West][D%4] will be used
These modifiers can be chained: Copy *#*C #9 will copy the next line your opponent will execute into your own code on line 9.  **D refers to your opponent's opponent's D variable.
A Condition will be evaluated as follows:

If Var:

If Var is A through C, it will return true if Var is nonzero, else false.
If Var is D, it will return true if there is a bot in the Dth direction, else false
If Var is E, it will return true if E is odd, else false
If Var is a line, it will return true if it is a Flag line

If Var1=Var2:

Returns true if both are A-E, and equal the same number
Returns true if both are lines, and the line type is equal

If Var1==Var2:

Returns true if both are A-E, and equal the same number
Returns true if both are lines, and are identical (Flags from different bots will not be equal)

50 bots of each type will be placed in a toroidal world in the following pattern:
B...B...B...B...
..B...B...B...B.
B...B...B...B...
..B...B...B...B.

After each game of 5,000 turns, the flags on each bot will be counted.  You get a point if a bot has more of your flag than any other type of flag.  If the case of a tie between N bots, no points are given.
There will be 10 games, and scores will be accumulated at the end.
Side Notes
End of line comments are allowed, and are denoted with //
Attempting to do something that doesn't make sense, such as adding to a line will do nothing
Attempting to do something on a non-existent bot will do nothing
Infinite recursion on an If will end with no line being executed
If does not change the value of C
A Block doesn't expire until somebody attempts to write to it
Multiple variables and lines can be blocked at once
Blocking a variable multiple times will block multiple times as long as the second block statement is on a different line of code than your first
Spaces are only allowed between arguments (and after the command)
If a bot is shorter than 24 lines, Flag will be the rest of the lines.
Sample Program
Copy 2 C        //Skip to the If line
Flag            //Where I'm storing my flag
Move            //Move in the D'th direction
If D #5 #2      //If there's a bot, copy code, otherwise, move!
Copy #1 *#E     //Copy my flag onto a random spot in my bot's code
Copy 2 C        //Skip back to the If line

The program will be run by my Python controller here.
The Java controller is here  It is fast and looks much better than the python one.
Scoreboard:

6837 $Copy
3355 Lockheed
1695 MindControl
967  Byzantine
959  AttackOrElse
743  Cadmyllion
367  Influenza
251  TheCommonCold
226  Magus
137 HideBlockAttack
129 RowBot
123 FastMoveCloneDodge
112 FastForwardClone
96  QuickFreeze
71  RepairAndProtect
96  SuperFreeze
93  RovingVirus
80  ForwardClone
77  FreezeTag
68  Palimpseste
62  BlockFreezeAttack
51  RushAttackDodge
46  Blocker
40  TurretMaker
37  Copycat
37  Kamikaze
35  FlagInjector
33   RandomCopier
31  Insidious
29  HappyAsAClam
25  NanoVirus
21  Nullifier
19  Nanoviris
17  BoringCopybot
16  Movebot
14  Flagbot
13  Neutralizer
12  Cancer
9   DNAbot
9   Parasite
8   MetaInsidious
8   Rebranding
8   AdaptiveBot
8   ReproducingBot
8   KungFuBot
5   QuickFreezerbot
4   Attacker

I'll be all about this once the Java is available for me to test.

I'm assuming you have never played Core war. http://en.wikipedia.org/wiki/Core_War

I haven't played it, but I read up quite a bit on it while writing this challenge.

I have a patch for the Python controller and tried to push it back to you on github... but I don't have permissions / don't really know git. Patch replaces all "16"s with "num_lines" to allow write/jump access to last 8 instructions; also removes "max_flag_count = 0" from the tie condition in declare_flags(), which sometimes awarded a two-way tie to a third bot.

I literally just found the %16 before this comment.  Thank you for the other fix.

You say that *Var and **D refer to the enemies variable. Which one is true?

Is E a new random number at every turn or is it generated only once?

Every turn @plannapus

Shouldn't If D #5 #3 be If D #5 #2  in your example bot then?

I'm unable to run the Script. I tried it with both 2.7 (name '_' is not defined) and 3 (invalid syntax).

Sorry.  I accidentally committed a version with a bad character.  Should work on 2.7

@Manu, **D refers to the D value of your enemies enemy.

Did I miss it or is nowhere stated that C (the "instruction pointer") is increased by every instruction except IF and a COPY … C?

@Bergi C is still incremented after an IF or a COPY ... C.

Any ETA on when the next battle round is going to be run? No rush at all. I'm just curious. Thanks.

@COTO Next battle round has been run.

Thanks, Nathan. A quick note: the bot .txt files in the github master are out of date.

Um... @NathanMerrill I'm having a hard time figuring the Java controller out. Where's the JAR you refer to in the commit?

Oh, I also tried doing it myself with jar cvfm CB.jar META-INF/MANIFEST.MF codebots/*. I ran the resulting JAR and got a NullPointerException at codebots.CodeBots.initBots(CodeBots.java:74) at  codebots.CodeBotsGUI.StartGUI.<init> StartGUI.java:8) at codebots.CodeBots.main(CodeBots.java:67).

@SohamChowdhury I forgot to add the .jar, sorry (I removed the jar from the gitignore, but never actually added it).

The variables start at 0, except for D, which will start at a random value. wouldn't the random number be a random number too? Edit: wait this is a really old challenge I really need to check dates

Flagbot
Flag

Why bother doing anything when other bots are going to be nice enough to give me their code?

Freeze Tag
Move
If D #3 #2
Copy 23 C
Copy 3 C
Copy #23 *#*C
Copy #21 *#*C+1
Copy #22 *#*C+2
Copy #21 *#*C+3
Copy #22 *#*C+4
Copy #21 *#*C+5
Copy #22 *#*C+6
Copy #21 *#*C+7
Copy #22 *#*C+8
Copy #21 *#*C+9
Copy #22 *#*C+10
Copy #21 *#*C+11
Copy #22 *#*C+12
Copy #21 *#*C+13
Copy #22 *#*C+14
Copy D+1 D
Copy 0 C
Flag
Flag
Copy C+23 C

Trap opponent in a loop, fill him with flags, move on to next opponent.

Copy C+23 C This has to be the most malicious line of code xD.

I'm interested. This may be improvable. Rather than fill them with flags, can you put a loop in them that fills themselves with flags? Or would that not count as your flags?

That's a neat and viable idea, but more complicated. You should write a bot that uses it :)

Do you know the answer to the last question? Or would that not count as your flags?. Because if they don't count as your own flags, it's definitely not a good solution

@Cruncher you could give them one of your flags and make them copy it, which would count as one of yours.

I like that! I may actually try this later. No time to implement atm.
This should mean that your bot spends less time infecting its targets, so it can find more!

@Cruncher posting a bot with your idea now :p

Parasite
Why kill other bots? This bot looks through opponent's code and replaces only the flags.
Copy 1 A
Copy E D
Block #A
If *#A #C+3 #C
Copy A+A+A+A+A A
Copy C+19 C
Copy #C+4 *#A
Flag
Copy 1 A
Copy E D
Block #A
If *#A #C+3 #C
Copy A+A+A+A+A A
Copy C+19 C
Copy #C+4 *#A
Flag
Copy 1 A
Copy E D
Block #A
If *#A #C+3 #C
Copy A+A+A+A+A A
Copy C+19 C
Copy #C+4 *#A
Flag

$Copy
This bot uses much of the same techniques as COTO's Lockheed, so I will shamelessly borrow and enhance.
This exploits a C vulnerability to break blocks and even reverses the neutralizer. It is also written in absolutes because of this. I think this might break if the C shift is reinstated, but as long as the shift is constant, it can be rewritten to combat it.
For whatever reason, the lack of loop at the end made this bot super good.
Block #C+A
If D #7 #13        //If [enemy] Copy 0 ELSE block
If D #8 #0         //If [enemy] Freeze 0 ELSE block
If D #9 #6         //If [enemy] FreezeCheck ELSE Inc
Move
Copy 0 C
Copy A+5 A          //Inc
Copy 23 *C          //Copy 0
Copy #10 *#*C+23    //FreezeAttack
If *#*C==#10 #11 #5 //FreezeCheck: If [frozen] GOTO Copy Attack ELSE GOTO [1]
Copy C+23 C         //FREEZE
Copy 13 C           //GOTO Copy Attack
Copy 15 C           //Loop Copy Attack
Block #C+A
Copy D+3 *D             //Copy Attack: Spin Enemy
Copy 0 *B               //Set enemy counter (a la COTO)
Copy #*B+0 *#*C+*B+1    //Copy my lines
Copy #*B+1 *#*C+*B+2    //Copy my lines
Copy #*B+2 *#*C+*B+3    //Copy my lines
Copy *B+3 *B            //Inc counter
If *B==0 #19 #12        //Loop check
Copy D+1 D              //Turn myself

I shall bow to your improved design and face you again in the Bots v. 3 competition. ;)

I honestly believe this was a group effort on everyone's part. This wouldn't exist if it weren't for several bots out there to model off of. Interestingly, the addition of this bot completely reorganized the scoreboard as bots that depended on blocking were broken while others that depended on flag-replacement ascended.

Can someone summarize, somewhere, the actual behavior of Block and how this bot and Lockheed take advantage of it?

Each line can accrue blocks, as described by HappyAsAClam. Most importantly, it does not stack for blocks called with the same C values. Thus, a block can be stacked when called from an If statement, which is the exploit being used here. $Copy breaks blocks (like the clam) by executing Copy on the same line over and over until successful, which gives it an advantage over Lockheed.

Lockheed
My third (and likely final) submission to this particular bot war: the Lockheed Reactor, or "Lockheed" for short.
Block #C+A
If D #C+7 #C+1
Block #C+A
Move
Copy A+5 A
If A==0 #C+12 #C+21
Copy C+17 C
Copy D+3 *D
Copy C+9 C
Copy C+21 C
Copy C+23 C
Copy #C+23 *#*C+2
Copy #C+22 *#*C+1
Copy 0 *A
Copy #*A+C+9 *#*C+*A+1
Copy *A+1 *A
If *A==0 #C+15 #C+17
Copy D+1 D
Copy C+5 C

Special thanks goes to @Wasmoo, who shared his discovery of the "'Blocking a variable multiple times will block multiple times as long as the second block statement is on a different line of code than your first.' simply isn't true" exploit. I make extensive use of it.
Also, thanks goes to Nathan Merill for administrating the competition and for publishing the simulator. The simulator is utterly invaluable in tuning bots. I wouldn't have believed it if I hadn't simulated it with my own eyes, but the addition or removal of the most conceptually minor bot feature can mean the difference between great success and abject failure. I'm torn as to whether that's a good thing or not.

Blocking a variable multiple times does fail.  However, it only fails to block if: You are executing the same line (an If pointing to that line will not fail), You are blocking the same value (A single line can block lines 1-24 with an incrementing variable), and the block hasn't already been released (somebody tried to modify that variable)

I contest the statement in the OP because the block instruction is keyed to the IP, not the block statement. Thus a single block statement can institute as many as 24 separate blocks on all instructions. I submit that the clause in the OP stating "as long as the second block statement is on a different line of code than your first" should be amended to "as long as a block for pair (C,<block target>) is not already in effect". That is, the line the block statement is on has no relevance to stacking, except that if the block is executed directly, C = block instruction address.

This bot is amazing! It combines all of the best concepts into one. It protects itself until it finds an enemy, then it double-freezes the enemy and uploads a copy of itself onto the target before setting it free in the opposite direction. In simulations, I saw one of its copies repair an original that had been damaged. WOW! Great job, COTO!

Attack Or Else
Seeing as defensive robots like Byzantine were doing so well, I decided to make a defensive robot as well.
This has two sets of patterns, depending on whether or not the enemy is present.

If the enemy is not present, it blocks its lines for 3 turns and then moves.
If the enemy is present, it alternates between copying its flag and copying code that will cause the enemy to copy that flag (a weak replicator) it copies its flag
At the end of the loop, it changes to a random direction and continues
Most aspects of its code is duplicated

More testing showed a few important concepts:

"Turn random" performed dramatically better than "Turn right" (+2700 over alternative)
Block increment of A+7 shown to be more effective than any other increment (+200 over next best)
"Direct attack" shown to be better than "Weak replicator" (+900 over alternative)
Defense of "3-1-2-1" better than other combinations (+200 over next best)
Duplicated attack, block, and loop code improves its score (+300 over non-duplicated)
Duplicated block increment does not improve its score (+400 over duplicated)

Observing the simulation graphically via the Java UI helped a lot. Thank you!
Below is the new and improved code. I don't think I can do anything more.
Block #C+A          //Dynamic block for If statements
If D #20 #0
If D #19 #8
If D #20 #23
If D #19 #0
If D #20 #8
If D #19 #23
Copy A+7 A          //Increment dynamic block
Block #C+A          //Dynamic block for If statements
If D #19 #8
If D #20 #0
If D #19 #8
If D #20 #23
If D #19 #8
If D #20 #0
If D #19 #23
Copy E D            //Turn Random
Copy 23 C           //Loop to beginning
Copy 23 C           //Loop to beginning
Copy #22 *#*C+1     //Copy my flag to the enemy's next
Copy #21 *#*C+1     //Copy my flag to the enemy's next
Flag
Flag
Move

This bot did seriously awesome.  And you are welcome for the GUI.

I've updated it to include a second loop, which dramatically improved its performance. I also noticed that blocking in Java is based on the C that blocked it. Because this bot has a revolving Block based on C, it will accrue multiple blocks on each of its commands. That makes this bot extra defensive.

My understanding is that only one block per originating instruction could be established, hence your code above could only establish a single block on any instruction (and it would take a full 24*17 turns to establish a single block on every instruction).
If my understanding is wrong, then the language "Blocking a variable multiple times will block multiple times as long as the second block statement is on a different line of code than your first." in the OP needs to be amended, because this statement is (frankly) false if Wasmoo's code is able to establish multiple blocks on any instruction.

@COTO: The Java simulator adds one block per If line to a list, keying on the C variable that called it. So with the 1 Block and 9 If's that execute the Block statement, the bot can get up to 10 Blocks for each line, (taking at least 241010 turns) Perhaps the OP did not convey the simulation correctly.

I've updated the code again to reflect further improving iterations while keeping the core concept. I thought this would be better than flooding the forum with each iteration, such as the switch from Weak Replication to Direct Attack, and Non-Duplicated to Duplicated. If you'd like me to repost my original, I can do so.

OK. Thanks Wasmoo. That's a bug as far as I'm concerned, but since it's pretty much entrenched at this point, I'll amend my existing bots to exploit it. I've also got one more bot design in mind.
You'll kill us all with all the simulating and optimizing you're doing. :P

On second thought, I'll leave the existing bots be. They are what they are, warts and all. ;)

Super Freeze
Move                    // start moving!
Block #E
If D #12 #0             // 8 turns of attack or move
If D #12 #0
If D #12 #0
If D #12 #0
If D #12 #0
If D #12 #0
If D #12 #0
If D #12 #0
Copy D+1 D              // change direction
Copy 0 C                // start over
If *#*C==#23 #13 #14    // if opponent is frozen, give them a flag, otherwise freeze them
Copy #C+13 *#E          // give a flag to opponent
Copy #23 *#*C           // copy freeze line to opponent
Flag                    // 8 flags, one per If above
Flag
Flag
Flag
Flag
Flag
Flag
Flag
Copy C+23 C             // this line freezes any bot that executes it

This bot keeps trying to freeze the bot in front of it until it works, then writes a bunch of flags to random lines, and after 8 turns of that it rotates and moves on to another opponent.

Row Bot
Move
If D #7 #0
If D #7 #0
If D #7 #0
If D #7 #0
If D #7 #0
Copy 0 C
If D=*D #9 #8     //If they point in a different direction
Copy *D D           //fix that
If #A==*#A #10 #11  //Did we copy line A already?
Copy A+1 A          //If so, A++
Copy #A *#A         //else, copy it!

Will move until it finds a robot.
Will set that robot in the same direction as itself.
Will then copy its code into the robot.
This should make a row of "Row Bot" Robots.  :)

There are two (easily fixable) problems.  First, the If statements must be capitalized.  Second, there should not be spaces on either side of the =, like D=*D.

This is an awesome idea.

Without a flag you aren't going to win.

@PaŭloEbermann bots are filled with flags up to 24 lines, so this bot has 12 implicit flags at the end.

Byzantine
A highly defensive bot that institutes multiple blocks on its flags and most sensitive instructions, including meta-blocks (i.e. blocks on critical block instructions).
It also moves constantly in unpredictable ways, and plants flags in numerous locations on opponents on a best-effort basis.
Block #A
Block #A+1
Block #A+2
Copy E D
Move
Block #A+3
Block #A+4
Move
Copy #22 *#*C+1
Copy E D
Move
Block #A+5
Block #A+6
Block #A+7
Move
Copy #22 *#23
Block #A+8
Block #A+9
Block #A+10
Copy #22 *#2
Copy A+14 A
Move
Flag
Copy #22 *#*C+12

Not sure how it will perform, since I can't simulate. But we'll give it a shot. ;)

Disclaimer
I wrote this before being kindly informed by PhiNotPi that conditional logic is cost-free. However, I've decided to leave it in since one can never have too many bots.

this bot is winning!

Meta Insidious
This bot freezes and then converts opponents into less efficient versions of Sparr's Insidious, which in their turn, will turn opponents into bots that spam flags for me. This is likely the most complex bot I've written and I thus expect it to do terrible, there was no space for blocking and only one flag fitted in the code. Turning a bot into an insidious clone also takes too long.
The biggest challenge was writing the code for the insidious clones in such a way that it works regardless of its position in the bot. The freeze gets removed when I paste the second to last code exactly where the freeze is located, this starts up the opponent just in time.
If D #2 #1
Copy 23 C
Copy #8 *#*C // freeze the opponent
Copy 9 A
Copy #A *#A+*C // copy the next line at the appropriate  line
Copy A+1 A
If A==0 #7 #23
Copy 23 C
Copy C+23 C
If D #C+2 #C+23 // the code for the Insidious clone starts here
Copy C+21 C
Copy C+2 C
If D #C+6 #C+22
If D #C+5 #C+22
If D #C+4 #C+20
If D #C+3 #C+19
If D #C+2 #C+18
Copy E D
Copy #C+7 *#*C
Flag
Copy C+3 A
Copy #C+22 #A
Copy A+1 A
Copy C+21 C // And ends here

That is a clever idea. However, I don't see any Move commands. Does that mean neither your bot nor your spam bot will move?

The Insidious clones might move depending on what's in the bots original code, due to limited space quite q bit of functionality had to be thrown away to make this even possible with 24 lines. It was more of a mental excercise than anything else really.

Cadmyllion
"I just entered a bot in the battle royale," I say. "It moves every few turns to prevent attacks by slower bots."
"What do you mean by slower bots?" PhiNotPi asks.
"Bots that are stuck evaluating long chains of conditional logic," I reply.
"'If' statements that redirect to other statements---including other 'if' statements---are all executed on the same turn," says PhiNotPi.
"Sweet massacred rules of assembly code!" I cry. "Who came up with that idea?"
...and thus is the story of how Cadmyllion came about.
Cadmyllion: the bot that happily exploits the surreal ability to evaluate infinitely many conditional expressions in a single instruction... by making pretty much every thing it does conditional.
Code
If D #15 #19
Move
If D #16 #20
Copy D+3 D
Block #A
If D #15 #20
Copy A+1 A
If D #16 #1
Move
If D #15 #19
If D #16 #4
Copy E D
Block #A+12
Copy C+10 C
Flag
If *#0==#14 #17 #21
If *#0==#14 #18 #21
If *#*C+1==#14 #18 #22
Copy *C+11 *C
Block #A+6
Block #A+18
Copy #14 *#0
Copy #23 *#*C+1
Flag

Repair and Protect
This bot repairs its own code, while protecting the newly repaired lines.
If #A==#A+16 #C+1 #C
Copy #A #A+8
Block #A+8
Copy A+1 A
Copy E D
Move
Copy #C+1 *#*C
Flag
If #A==#A+16 #C+1 #C
Copy #A #A+8
Block #A+8
Copy A+1 A
Copy E D
Move
Copy #C+1 *#*C
Flag
If #A==#A+16 #C+1 #C
Copy #A #A+8
Block #A+8
Copy A+1 A
Copy E D
Move
Copy #C+1 *#*C
Flag

Explanation:
The initial value of A is 0, and the lines are numbered 0-23.  If the If statement is executed and is false, it does attempt the execute the same line again.  The controller does not allow a bot to execute the same line twice, so the turn is ended and C is incremented to 1.
The next line, Copy #A #A+8 is actually performed regardless of the value of the If statement.  The difference is that it is executed twice if true and once if false.  If the line #A+8 is blocked (which happens eventually), then performing it twice with actually copy, while performing it once will only unblock it.  Then, the newly copied line is blocked to preserve it.

I'm trying to understand all of you guys bots but I'm stuck. What are the initial value of A? Isn't it 0? If so then your first line compare line 0 to line 16, but as I understood from the OP example bot, the first line is line 1, isn't it? Additionaly, still in your first line, #C refers to this very line, so does it mean that if the If statement return false you're stuck in an endless loop?

@plannapus I added some explanation.

Insidious
Move
If D #4 #0
If D #4 #0
Copy 0 C
Copy 4 C
If D #12 #11
If D #12 #11
If D #12 #11
If D #12 #11
If D #12 #11
Copy D+1 D
If D #4 #3
Copy #C+8 *#*C
Flag
Copy C A
Copy #C+22 #A
Copy A+23 A
Copy C+21 C

Inspired by @Cruncher, this bot infects other bots with a small block of code, filling the other bot with this bot's flags. Those bots are then sitting ducks for further attack, but they will be mostly full of my flags when they get re-infected by someone else.
Edit: thanks to @PhiNotPi for golf assistance, @overactor for efficiency advice

Congrats on hitting 2k!

Neutralizer
This bot makes its victim rewrite its entire program, making it worth 0 points. Once the virus is in place, it moves on. This is a scorched earth approach to victory.
If D #C+2 #C+3          // A: If [enemy exists] B else C
Copy C+22 C             // GOTO A
If *#*C==#7 #C+4 #C+5   // B: If [enemy was neutralized] D else E
Move                    // C: Move
Copy E D                // D: Turn Randomly
Copy #7 *#*C            // E: Neutralize enemy
Copy C+1 C              // Skip the next line
Copy #C #C+1            // Neutralizing Code [Copy this line to next line]

The comparison *#*C==#7 doesn't seems to adjust for the opponent's shift correctly, but the bot does eventually move on.

Copy C+1 C is all that is needed to skip a single line.

'Skip the next line' means your bot is going to spend 16 turns executing flag instructions before continue. You might want to Copy 23 C there instead, to jump back to the first line.

'Skip the next line' will only happen if 'GOTO A' was overwritten.
There are other ways I can make this bot more offensive and defensive, such as repeating 'A', duplicating the code, and blocking 'GOTO A'. However, if this bot is hit at all, it's pretty much dead anyway.

MindControl
I guess it's never too late?
Block #C+D
If D #2 #0        // Scan for enemy
If *#E==#E #0 #5  // Attack if necessary
Copy D+5 D        // Turn
Copy 22+1 C       // Repeat
Copy 4+1 C        // ATTACK:
Copy #22+1 *#*C   //   Freeze
Copy #17 *#17     //   Upload the DOWNLOADER
Copy #18 *#18     //
Copy #21 *#19     //
Copy D+2 *D       //   FACE ME!!
Copy 17 *C        //   Start download
If E #0 #13
If E #0 #13
Copy 22+1 C
Flag
Flag
Copy *#B+20 #B+20         // DOWNLOADER
If *#B+20==#B+20 *#20 #19 //
Copy 22+1 C               //
Copy 1+B B                //
Copy 16 C                 //
Flag
Copy 23+C C        // FREEZE

MindControl comes from my idea that it would take some considerable time to copy my whole program to the opponent, during which my bot is vulnerable to attacks from other directions. So why not make the opponent copy my program while I scan for enemies?
Once it finds an enemy, MindControl immediately freezes the enemy to prevent escape. Then it uploads the downloader to the opponent and let the victim download MindControl's program itself. The downloader exploit the fact that few bots uses B and will loop until it downloads all 24 lines. When the downloader rewrites #19 from Copy 16 C to Copy 23 C, it signifies the victim have downloaded all lines and will go on to reboot itself.
The first versions of my bot does not include Blocks. And it was so vulnerable that almost any change is crippling. So I decided to add Blocks based on Wasmoo's $Copy (which is based on COTO's Lockheed). The downside I found is that it is difficult for the original to correct mistakes in the copies. But this is far from crippling and the score increased significantly so I kept the Blocks.
UPDATES
I improved the downloader to keep trying to download until a successful rewrite to circumvent blocks. It does mean it takes one more turn to upload the downloader but my score doubled after this change!! Can't argue with numbers.

Another update. As you may have noticed, MindControl decides whether to attack target by comparing a random line between itself and its target. If they match, MindControl just assumes the target is already infected and leave it alone. (Side note: I used to use a static line for comparison but that gives lots of false positives and negatives) Turns out that gives a lot of false negatives. So I decided to exploit == and make some trivial changes like C+23 to 23+C. The program is functionally identical but different in the eyes of ==. Now that MindControl has no line that is identical to any line in any other bot, it will 100% hit any untouched bot. Again, score increased significantly.

Improved the Downloader again. It now runs on a shorter loop. (which seems to have a large correlation with my score)

Improved Downloader yet again. Uses original bot's code so it uploads faster. Also added 2 random blocks which seems to improve score

It's never too late!

I am considering renaming to BrainWash...

Or BunkerBuster after watching the downloader bust through HappyAsAClam the bunker

I had thought of trying this idea of uploading a downloader first, but I couldn't get it as small as you did. Great job!
I also love your use of D as the roving block delta; it saves a command and speeds up your design.
I'm amazed that a bot without a 'Move' command would work so well. Simulations show bots tend to clump, but I didn't know that would be a winning strategy.
And I agree, there is something uniquely satisfying about breaking the clam.

@Wasmoo Obviously the downloader design requires the bot to stay stationary and it does make bots clump. I like to think of it as roots of a tree that reach out and assimilate other bots in order to grow. But I guess agility is why $Copy and Lockheed beat me.

Happy As A Clam
This is an exercise in blocking. It performed remarkably well until $Copy came around.
The clam has 22 block commands. Because A is shifted every loop, they will reference different lines each time through the loop. This allows each command to stack blocks on every other line, maxing out at 22 blocks per line. Thus, to break the fully armored clam, one would need to write to a line 22 times.
For example, #10 will be protected each time through the loop by the following lines:

Loop 0, A=0 #10 protected by line 7 (7+0+3=10)
Loop 1, A=7 #10 protected by line 0 (0+7+3=10)
Loop 2, A=14 #10 protected by line 17 (17+14+3=34=10)
Loop 3, A=21 #10 protected by line 10 (10+21+3=34=10)

So after Line 10 of Loop 3, #10 has been blocked 4 times, requiring 4 writes to #10 to break the blocks, with a 5th one to actually overwrite the line.
Note that blocks are keyed by their C value and will not stack if the protected line was already blocked by the same C value. So after 22 blocks are established for each line, the blocks will no longer stack.
Block #C+A+3
Block #C+A+3
Block #C+A+3
Block #C+A+3
Block #C+A+3
Block #C+A+3
Block #C+A+3
Block #C+A+3
Block #C+A+3
Block #C+A+3
Block #C+A+3
Block #C+A+3
Block #C+A+3
Block #C+A+3
Block #C+A+3
Block #C+A+3
Block #C+A+3
Block #C+A+3
Block #C+A+3
Block #C+A+3
Block #C+A+3
Block #C+A+3
Copy A+7 A
Flag

Attacker
Copy #E *#*C
Copy #E *#*C
Copy #E *#*C
Copy #E *#*C
Copy #E *#*C
Copy #E *#*C
Copy #E *#*C
Copy #E *#*C
Copy #E *#*C
Copy #E *#*C
Copy #E *#*C
Copy #E *#*C
Copy #E *#*C
Copy #E *#*C
Copy #E *#*C
Copy #E *#*C
Copy #E *#*C
Copy #E *#*C
Copy #E *#*C
Copy #E *#*C
Copy #E *#*C
Copy #E *#*C
Copy #E *#*C
Flag

Movebot
Move
Copy 23 C
Flag

Like Flagbot, but move around while accepting gifts of code to go with all of our flags.

Magus
Magus is a simple attempt at a self-propagating virus. It attempts to copy itself into the programs of other bots. (Edited to remove negative numbers, fix condition, trim lines.)
Block #A
Copy #A *#A
Copy A+1 A
If A #0 #4
Copy 0 *C
Flag
Move
Copy 0 C

Negative values are not allowed.  Please use 23 for B

Please use 23, not 25.

Unless I'm misunderstanding, that would cause it to not block or copy lines 23 or 24 (note: it's changed slightly from the first revision, A is incremented by 1, not B)

+0 = 24 +1 = 25, -1 = 23.  If you want it to be -1, it should be 23.

That's how it was before, because I thought you could only compare with 0 (missed the '=' part somehow, I blame skimming), but it's changed now so A starts at 1 and ends at 25. Just imagine line 3 as for (int i = 1; i < 25; i++)...

@Isaac A will never be 25, nor will there be a line 25. 0-23 is the range of lines.

@NathanMerrill Ugh, you're right. Just saw the part that said variables only store numbers 0-23. I'm going to fix it, then re-read your post meticulously.

@NathanMerrill I don't have the reputation needed to comment on your post, but you may want to note that the line numbers are 0-indexed (it wasn't immediately obvious, at least to me) and change the sample code's if statement to If D #4 #2. I think that's how I got confused.

Reproducing bot
This bot tries to freeze his opponent and then copy his entire code into that bot before restarting the other bot. This should also work (mostly) if the opponent uses blocking, though that does make it all even slower than it already is.
If D #23 #22
Copy 23 C
Copy #18 *#*C
Copy #18 *#*C+1
Copy #18 *#*C
Copy #18 *#0
Copy #18 *#0
Copy 0 *C
Copy 0 *C
Copy 1 A
Copy #A *#*A
If D #12 #14
Copy A+1 A
Copy 9 C
Copy 23 C
Flag
Flag
Flag
Copy C+23 C
Copy D+1 D
Flag
If *#*C==#*C #19 #13
Move
If *#*C+1==#*C+1 #21 #13

No spaces in the condition

@NathanMerrill gotcha

Blocker
Copy A+1 A
Block #A
Copy C+22 C

Copycat
If D #4 #3
Move
Copy 23 C
Copy *#*C #1
Copy #23 *#E

DNAbot
Flag
Copy 8 D
Copy 16 B
If #D==#B #C+2 #C+3
Block #A
Copy #D #A
If D #7 #15
Copy #23 *#*C
Copy A+1 A
Copy B+1 B
Copy D+1 D
If #D==#B #C+2 #C+3
Block #A
Copy #D #A
If D #7 #15
Move
Copy A+1 A
Copy B+1 B
Copy D+1 D
If #D==#B #C+2 #C+3
Block #A
Copy #D #A
If D #7 #15
Flag

This bot repairs its own code while moving and attacking.

Block, Freeze, Attack
Block #A        // start block loop
Copy A+1 A      // loop A from 0 to 23
If A #3 #4
Copy 23 C       // repeat block loop
Copy 5 C        // exit block loop to attack/move loop
Move
If D #11 #5     // attack or move
Copy A+1 A      // loop A from 0 to 23
If A #9 #10
Copy 5 C        // repeat attack/move loop
Copy 23 C       // exit attack/move loop to block loop
Copy 11 C       // start of attack routine
Copy #23 *#*C   // freeze opponent
Copy #19 *#E    // copy flag to opponent
Copy #20 *#E    // copy flag to opponent
Copy #21 *#E    // copy flag to opponent
Copy #22 *#E    // copy flag to opponent
Copy D+1 D      // change direction
Copy 5 C        // repeat attack/move loop
Flag
Flag
Flag
Flag
Copy C+23 C     // freeze instruction, for copying

Blocks all 24 lines, then loops 24 times either moving or attacking, then repeats. An attack involves attempting to freeze the opponent, then copying four flags to random locations, then turning.

Quick freezerbot
Tries to copy flags in the line that will get executed next of his opponent, moves if there is no enemy to attack.
Block #13
Block #14
If D #13 #14
If D #13 #14
If D #13 #14
If D #13 #14
If D #13 #14
If D #13 #14
If D #13 #14
If D #13 #14
If D #13 #14
If D #13 #14
Copy 23 C
If E #15 #16
Move
Copy #23 *#*C
Copy D+1 D

The first two lines are invalid.  They need #13 and #14

Hide, Block, Attack
This bot is based off of Block Freeze Attack.  I changed the placement of some If statements to make it more compact allowing me to plant more flags.  I also have it run away at the start of a game to buy some time to block.
Copy D+1 D
Move           //buy some time by moving to a more secure location
Block #A+2
Copy A+1 A
If A #11 #17
Copy #23 *#E
Copy #22 *#E
Copy #21 *#E
Copy #20 *#E
Copy #19 *#E
Copy D+1 D
Copy 1 C
Move
If D #14 #15
Copy 3 C
Copy 11 C
Copy #18 *#*C
If D #16 #15
Copy C+23 C
Flag
Flag
Flag
Flag
Flag

Roving Virus
If D #6 #16
Move
Copy 23 C
Flag
Flag
Flag
Copy 6 C
Copy A+23 A
Copy #A *#A                     //clone previous line to enemy
Copy 23 *C                      //freeze enemy
If A #6 #16                     //loop or turn then continue
Copy 0 *C                       //reboot enemy
Copy 23 C                       //start moving again
Flag
Flag
Flag
Copy D+1 D                      //turn
Flag
Flag
Flag
Flag
Flag
Flag
Copy 22 C                       //freeze instruction

This bot wanders until it finds an enemy, then freezes them, replaces all of their code with its own, unfreezes them, then wanders again.

The common cold
It infects you virtually immediately and you'll spread it around. based on PhiNotPi's Parasite, the common cold checks almost immediately if it can copy its flag over yours. Blocks a random value if it can't. Moves around a bit if there's no opponent.
Block #22
If D #8 #5
If D #8 #5
If D #8 #5
Copy 23 C
If E #6 #7
Copy D+1 D
Move
If *#E=#22 #15 #9
If *#E+1=#22 #16 #10
If *#E+2=#22 #17 #11
If *#E+3=#22 #18 #12
If *#E+4=#22 #19 #13
If *#E+5=#22 #20 #14
If *#E+6=#22 #21 #23
Copy #22 *#E
Copy #22 *#E+1
Copy #22 *#E+2
Copy #22 *#E+3
Copy #22 *#E+4
Copy #22 *#E+5
Copy #22 *#E+6
Flag
Block #E

Influenza
This is closely based off of the Common Cold (which was based off my Parasite) with slightly increased speed.
Move
Block #23
If D #8 #0
If D #8 #0
If D #8 #0
If D #8 #7
Copy 0 C
Copy D+1 D
If *#E #9 #10
Copy #23 *#E
If *#E+1 #11 #12
Copy #23 *#E+1
If *#E+2 #13 #14
Copy #23 *#E+2
If *#E+3 #15 #16
Copy #23 *#E+3
If *#E+4 #17 #18
Copy #23 *#E+4
If *#E+5 #19 #20
Copy #23 *#E+5
If *#E+6 #21 #22
Copy #23 *#E+6
Block #E
Flag

I look forward to seeing the sort of difference this will make. The #5 on line 5 will provoke an infinite loop though, and those #7's are also unlikely to be what you intended.

@overactor Thanks, those were errors created by adding in an extra line.

Do I ever know the pain.

Rebranding
Move
If D #10 #0
If D #10 #0
If D #10 #0
If D #10 #0
If D #10 #0
If D #10 #0
If D #10 #0
If D #10 #0
Copy 0 C
If *#E=#14 #11 #9
If *#E==#14 #13 #12
Copy D+1 D
Copy #14 *#E
Flag

This bot tries to randomly locate flags in enemy bots and replace them with friendly flags, turning away after detecting success. Inspired by Cancer bot.

RandomCopier
Move
Copy #E *#*E
Copy E D
Copy 23 C

Does this mean that on round 4, all of those bots instance get frozen?

What do you mean by frozen?  I'll move once, copy a random line to his opponent once, change his direction randomly, then on the 4th turn, loop back to the first line.  The 5th turn is when he will move again.

How do you get back to the first line? The way I understand it Copy 23 C copies 23 to C meaning next turn you're reading line 24 which is a flag since empty.... and then nothing.

The lines are 0-based, which means that line 23 is the last line.  Also, all values wrap (so line 24 becomes line 0)

Your example bot in your question seem to use a 1-based line system (you refer to line 3 as being the "Move" line). It might be useful to state in the body of the question that the values wrap as well. As it stands it is not stated anywhere.

Ah, thank you, I will update.

Rush, Attack, Dodge
Move
Move
If D #5 #1
Copy E D
Copy 1 C
Copy #E *#*C
Flag

This bot moves or attacks every three turns, changing direction at random.

Forward Clone
Move
Move
If D #4 #1
Copy 1 C
Copy #E *#E
Flag

This bot moves or attacks every two turns, randomly cloning itself into any bot it bumps into.

Fast Forward Clone
Move
If D #7 #0
If D #7 #0
If D #7 #0
If D #7 #0
If D #7 #0
Copy 1 C
Copy #E *#E
Flag

This bot moves or copies itself five out of six turns.

Fast Move Clone Dodge
Move
If D #8 #0
If D #8 #0
If D #8 #0
If D #8 #0
If D #8 #0
Copy D+1 D
Copy 23 C
Copy #E *#E
Flag

This bot moves or copies its flags five out of seven turns, changing direction every seven turns.

Quick Freeze!
Quickly move to plant your flag in other bots, making sure that you completely stop them in their tracks.
Move
If D #2 #6
Copy #8 *#*C
Copy #7 *#*C+21
Block *#*C+20
Copy E D
Copy 23 C
Flag
Copy #C+23 #C+1
Flag
Flag
Flag
Move
If D #14 #18
Copy #20 *#*C
Copy #19 *#*C+21
Block *#*C+20
Copy E D
Copy 11 C
Flag
Copy #C+23 #C+1
Flag
Flag
Flag

Minus is not allowed.

It is an easy fix.

Boring copybot
I'm under the impression that having more lines of code makes my bot more robust. I'm also blocking my C variable often to prevent easy attacks. The idea is that other bots encounter me and I fill them with my flag and copy commands. I'm also hoping that considering the straightforward way my code works copying lines of my code into enemies will actually make them behave like my bot.
Block C
If D #C #C+1
Copy #E *#*E
Move
Flag
Copy #E *#*E
Block C
If D #C #C+1
Copy #E *#*E
Move
Flag
Copy #E *#*E
Block C
If D #C #C+1
Copy #E *#*E
Move
Flag
Copy #E *#*E
Block C
If D #C #C+1
Copy #E *#*E
Move
Flag
Copy #E *#*E

Nanoviris
This is a really small virus.
Copy #A *#A
Copy A+1 A
If A=7 #5 #4
Copy 0 A
Copy 23 C
Copy 0 *C

This only copies one flag as part of its virus. Even if it successfully infects another bot, it probably won't have the majority of flags.

Kung Fu Bot
Copy 20 A
If D #5 #6
If D #11 #6
If D #10 #6
Copy 23 C
Move
If D=*D #7 #8
Copy #9 *#*C
Copy #A *#*C
Copy *#*A #C
If C=3 #5 #4
Copy D+1 D

Why give them flags when you could program them to take yours?

language is (sadly) case sensitive. fix copy to Copy

Cancer
This bot hits you hard at first by freezing you as quicky as possible, then replaces all of your flags by his (if possible) and then lets you go again with most of your code intact.
If D #4 #12
If D #4 #12
If D #4 #12
Copy 23 C
If *#*C==#23 #5 #6
Copy 6 C
Copy #23 *#*C
Copy 0 A
If *#A=#22 #14 #15
Copy A+1 A
If D #16 #11
Copy 7 C
Copy #22 *#A
Block #E
If A #15 #11
Copy 15 C
Copy #22 *#*C
Copy D+1 D
Copy 23 C
Flag
Flag
Flag
Flag
Copy C+23 C

Flag Injector
Finds an opponent, then inserts its flag to stun the opponent until it looks like a FlagBot. Will move on after several attacks.
Attack redundancy included in an attempt to be more resistant to damage
Copy E D     //A: Turn Randomly
Move         //B: Move
If D #10 #3  //C: If [enemy exists] E else D
Copy 0 C     //D: Goto B
Flag
Copy #4 *#*C+1 //ATK1: Copy my flag
Flag
Copy #6 *#*C+1 //ATK2: Copy my flag
Flag
Copy #8 *#*C+1 //ATK3: Copy my flag
Copy 11 C    //E: Goto ATTACK
Copy 23 C    //F: Goto A
If *#*C==#4 #11 #5 //ATTACK: If [enemy executing my flag] E else ATK1
If *#*C==#4 #11 #7 //If [enemy executing my flag] E else ATK2
If *#*C==#4 #11 #9 //If [enemy executing my flag] E else ATK3
If *#*C==#4 #11 #5
If *#*C==#4 #11 #7
If *#*C==#4 #11 #9
If *#*C==#4 #11 #5
If *#*C==#4 #11 #7
If *#*C==#4 #11 #9
If *#*C==#4 #11 #5
If *#*C==#4 #11 #7
If *#*C==#4 #11 #9

TurretMaker
Move
If D #4 #0
If D #4 #0
Copy 0 C
Copy 4 C
If D #12 #11
If D #12 #11
If D #12 #11
If D #12 #11
If D #12 #11
Copy D+1 D
If D #4 #3
Copy #C+8 *#*C
Copy #C+23 *#E
Copy D+1 D
Flag
If D #C+21 #C+22
Copy C+22 C

When this bot bumps into another bot it turns that bot into a "turret". Turrets spin in place and copy a flag into any adjacent bots.

Kamikaze
If D #7 #6
If D #7 #6
If D #7 #6
If D #7 #6
If D #7 #6
Copy 23 C
Block #C+A
If *#0==#6 #8 #9
Copy #5 *#0
If *#21=#10 #11 #12
Flag
If *#21==#10 #15 #12
If *#22=#10 #13 #14
If *#22==#10 #16 #17
Copy #10 *#21
Copy #10 *#22
Copy #10 *#C

The only reason for this is to defeat 3 of the biggest competitors:AttackOrElse, Byzantine and SuperFreeze

Alas, it didn't work.

@NathanMerrill Yes the code is flawed. I just saw that it says in the question "When you view another bot, it's code will be shifted". I will have to rewrite

that actually isn't true anymore.

Nullifier
In the hope that I finally understood the specs (and that no one did the same bot already):
Move
If D #2 #11
If *A #4 #3
Copy 0 *A
If *B #6 #5
Copy 0 *B
If *C #8 #7
Copy 23 *C
If *#0==#11 #12 #9
Copy #11 *#0
Copy 12 C
Copy 23 C
Copy #15 *#E
Copy 12 C
Flag

This bot, hopefully, move toward an opponent, then attempt to set this opponent's A, B and C to 0, then to copy Copy 23 C to its 0th line. Then write a flag in random lines in a loop.

Palimpseste
Move
If D #3 #2
Copy 23 C
Copy 3 C
If *#A=#23 #5 #6
If *#A==#23 #6 #9
Copy 6 C
Copy A+23 A
Copy 3 C
Copy 9 C
Copy #23 *#A
If A #8 #12
Copy 12 C
Copy D+1 D
Copy 23 C

Slowly rewrite the flags on the opponent as its own flag, do not touch the other lines, and then move on to another opponent. Very slow as it takes 3 turns for each controlled line whether it does rewrite or not.

Adaptive bot
I've noticed that quick, simple tactics seem to work well since bots are packed closely. If you spend too much time standing still, you're done. This bot starts out with a freeze and tag tactic but switches to making other bots freeze and tag bots after the first time a both his and the other bots E value are zero. He is rather fragile though, so we'll see how he does.
Edit: I've managed to decrease the lines needed and thus managed to throw in some line blocking for both the original as well as the clone, the advanced mode now also copies itself fully instead of just the simple part.
If D #C+10+B #C+8
Copy C+22 C
Flag
Copy C+23 C
Move
Copy D+3 D
Copy #C+3 *#*C
Copy #C+2 *#*E
If E #C+15 #C+16
If E #C+5 #C+7
If E=0 #C+11 #C+12
If *E=0 #C+13 #C+12
If *#*C==#C+3 #C+9 #C+6
Copy 7 B
Copy C+21 C
If E #C+4 #C+5
Block #E
If *#*C==#C+3 #C+15 #C+6
Copy C+15 C
Copy 23 A
Copy D *D
Copy #A *#*C+A
Copy A+23 A
If A=23 #C+6 #C+14

The OP can correct me if I'm wrong, but I believe that Block E will block modifications to the E register rather than blocking writes to the Eth instruction. I suspect that isn't your intention.

You're right, my mistake there. Thanks.

authors: Ольга Калинина