# What is the Sandbox?

This "Sandbox" is a place where Code Golf users can get feedback on prospective challenges they wish to post to the main page. This is useful because writing a clear and fully specified challenge on the first try can be difficult. There is a much better chance of your challenge being well received if you post it in the Sandbox first.

See the Sandbox FAQ for more information on how to use the Sandbox.

## Get the Sandbox Viewer to view the sandbox more easily

To add an inline tag to a proposal use shortcut link syntax with a prefix: [tag:king-of-the-hill]

I've been reading this forum for a bit and I thought it might be a good idea to do a short sequence of challenges themed on famous mathematicians. It's my first post here so please point out any shortcomings.

It is Irving Kaplansky's birthday today. Among other things he is famous for his conjectures on group rings. It is one of these conjectures in mathematics that requires virtually no special knowledge to understand. There a couple of words that need explaining in them but their definitions are very simple. These words are "group", "torsion-free group", "ring", "domain", "group ring", "idempotent", "unit".

Please read up if you want to. This challenge doesn't require understanding these words or the conjecture. All that's needed is the concept of a finite cyclic group. I'm sure most of you know what it is, but I'll give a short introduction. A cyclic group of order n can be understood as what you get when you take something (whatever) called a generator, say p, and decide that it can be raised to integer powers. These powers can be multiplied like so: pk * pl = pk+l. But there's one catch: whenever the exponents of the powers give the same remainder from the division by n, these powers are considered equal. This means, in particular, that there are exactly n powers really: p0, p1,...,pn-1. Any other power is equal to one of these.

The challenge is to implement a certain operation on certain formal expressions involving these powers. The expressions are of this form:

r0 * p0 + r1 * p1 + ... + rn-1 * pn-1,

where all ri are real numbers.

The operation, called multiplication, consists in, first, multplying two such expressions as if they were real sums, that is for example, for n=3:

(2 * p0 + 3 * p1 + 2 * p2) * (0 * p0 + 1 * p1 + 2 * p2)=

(2 * p0) * (0 * p0) + (2 * p0) * (1 * p1) + (2 * p0) * (2 * p2) +

(3 * p1) * (0 * p0) + (3 * p1) * (1 * p1) + (3 * p1) + (2 * p2) +

(2 * p2) * (0 * p0) + (2 * p2) * (1 * p1) + (2 * p2) + (2 * p2).

Then, we simplify each of the summands according to the rule

(r * pk) * (s * pl) = (r * s) * (pk * pl) = (r * s) * pk+l.

And finally, we simplify the resulting sum according to the rule

(r * pk) + (s * pk) = (r + s) * pk.

This means that for n=3, we have 2 * p2 + 5 * p5 = 7 * p2 because p2=p5!

The resulting sum is again of the form

r0 * p0+ r1 * p1 + ... + rn-1 * pn-1

after we order the summands by the exponents.

This operation is exactly the product in the group ring R[C], where R is the field of real numbers and C is a finite cyclic group. This group ring doesn't satisfy the hypothesis of Kaplansky's conjecture because finite cyclic groups aren't torsion-free.

Your task is to implement this in any language. Your program/procedure/whatever has to take a natural number n>0 as user input. This will be the order of your cyclic group. Then it has to take 2n "real numbers" as user input. I don't really care what the "real numbers" are in your implementation. They could be ints for all I care. Just make them something that can reasonably be interpreted as real numbers and has a reasonable arithmetic. The first n numbers will be the coefficients of the first formal sum and the other n numbers will be the coefficients of the second formal sum. You need to output the n coefficients of their product. You don't need to compute the product in the way describe above. It just has to be correct (modulo rounding errors and other things computers do wrong with numbers).

Shortest code wins. You can assume the input is valid. Both input and output can be in any reasonable form. I'm not sure if this is a good restriction on this site, but I'd like you to think "actually usable". Though I don't really care about how long it takes to compute. I guess all standard loopholes apply, as I've noticed it seems to be a mantra here. :-)

• Did you mean to shift the indices in "r_1 * p^0 + r_2 * p^1 + ... + r_(n-1) * p^(n-1)"? Also, do I understand right that you're asking for us to multiply formal polynomials under the relationx^n = 1? – xnor Mar 22 '15 at 22:53
• @xnor I didn't mean to do that! And yes, that's one way of saying this. Another way of saying it is to multiply elements of the group ring R[C] where C is a finite cyclic group and R is the field of real numbers. My goal is to introduce the concept of a group ring and this is one of the simplest cases. For the infinite cyclic group it would amount to the Laurent polynomials, and that's too familiar I think. This is the next simplest case. – ymar Mar 22 '15 at 22:59
• @Martin Done, thanks! – ymar Mar 22 '15 at 23:18
• @xnor I've corrected the indices (there were some more errors). Do you think this is too simple? I was thinking of doing it with the quaternion group... – ymar Mar 22 '15 at 23:19
• Added the statement that this is a group ring product. – ymar Mar 22 '15 at 23:23
• I think the problem is OK, but people might just do this by multiplying regular polynomials and then combining x^(n+i) with x^i. I like the group idea, but I've already done the quaternions. – xnor Mar 23 '15 at 4:03
• @xnor Well, for the quaternions it wouldn't be as simple. Perhaps I could stipulate that one of the answers to your problem should be used in some way? – ymar Mar 23 '15 at 4:16
• What do you mean that it wouldn't be as simple? – xnor Mar 23 '15 at 4:20
• @xnor I mean that it wouldn't be just a simple variation on polynomial multiplication. It's still similar because that's what the (semi)group ring multiplication is: a generalization of polynomial multiplication. But the case of the quaternion group is further away from polynomials than cyclic groups. – ymar Mar 23 '15 at 4:24

# Functioning HTML-Encoded Program

Introduction

When showing code to others on the web, some characters are generally replaced by their HTML-encoded entities. Browsers display this properly, but if a user copies the code directly from HTML or a script tries running the code without decoding its entities, the code will likely contain errors.

Challenge

You are to come up with a program that uses all of the following five characters: ", &, ', <, and >. When encoded to their named XHTML entities, the code must still run using the following respective entities: &quot;, &amp;, &apos;, &lt; and &gt;. The code must be able to run both ways without throwing errors. Each of the five characters must be used outside of comments and string-like objects at least once (ie. for JS, outside of literal regex). You may use an expression in place of a statement up to one time (if your language supports it).

Example JS Script (1/5 required characters)

Unencoded: (Sets lt to true)

var lt = 6;
lt = 3 < lt;

Encoded: (Sets lt to 2)

var lt = 6;
lt = 3 &lt; lt;

Encoder/Decoder

Here's a converter to make testing your code easy (click run code to use):

function encode() {
document.getElementById('post').value = document.getElementById('pre').value.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/'/g, '&apos;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
if (entity=document.getElementById('pre').value.match(/&\S+?;/)) alert('Warning: Unencoded text may already have entities. (ie: ' + entity[0] + ')');
} function decode() {
document.getElementById('pre').value = document.getElementById('post').value.replace(/&quot;/g, '"').replace(/&apos;/g, '\'').replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&amp;/g, '&')
if (entity=document.getElementById('post').value.match(/&(?:[\s;]|[^\s;]*(?:\s|\$))|<|>|'|"/)) alert('Warning: Encoded text may contain unencoded characters. (ie: ' + entity[0][0] + ')');
}
<label for="pre"><b>Unencoded:</b></label> <button onclick="encode()">Encode</button><br /><textarea id="pre" style="width:100%;min-height:49px;resize:vertical"></textarea><br /><br />
<label for="post"><b>Encoded:</b></label> <button onclick="decode()">Decode</button><br /><textarea id="post" style="width:100%;min-height:49px;resize:vertical"></textarea>

The shortest functioning unencoded code block wins. Have fun!

• I would vote to close this as too broad, because as far as I can tell from the question, all the program has to do is not crash. It probably wouldn't be a good question even with a spec which required it to perform a stated task, though, because it's so easy to bypass the intent by using no-ops. – Peter Taylor Mar 27 '15 at 23:37
• @PeterTaylor That was the point of me including "You may use an expression in place of a statement up to one time (if your language supports it)," but I suppose that I can't assume that'll cover every case of no-ops in programming languages out there. – Pluto Mar 30 '15 at 19:40

# Print All Provable Statements

This might be a stretch to make into a challenge, but I think it can be done. The challenge will most likely be code-golf. I'm thinking about using 2D geometry as the basis. I will have to create a notation system for geometrical and logical statements that is golf-friendly.

The general idea is that you start off with a list of known facts. Then, the program uses the laws of logical deduction to work through every possible deduction that can be made, and then add these new facts back into the pool of knowledge. Given enough time, every possible provable statement will show up in your list. Of course, you will run out of memory first, and that's okay.

Probably the best axioms to use are Tarski's Axioms. From the wiki article:

Tarski's system has the unusual property that all sentences can be written in universal-existential form, a special case of the prenex normal form. This form has all universal quantifiers preceding any existential quantifiers, so that all sentences can be recast in the form

∀u∀v...∃a∃b...

This fact allowed Tarski to prove that Euclidean geometry is decidable: there exists an algorithm which can determine the truth or falsity of any sentence. Tarski's axiomatization is also complete. This does not contradict Gödel's first incompleteness theorem, because Tarski's theory lacks the expressive power needed to interpret Robinson arithmetic (Franzén 2005, pp. 25–26).

There are three (?) fundamental relations:

• x=y Equality - x and y refer to the same objects
• Bxyz Betweenness - The point z is between x and z, lying on line segment xz. It is possible for x=y or y=z.
• wx~yz Congruence - The length of line segment wx is equal to the length of line segment yz.

There are three congruence axioms:

• xy~yx Reflexivity of Congruence
• xy~zz → x=y Identity of Congruence
• xy~zu & xy~vw → zu~wz Transitivity of Congruence

There are also betweenness axioms:

• Bxyx → x=y Identity of betweenness
• Bxuz & Byvz → ∃a(Buay & Bvax) Axiom of Pasch
• Axiom Schema of Continuity: I'll need some help translating this.
• ∃a∃b∃c(!Babc & !Bbca & !Bcab) Lower Dimension

And some more:

• (xu~xv & yu~yv & zu~zv & u!=v) → (Bxyz | Byzx | Bzxy) Upper Dimension
• (Bxuv & Byux & x!=u) → ∃a∃b(Bxya & Bxzb & Bavb) Equivalent to Euclid's Axiom
• (x!=y & Bxyz & Bfgh & xy~fg & yz~gh & xu~fi & yu~gi) → zu~hi Five Point
• ∃z(Bxyz & yz~ab) Segment Construction

## Some notes on mathematical notation.

I think it would be a good idea to convert all math notation to ASCII. I've done with with congruence already, but I need replacements for → ∃ ∀. I might replace a!=b with !a=b for consistency, or I could go all-out and put everything in Polish notation.

## If I wanted fancier axioms

Here is an alternative set of axioms, which are based on Hilbert's geometry axioms but excluding the ones that talk about planes. Some of them are copied verbatim from that website and may be unnecessarily fluffy. I would have to re-write all of them to be in formal notation.

1. Given two distinct points A and B, then there exists exactly one line a that contains both points.
2. Given a line a, there exist at least two distinct points A,B which lie on the line and three distinct points X,Y,Z which are not on the line.
3. If a point B lies between points A and C, then points A,B,C are three distinct points on a line, and B also lies between C and C.
4. For two distinct points A and C, there exists at least one distinct point B such that C lies between A and B.
5. Of any three points on a line, there exists no more than one that lies between the other two.
6. Let A, B, C be three points that do not lie on a line and let a be a line which does not meet any of the points A, B, C. If the line a passes through a point of the segment AB, it also passes through a point of the segment AC, or through a point of the segment BC.
7. If A, B are two points on a line a, and A' is a point on the same or on another line a' then it is always possible to find a point B' on a given side of the line a' through A' such that the segment AB is congruent or equal to the segment A'B'. In symbols AB = A'B'.
8. If a segment A'B' and a segment A"B", are congruent to the same segment AB, then the segment A'B' is also congruent to the segment A"B", or briefly, if two segments are congruent to a third one they are congruent to each other.
9. On the line a let AB and BC be two segments which except for B have no point in common. Furthermore, on the same or on another line a' let A'B' and B'C' be two segments which except for B' also have no point in common. In the case, if AB = A'B' and BC = B'C' then AC = A'C'.
10. Let angle(h,k) be an angle and a' a line and let a definite side of a' be given. Let h' be a ray on the line a' that emanates from the point O'. Then there exists one and only one ray k' such that the angle(h,k) is congruent or equal to the angle(h',k') and at the same time all interior point of the angle(h',k') lie on the given side of a'. Symbolically angle(h,k) = angle(h',k'). Every angle is congruent to itself, i.e., angle(h,k) = angle(h,k) is always true.
11. If for two triangles ABC and A'B'C' the congruences AB = A'B', AC = A'C', angleBAC = angleB'A'C' hold, then the congruence angleABC = angleA'B'C' is also satisfied.
12. Let a be any line and A a point not on it. Then there is at most one line in the plane, determined by a and A, that passes through A and does not intersect a.
13. If AB and CD are any segments, then there exists a number n such that n segments CD constructed contiguously from A, along the ray from A through B, will pass beyond the point B.
14. An extension of a set of points on a line with its order and congruence relations that would preserve the relations existing among the original elements as well as the fundamental properties of line order and congruence that follow from Axioms I-III, and from V,1 is impossible.

Here's a puzzle to be split into two questions:

# Build an evil-defying Tetris AI

Build a program that takes the state of a current board and a piece and attempts to find the optimal space for it.

Your program will be scored by the number of points it can score against the evil Tetris block generators in the question below. Highest score wins. (scoring algorithm to come later)

# Build an evil Tetris block generator

Build a program that attempts to take the state of a current board and generate the worst possible piece for it.

Your program will be scored by the total number of points the AIs built in the question above can score against it. Lowest score wins.

• In general, if you mainly flood with S and Z then it's basically unsolveable. Also related :) – Sp3000 Apr 6 '15 at 13:44

# It's just a flesh wound!

The idea is to create a program that:

• If any one of the four quarters (counted in bytes) is removed, the program outputs "Tis' but a scratch" (exactly, with optional newline).
• If any two of the four quarters are removed, the program outputs "Just a flesh wound.".
• If any three of the four quarters are removed, the program outputs "Let's call it a draw, then.".
• The full program should output "None shall pass.".

Rules:

• The program has to have length divisible by four (4).
• The program must not read it's own source or it's length in any way.
• The output is to stdout if it is possible in your language (REPL output is considered valid in this case).
• The answer with the fewest bytes wins.
• I don't think this would actually be a duplicate of anything in the source-layout tag, but it doesn't feel like it would add anything to the sum of what's already in that tag. – Peter Taylor Mar 19 '15 at 19:17
• Would these 'quarters' be defined by the user, or is it any random 1/4th of the program? – ASCIIThenANSI Apr 5 '15 at 16:49
• @ASCIIThenANSI The quarters are successive quarters of the code. ie. the first one is 0 - 1/4, second is 1/4 - 2/4, third is 2/4 - 3/4 and fourth is 3/4 - 4/4 – seequ Apr 5 '15 at 17:48
• Would it be allowed to read the program's own length? – ASCIIThenANSI Apr 7 '15 at 13:03
• @ASCIIThenANSI No. Updated. – seequ Apr 7 '15 at 14:50
• Here's an idea: If it is full, it prints None shall pass., one-quarter, Tis' but a scratch., and three-quarters, Let's call it a draw, then.. – ASCIIThenANSI Apr 7 '15 at 14:55
• @ASCIIThenANSI Awesome. – seequ Apr 7 '15 at 15:41

# Programming Tetris Blocks (Even More Literally?)

In this challenge, you will write a Tetris AI. There's one twist though: the AI will operate from the perspective of the Tetris blocks themselves.

Note: I am worried about the novelty of this question. The key is "the perspective of the Tetris blocks themselves." In order to make this interesting, I have to give the AI a bare minimum of information needed to make a move. Otherwise, it will just be a regular Tetris AI challenge.

When a Tetris block is spawned at the top of the map, a new AI object is created. Each time step, and the block receives data about its immediate surroundings and returns a move (move left/right, rotate clockwise/counterclockwise, or nothing).

An idea as to "block vision": each of the four squares in a block each have four "eyes," one on each side. Each eye returns the distance to the nearest wall/block (including/excluding other squares in the same block?). This means that the AI will receive exactly sixteen numbers each update.

#######
# 1234#
#  #  #
#### ##
#######

If a 2D array where each row (1st level) is a square and each column (second level) is an eye in the directions [U,D,L,R], then here is what could be seen as input, with 0s representing an adjoining block.

[[1,2,2,0],[1,1,0,0],[1,3,0,0],[1,2,0,1]]

More details coming sometime not now.

• For 'block vision', what if returns -1 if it hits the same block? Also, shouldn't the squares be numbered left to right and up to down, so the I piece is [1][2][3][4], and an example 'block vision' would be [1, 2, 3, 1, 2, 3, 1, 2, 3, 4, 4, 4, 4, 4, 2, 2]? – ASCIIThenANSI Apr 14 '15 at 16:24
• @ASCIIThenANSI In your example, which numbers refer to which squares/eyes? – PhiNotPi Apr 14 '15 at 16:49
• Square 1 is the first 4 numbers ([1, 2, 3, 1]), square 2 the next 4 ([2, 3, 1, 2]), etc. The directions are in the format [U, D, L, R], and it works like [U, D, L, R, U, D, L, R, U, D, L, R, U, D, L, R]. – ASCIIThenANSI Apr 14 '15 at 17:10
• I couldn't really visualize where you were getting the numbers from, so I added my own example. – PhiNotPi Apr 14 '15 at 17:27

# Background

Consider the following grid:

a   b   c
|   |   |
|   |   |
|   |   |
d---+---+---+---e
|1  |2  |3
|   |   |
|   |   |
f---+---+---+---g
|4  |5  |6
|   |   |
|   |   |
h---+---+---+---i
|7  |8  |9
|   |   |
|   |   |
j   k   l

I've marked every endpoint with a letter a-l, and every + with a number 1-9. Imagine, for a moment, that this grid represents a small section of a town. Each | or - represents one segment of a two-way road, and each + represents an intersection, which will have a corresponding stoplight.

During the game, cars will be added and removed from the grid at the endpoints a-l. Cars move exactly one space (through one segment of road or through one intersection) per turn, and never change direction. Thus, if a car enters the grid at endpoint d, it will exit after reaching endpoint e. We may assume that the cars are smart enough to avoid all collisions. They will never move to a space occupied by another vehicle, and they will never enter an intersection when the stoplight they see is red. When a car reaches the opposite endpoint, it disappears and can be safely forgotten.

Assume that we have a variable entitled public_unhappiness that is initialized to 0.

If a car following the above rules may not move due to another vehicle or a stoplight, the value of public_unhappiness is increased by 1.

//SANDBOX NOTE: This formula is linear, but one could say that unhappiness goes up exponentially the longer you sit at a stoplight. This formula is subject to change.

We pit two bots against each other, both controlling traffic flow in different ways. One bot aims to maximize public_unhappiness and the other aims to minimize it. We will refer to the former as The Driver and the latter as The Traffic Engineer. Because this KotH is inherently unbalanced, Drivers and Traffic Engineers will face off in a round-robin tournament (playing only against the opposing faction) and will be placed in separate leaderboards.

# Input

Though the bots are different and rely on entirely different strategies, every bot has access to the same information. Every turn, the bots will be prompted with a list of command-line arguments. Below is a general format:

./Traffic_Troubles Your_bot.extension S1 S2 S3 S4 S5 S6 S7 S8 S9 N a,b,c a,b,c ...

S1 through S9 are binary digits that represent what direction traffic may flow through the corresponding stoplight. If the value is 1, traffic flows horizontally through this stoplight. If the value is 0, traffic flows vertically. Hence, a car approaching intersection 1 from the east will stop moving if the value of S1 is a 0, and continue moving along if that value is a 1.

The following argument is N. This represents the number of cars currently active on the board.

There then follows N descriptions of cars in the form a,b,c. Here, a is the character of the endpoint that a car originated, b is its destination, and c is the number of spaces it has moved. A car that has just been put on endpoint a has moved 0 spaces, and would thusly be described as a,j,0. On the other hand, a car approaching intersection 6 from the west would be described as f,g,11.

On the first turn, every stoplight has value 0, and no cars exist on the board (N == 0).

//SANDBOX NOTE: This input seems pretty messy... Any ideas?

# The Traffic Engineer

Traffic Engineers aim to minimize public_unhappiness by changing the values of the stoplights to allow for traffic to continue through.

You may specify the values of up to three stoplights per turn. Every turn your bot is called, you must provide up to 3 space-separated output pairs of the form a,b where a is the number of the spotlight you want to change, and b will be a binary digit representing the desired value of the stoplight. Invalid output will count as a change to the stoplights, but be ignored. You may choose to output any number of changes less than or equal to 3.

//SANDBOX NOTE: The value of 3 is subject to change.

# The Driver

Drivers aim to maximize public_unhappiness by choosing entry points for cars.

Every turn, you may output up to six distinct entry points for cars in the form X Y Z .... If a car already exists on that entry point and is not moving in the opposite direction that output will be ignored. You may specify any number of entry points less than or equal to 6.

//SANDBOX NOTE: The number 6 is subject to change

# The Sequence of Events

1. Both bots are called at roughly the same time with access to the exact same information.

2. Cars are added to the entry points and the value of stoplights are changed.

3. Cars move, and public_unhappiness is incremented accordingly.

4. Any car that has surpassed its respective exit point is removed from play.

//SANDBOX NOTE: Perhaps the Traffic Engineer should be able to view where the Driver put cars and adjust accordingly. Thoughts?

# Rules

1. Your bot is given 1 second to respond.

2. You may not tailor your bot to act specifically against another bot.

3. Please provide a method for compiling your bot and a command-line method for running your bot.

[Language-name] - [Traffic Engineer/Driver] - [Bot-name]

5. Standard Loopholes are disallowed.

//SANDBOX NOTE: If this idea is received well (~4-6 upvotes on the sandbox) I will build the controller. For now, it's just an idea. If you wish to run/improve on this KotH, you are welcome to.

# 8-FTU - Retrofit UTF-8 to any pre-1988 language

The design of Unicode started in 1987 and was first published in 1988. UTF-8 itself was designed in 1992 and first presented in 1993. Your goal is to retrofit the UTF-8 encoding of Unicode to any language that was in existence on 31 December 1987. You can't use any features that were added to the language after this date.

Your program will take a text input (byte encoded characters, possibly with errors) and up to two integers. Your program must accept any value at any byte position (00-FF).

### Task 1 - Validate the input

Your program will print one of TRUE/FALSE, True/False or true/false depending on whether the text is valid UTF-8 or not, and exit if the format is not valid. See below for validation rules. There are also many online resources that cover the format that you can reference.

### Task 2 - Count the code points

If your program didn't exit at the end of Task 1, it will print the number of Unicode code points encoded within the text.

Using the two integer inputs your program will find and output the matching substring. The first integer will be the starting position, 0 will be the start of the string. If the starting position is after the end of the string, return an empty string. The second integer will be the length of the substring in Unicode code points. If the length is omitted or goes past the end of the string return all the text from the start position to the end of the string. You do not need to program for negative numbers, although you can if you want to.

Tasks 1 & 2 must be printed to standard output. If printing the output of Task 3 would have undesirable consequences (e.g. characters interpreted as control codes) you may return the text instead. You don't have to worry about how the text will display, your code will be taken by DeLorean or TARDIS (depending on country) to 1987 or earlier where a team of engineers will work on displaying it correctly!

### Valid encodings

Code points        Byte encoding
---------------    -----------------
U+0000 - U+007F    Standard 7-bit ASCII (00 - 7F)
U+0080 - U+07FF    Two bytes per code point (C2 80 - DF BF)
U+0800 - U+D7FF    Three bytes per code point (E0 A0 00 - ED 9F BF)
U+D800 - U+DFFF    High and low surrogate pairs, invalid in UTF-8 (ED A0 80 - ED BF BF)
U+E000 - U+FFFF    Three bytes per code point (EE 80 80 - EF BF BF)
U+010000 - U+10FFFF    Four bytes per code point (F0 80 80 80 - F4 8F BF BF)

### Byte table

• 00 - 7F: Standard 7-bit ASCII
• 80 - BF: Continuation bytes
• C0 - C1: Invalid - Task 1 must print one of the false messages if either of these bytes are present
• C2 - DF: Start of two-byte code
• E0 - EF: Start of three-byte code. ED codes where the next byte is one of A0-BF are invalid because they encode surrogate pairs
• F0 - F4: Start of four-byte code. Note: not all sequences starting with F4 are valid. You need to test for these too
• F5 - FF: Invalid - Task 1 must print one of the false messages if any of these bytes are present

The remainder of a multi-byte code must only be continuation bytes until the length is reached. E.g. E4 85 B9 is valid because E4 marks the start of a three byte code, there are exactly three bytes and 85 and B9 are both within the range 80-BF. A continuation byte must not appear except as part of a multi-byte sequence, which must start with C2-F4. Long encodings are not allowed. E.g. "A" is 41, which could also be encoded as C1 81 or E0 81 81. These longer sequences are invalid because there is a shorter, valid sequence.

You don't need to worry about the BOM code point U+FEFF (EF BB BF). Treat it as any other character even if it appears within the text.

### Example input (to be expanded)

C3 87 61 20 76 61 3F 0 2 (Ça va?, 7 bytes, 6 code points)

Outputs:

True
6
Ça

C3 87 61 20 76 61 3F 2 (Ça va?, 7 bytes, 6 code points)

Outputs:

True
6
va?

C1 87 61 20 76 61 3F 0 2 (Ga va?, 7 bytes (overlong error), 6 code points)

Outputs:

False

As mentioned above, the output for Task 3 may be returned as a string instead of printing it.

### Scoring

Either shortest code in bytes or a bonus awarded for retrofitting an older language. Maybe bytes minus the number of months before January 1988, assuming a release date of December if not otherwise specified?

# KotHgress

As everyone knows, the only way to make sure your voice is heard among a group of people is to shout louder than everyone else. This is especially true in KotHgress, a bureaucratic committee of PPCG bots.

The KotHgress Register is a 1D string, at least 100 characters long, containing the minutes of each committee meeting. The only problem is that all the committee members talk at the same time, often shouting over each other, so that (like a typical committee), nothing ever gets done. However, since this is a committee of bots, efficiency is prized almost as much as volume.

# Rules

The Register for each meeting is a string of length max(100, N_bot * 4). At the beginning of each meeting, a committee member bot is pseudorandomly assigned an ascii character to be its voice, and 3 starting positions for its voice in the Register (initial index of 1), with each bot's positions having the same sum - for example, [1,4,100] and [5, 25, 75] could be starting positions.

Each turn, a bot receives 20 points times the number of times its voice appears in the Register. The bot can spend any amount of its points to bid on positions in which to place its voice. A bot that does not spend all its points banks any remaining points towards its score for the round; points do not carry over to following rounds.

Once all bids have been collected, each position is overwritten with the voice of the highest bidder, with ties for high bid causing no change in that position's current character. Note: a bot that is outbid for a position it already occupies loses that position.

Then, each bot accumulates score equal to the combined rank of its voice characters in the Register (for example, "ABABB" would score 4 for "A" at rank 1 and 3, and 11 for "B" at rank 2, 4, and 5), and the Register is sent as input to each member for them to choose their next bids.

After 100 turns, the meeting is over, and the bot with the highest accumulated score wins the meeting.

# Input

Each turn, bot will receive four inputs, in this order:

1. a single character which is its voice
2. a positive integer indicating its current (banked) score
3. a positive integer indicating the number of points it collected this turn
4. a string of length max(100, N_bot * 4), the Register

# Output

The bot should output a string consisting of integer pairs, separated like so: "pos0 bid0|pos1 bid1|...|posM bidM". Banked points will be automatically calculated from the output: banked_points = turn_points - sum(bids).

Invalid output, including sum(bids) > turn_points, will cause your bot to lose its turn (not banking any points).

# Meta-notes

• Controller construction is in progress.
• I expect it to be language-agnostic (using a similar setup to aBOTcalypse). Bots will be allowed one storage file for memory purposes.
• I understand that a > z, A > a, and A > Z. But which would be greater: a or Z? And is the bot with voice a placed before or after the bot with voice b? – ASCIIThenANSI May 15 '15 at 13:10
• I was figuring on going in ascii order, so A->Z->a->z'. That allows for 52 committee members; I can do non-alphas if we get more interest than that, lol. – sirpercival May 15 '15 at 13:33
• OK. Just make sure that you add that to the rules. You could also use some of ASCII's 95 printable characters (minus space, and maybe take out some others that could mess up the input.) – ASCIIThenANSI May 15 '15 at 13:43
• I'll be a little more specific about this, sure. – sirpercival May 15 '15 at 15:02
• This has the classic KotH flaw: the best strategy is either to be purely random or to be the last person to submit your bot, and to metagame it against everyone else's bots. – Peter Taylor May 17 '15 at 16:01
• how would one metagame? the priority order is randomized at the beginning of each meeting – sirpercival May 17 '15 at 16:19

# Time Travel in KotH

This is not a question but a possible mechanic for KotH (type challenge).

In KotH we can ask each program (player) to store all its memory in a file between steps. This makes it possible to change a player's memory to an older one which is not possible with human players. This fact makes it possible to crate time-traveling based games.

I will outline to mechanics here, a simpler one (Time Reverters) and a more complex one (Time Travelers). Both will use a simple game to show how they would work.

# Time Reverters (mechanic I)

## A very simple example game

• Two players, N rounds.
• At every round a random player scores a point.
• The winner is the player with more points after round N.

## The time reverse twist

• At any time in the game a player can chose to time travel (TT) back to any previous round. This means the players will receive the memory they had at that round and forget everything else. Neither of them will know a TT happened.
• Each player can TT K times and this is counted by the controller. If a player tries to travel when it has no more travels left, the TT request is simply ignored.

# Time Travellers (mechanic II)

(will be written later...)

# Split multi-language no-space sentences

You will be given a string representing a sentence without word any boundaries. Additionally, you're given a dictionary of all possible words. Output all possible possible ways of splitting the sentence into words.

But there's a catch! The sentence was written by a drunken polyglot and contains words from multiple languages mixed together. Luckily, you've already got a dictionary of which words from different languages cirrespond to each other. So for each word, you should output its surface form (as it appears in the input sentence) and base form (eg. English). To prevent meaningless interpretations of a sentence as many one-letter words and abbreviations, sort the output by the number of words of each interpretation, lowest first.

Example:

teeistunnationalgetränkdeeikoku

tee/tea ist/is un/a national/national getränk/drink de/of eikoku/england

Given the dictionary below, the first word can only be tee, German for tea. Then comes is, which is already the English is. Then un, French for a. And so on.

tea => tea, tee, cha

is => is, ist, est, dess

a => a, ein, un, une, aru

national => national, kokkateki

drink => drink, getränk, nomimono

of => of, de, von, no

england => england, angleterre, igirisu, eikoku

Each entry of the dictionary is of the form:

<base_form> => <surface_form_1>, <surface_form_2>, ...

That is, the dictionary contains the base form (here English is used), and a list of possible variations in different languages for each.

See below for examples with multiple possibilities.

# Scoring

Code-golf.

(Golfed explanation. Ungolfed: The answer with the shortest code as measured by its bytesize in an encoding the interpreter or compiler accepts without additional flags wins. Multiple files add a penalty of 1 byte for each additional file. Flags add to the score.)

# Rules

• The defaults apply, function or program.
• You may assume there exists at least one solution.
• Your program must run in a reasonable amount of time, so don't just try every possible combination of words. Be prepared for a dictionary that contains hundred or thousands of words. Let's say about ~10 minutes on a modern PC.
• You must support unicode, at least the basic multi-lingual plane, codepoints 0x0000 - 0xFFFF. If your language of choice does not support unicode, you can emulate it using a fixed-length unicode encoding: consider each n bytes of the input sentence a letter.
• You do not need to worry about unicode modifiers, normalizing etc. -- each codepoint is considered a unique "letter".

# Input

• The defaults apply, stdin, command line argument, function argument, javascript prompt etc.
• The input sentence is given as a string (teaist) or list/array ([t,e,a,i,s,t])
• You may assume the input sentence is already in lower case.
• There is no additional punctuation in the input sentence to take care of.
• However, the input sentence and the dictionary may contain "words" with commas, periods, etc., ie. every unicode codepoint from the basic multilingual plane. It will not contain any of the codepoints 0x00-0x20, which means no null-bytes, spaces, tabs, newlines, so you can use them for separating the output.
• The dictionary may be in any format of your choice, but it must contain an association between a base form and all possible surface forms. It must not list all base forms for each surface form.
• You may also read the dictionary from a file, and take the file name or raw data as input.
• You may also assume the dictionary has already been stored in one variable of your choice. If you do, please provide some code for reference how I can put custom data in it, or read the dictionary from a file. However, it must not be pre-processed and as close to a hash (eg. {<base_form> => [ <surface_form_1>, <surface_form_2>, ... }) or array/list (eg. [ [<base_form>,<surface_form_1>,<surface_form_2>,...], [<base_form>,...], ...]) as possible in your language.
• You may choose whether the list of surface forms includes the base form or not, eg. big => big, gross or big => gross.

# Output

• The defaults apply, stdout, stderr, return value, javascript alert, etc.
• It should not need to be said, but if you output to stderr, nothing else but the solution must go to stderr, unless it's a compiler/interpreter warning that can be turned off by a flag.
• A list/array of all possible interpretations of splitting the sentence into words, sorted by the number of words.
• Each interpretation is a list/array of words. Each word is pair/list/array containing the surface form and the base, you may choose in which order. The words must be ordered as they appear in the input sentence.
• Alternatively, the array may be flattened.
• Alternatively, output two lists/arrays, one containing the base form for each word, and one the surface form.
• Alternatively, output a string representation of the array/hash/list.

For example, you could output an array

[["tee","tea"],["est","is"]]

or a flattened array

["tee","tea","est","is"]

or two arrays

["tee","est"]

["tea","is"]

or a string representation such as tee:tea:est:is or tee\ttea\nest\tis\n (\t tab, \n newline). But make sure you're escaping characters properly.

# Test cases:

First line is the input string. Each following line is a possible way of placing word boundaries, surface/base. Afterwards a sample dictionary is provided.

## 1

Note that some words contain a semi-colon.

abcd;efghi

ab/test cd;ef/awesome ghi/result

a/only bcd/test ;ef/awesome ghi/result

with the dictionary:

test: ab, bcd

awesome: cd;ef, ;ef

result: ghi

only: a

yahoo: abcd;efgh

## 2

sumomouserune

sumo/sumo mouse/mouse rune/rune

sumomo/plum useru/lose ne/right

with the dictionary:

sumo: sumo, mouse:mouse, rune: rune, plum: sumomo, lose: useru, right: ne

## 3

koukousensei

koukou/school sensei/teacher

koukou/shiptravel sensei/starfortunetelling

with the dictionary

school: koukou, teacher: sensei, shiptravel: koukou, starfortunetelling: sensei

## 4

unicode support:

with the dictionary:

sira:白, haku:白, kumo:雲, uñ:雲

## 5

Note the order of the results.

aaaa

aaaa/test

a/test aaa/test

aa/test aa/test

aaa/test a/test

a/test a/test aa/test

a/test aa/test a/test

aa/test a/test a/test

a/test a/test a/test a/test

with the dictionary:

test: a, aa, aaa, aaaa

I'll add a larger example should I post this.

• This is basically like a previous suggestion I made, but less complicated. My main motivation had been parsing Japanese kanji compounds, hence the unicode support, but I translated it into something more familar to non-Japanese speakers. – blutorange May 20 '15 at 19:21

## Snake vs labyrinth

Write a program that takes as input a text file representing a labyrinth and checks if this labyrinth can be entirely filled with a snake path. The program should output true or 1 if this is the case, false or 0 else.

The snake can enter the labyrinth at any point. He can move one cell up, left, right or down; once he has crossed a cell of the grid, he cannot go back to that cell. The snake cannot cross a wall or the borders of the labyrinth.

The labyrinth file is a grid of m x n characters, containing either # (wall) or . (empty space).

Example 1

should return true

.

Example 2

should return true

..
..

Possible solution (S = snake start, E = snake end, v = go down, < = go left)

Sv
E<

Example 3

should return true

...
.#.
...

Possible solution (S = snake start, E = snake end, v = go down, < = go left, > = go right, ^ = go up)

S>v
E#v
^<<

Example 4

should return false

.#
#.

Example 5

should return false

#.#
...

Example 6

should return false

.#.
...
...

This is code-golf, so the shortest code wins.

• I take it there aren't any limitations on efficiency? I seem to remember it's an open problem whether HAM-PATH is hard on subgraphs of the grid graph, and if so, you won't be getting an poly-time algorithms. – xnor May 22 '15 at 9:13
• @xnor Yes, no limitations on time/efficiency – Arnaud May 22 '15 at 11:59

Given an input, calculate the correct suffix and output the number in a readable format. The suffixes must go to at least 10^3000, in which the rules for calculating them can be found here, or a list can be found here.

For example:

10000 = 10.0 thousand
135933445 = 135.93 million
-2 = -2.0
-2.36734603 = -2.37
'1'+'9'*3000 = 2.0 nongennovemnonagintillion

Rules:

• No getting things from external resources - it must all be calculated within the code.
• External modules are fine as long as it doesn't breach the above rule.
• The input should work when input as a string, integer or float.
• The output must always contain a decimal place.
• The output must be rounded if above 2 decimal places.
• Leaving zeroes at the end is optional, as long as it doesn't go above 2 decimals (1.00 or 1.0 are both fine) and is consistent for all inputs (1 should output the same as 1.0).
• Must not throw an error no matter how high or low the input is.

Scoring:

• Score is the length of the code, including indents.
• Lowest score wins.
• It does not need to be a function, printing the output is fine.

As a starting point, here is an ungolfed version of some code to generate the list of suffixes. Feel free to build upon this or start from scratch.

a = ['', 'un','duo','tre','quattor','quin','sex','septen','octo','novem']
c = ['tillion', 'decillion', 'vigintillion', 'trigintillion', 'quadragintillion', 'quinquagintillion', 'sexagintillion', 'septuagintillion', 'octogintillion', 'nonagintillion']
d = ['', 'cen', 'duocen', 'trecen', 'quadringen', 'quingen', 'sescen', 'septingen', 'octingen', 'nongen']

num_dict = ['']
num_dict.append('thousand')
num_dict.append('million')
num_dict.append('billion')
num_dict.append('trillion')
num_dict.append('quintillion')
num_dict.append('sextillion')
num_dict.append('septillion')
num_dict.append('octillion')
num_dict.append('nonillion')

for prefix_hundreds in d:

#tillion can't be used first time round
if not prefix_hundreds:
b = c[1:]
else:
b = c

for prefix_tens in b:
for prefix in a:
num_dict.append(prefix_hundreds+prefix+prefix_tens)

For the record, my result is 578 characters. To be fair I'm surprised I couldn't find this being asked before :P

• The meat of this challenge is basically just the reverse of this one, which may explain why you haven't seen it this way. – Geobits May 27 '15 at 16:07
• "The input can be in any format, not just integers." is far too vague. "The output must be rounded if too long." needs to define "too long", and ideally give a rounding rule (e.g. floor, ceiling, nearest half-up, nearest half-down, nearest half-even, nearest half-odd). – Peter Taylor May 30 '15 at 13:46
• Thanks, sorry I'd missed the first answer, that is quite similar haha. This one should use 10x the values and may golf better with outputting the number instead of reading the input. And is the rounding rule actually needed? I generally meant what the default rounding functions do (that you learn in school), which is like half up, but then half down when you're below 0. – Peter May 31 '15 at 8:45
• Ended up busy with other stuff recently so only just remembered about this, would it be worth posting, or is it too similar to that other question? – Peter Jul 13 '15 at 21:46

# Code Bots ϕ

This is a challenge based on the popular Code Bots ("What's wrong with public variables?") challenge.

I made a few observations during the development of the original Code Bots:

1. I had a literal ton of ideas and wouldn't stop harassing Nathan Merrill about them.
2. Nathan Merrill already claimed Code Bots 2.

The solution is obvious: make my own challenge. So, that is exactly what I intend to do.

Note: I am working on various ways to distinguish the two challenges.

## Variables

Note: I have changed the names of some variables to make them more "intuitive."

The variables A and B each store an integer 0-23.

The variable C (for Control) stores an integer 0-23 and is incremented at the end of every turn. It indicates which line of the program is to be executed.

The variable D (for Direction) stores and integer 0-23, which determines the current direction of the bot. The direction is determined by {north east south west}[[D % 4]].

The variable E (for Entropy) is overwritten by a random integer at the end of each turn, but only if your bot uses it that turn.

The variable F (for Feeling) provides a sense of touch. This allows you to detect when a bot is next to you. The value equals the number of adjacent bots. For example, F equals 4 when you are completely surrounded on all four sides (and thus out of luck).

The variable G (for aGe) provides a timer. The value is incremented after the end of every turn, mod 24. This allows an easy way to do for-like loops.

## Instructions

Each line contains a single command, and each command takes a variety of arguments.

Flag : This represents your flag. Your goal is to smear your flag across the known universe. Each flag line has a hidden identifier denoting the owner. These lines do nothing upon execution.

Move : This moves the bot 1 unit forward in the direction that it is facing.

Copy [expr|line] [var|line] : This copies one expression to another. Both expressions must be of the same type. You can copy a line to another line or copy the value of one variable to another. Copying to yourself has a new advantage in that, instead of making an immediate change, the change is made just prior to the start of your next turn.

Copy2 [expr|line] [var|line] : This is a new version of copy, but instead of performing the action immediately after your turn, it performs the action immediately before your next turn. [todo: find a better name for it. Maybe "DelayCopy"]

If [cond] [line] [line] : This is an If statement, one of the most important statements. If the conditional evaluates to true, then the first of the two lines is executed immediately afterwards (on the same turn). If the conditional is false, then the second line is executed immediately afterwards. In order to prevent infinite loops of various kinds, a bot is not allowed to execute the same line twice in a single turn.

Jump [expr] [cond] : This is a new instruction designed to help speed up bots. Given a number N, it immediately sets the value of C to N and then executes #N on the same turn. The condition is optional, but if present it will determine whether or not the Jump command is executed or not.

Block [var|line] : This blocks a certain variable or line. Each variable or line can be blocked once, and this block prevents one modification attempt of that variable/line. If an opponent (or yourself) attempts to modify that variable, then the variable is merely unblocked rather than modified.

## Arguments

There are four types of arguments, var, line, expr, and cond. Here are their relationships:

var = *[var] | A | B | C | D | E
expr = [var] | [expr][op][expr] | [literal number]
op = + | - | %
line = *[line] | #[expr]
cond = [expr] | [line] | [expr]=[expr] | [expr]==[expr] | [line]=[line] | [line]==[line]

There are three types of operators which can be used in expressions: Addition +, Subtraction -, and Modulo %. The modulo operator has highest preference (left to right), with addition/subtraction being applied afterwards.

There are several different kinds of conditionals.

1. If [expr] usually returns true if the value of the expression is non-zero. There are several special cases. If D returns true if there is a bot directly in front of you. If E returns true if E is odd. (Note: add more special cases)

2. If [line] returns true if the line contains a flag.

3. If [expr]=[expr] returns true if the two expressions are equal mod 4.

4. If [line]=[line] returns true if the two lines are the same type (same command).

5. If [expr]==[expr] returns true if both expressions are equal mod 24.

6. If [line]==[line] returns true if the two lines are exactly equal (such as both flags having the same owner).

## The Turn Structure

(Initially, all variables are 0 except for E)
[command execution starts]
The command at line #C is executed.
If there is a chain of logic, it is followed until it stops or a line is visited twice.
The effect of a Copy statement is applied, if any.
C is incremented
If needed, E is randomized.
(other bot's turns here)
F is updated
The effect of a Copy2 statement is applied, if any.
[next command execution]

## Line Labels

To increase the ease of writing bots, there will be new things called line labels, which look like this word: and can be placed at the start of a line. Later in the code, you can reference the line label like this :word. (Note: The exact formatting is up for discussion).

During preprocessing, the controller will replace all instances of :word with the number of the line labeled word:. If the :word label is the only thing on the line (no command) then the entire line will be copied into that blank line. Here is an example:

main: If D #:move #:attack
:main
:main
Jump :main
move: Move
attack: Copy #:flag *#*C

## Other usability features

The language will be completely case-insensitive. Comments will take the form of //comment.

## The Arena

There will be 50 bots of each type entered into an arena. Initially, all of the bots will be evenly spaced on a grid and facing north.

....@.......@.......
.......@.......@....
..@.......@.......@.
.....@.......@......
@.......@.......@...
...@.......@.......@
......@.......@.....
.@.......@.......@..

Note: I believe this to be an improvement because the bots are not directly lined up with each other. In Code Bots 1, a bot could Move on its first turn and end up right behind another bot. In this grid, a bot has a much smaller chance of

## A complicated example bot

Each bot can contain up to 24 lines, and each line contains an instruction. If there are any blank lines (after substitution with line labels), then those lines are filled by Flags.

main: If D #:attackloop #:move        //attack if an opponent
:main                             //automatically filled in with the same line
loop: jump :main                  //executes line 0 again and sets C to 0
move: if T #:run #:turn           //always move (never rotate) when being attacked
run: Move
turn: If E #:run #:turn2          //randomly pick move or rotate
turn2: Copy2 D+1 D
attackloop: jump :attack
attack: Copy #:freeze *#*C         //freeze the opponent
plant: Copy #C+6 *#E              //plant your flag
:plant
:plant
:plant
freeze: Copy2 C-1 C             //this creates an endless loop when executed

After preprocessing, the above bot turns into the bot below. You can also simply submit the bot below without using any line labels if you'd like.

If D #8 #3
If D #8 #3
Jump 0
If T #4 #5
Move
If E #4 #6
Copy2 D+1 D
Jump 9
Copy #14 *#*C
Copy #C+6 *#E
Copy #C+6 *#E
Copy #C+6 *#E
Copy #C+6 *#E
Jump 2
Copy2 C-1 C
Flag
Flag
Flag
Flag
Flag
Flag
Flag
Flag
Flag

## Short, Useful Code Snippets

Block #G
Jump 0 G   //block all the lines in 24 moves

A covering array is an N by k array in which each element is one of {0, 1, ..., v-1} (so v symbols in total), and for any t columns chosen (so an N x t array) contains all possible v^t tuples.

Input: N, k, t, v (all 4 are positive integers), and then N x k integers, each of which comes from {0, ..., v-1}. Each of the integers are separated by spaces.

Output: Yes if the input is a valid covering array, and No if it is not.

Goal: in any language you want, write a program that validates if the input is a covering array in the fastest time. I will run programs on my machine, which is a Macbook Pro 2.2 Ghz Intel i7 with 16 GB RAM.

• Are you planning a follow-up which asks people to generate minimal covering arrays? That seems to be the more interesting direction. – Peter Taylor Jun 11 '15 at 5:31
• @PeterTaylor that's actually a cool idea, but other than v=t=2, the minimal case is not known, and no explicit construction is known (other than orthogonal arrays, which only work for one value of k). One question could be to ask for the best known minimal CA, which is actually something I'd really like (because it is part of my research). – Ryan Jun 11 '15 at 11:46
• I was thinking of a code-challenge which scores by the best CA for certain parameters, possibly required to be deterministic and inside a certain time limit. – Peter Taylor Jun 11 '15 at 12:33
• @PeterTaylor I like that idea, possibly allowing any technique such as simulated annealing. – Ryan Jun 11 '15 at 21:02

# KOTH Simpleton's Chess

## Introduction

### Disclaimer: The word "simpleton" is not meant to offend anyone who is simple or anything else. Don't take it personally, please.

It is a lovely afternoon at the Completely Average Chess Club, and like most afternoons, the chess players, who are also part-time code golfers, are golfing programs to play chess. They use incredibly complicated move-finding algorithms and are golfing them down into 4 byte programs. However, on this particular afternoon, some aliens, who are looking to use human intelligence to play alien chess, steal the chess players' intelligence, turning them into simpletons! Now they can't even remember all the pieces, let alone perform an alpha-beta tree-search.

Today, we won't be focusing on restoring the chess players' minds back. Instead, we'll be playing a modified chess game with simpler rules!

## Rules

### The pieces

Like regular chess, Simpleton Chess has two teams: white and black. Unlike regular chess, however, Simpleton Chess only has one piece that can attack north, north west and north east and can move two squares at a time. If you are familiar with regular chess, this is much like the pawn except for the fact you can attack forward (or north) and can move two squares at a time. Like regular chess, to take a piece you must move in the place of the piece that you wish to take. If there is a piece in of you, and you move 1 square in front, then you will take that piece.

Castling and en passant are ignored.

### Winning the game

To win the game, you must take all the pieces of the opposing team.

### Time limit

Each entry has an allowed time is 3 minutes (180000ms).

### The board

Any piece that moves outside the board will disqualify you. The board is a 2D int array that you can access by assigning a variable to SimpletonUtils.read

### Entries

Your entry is expected to have two methods: getName() and move().

The getName() method will return a String of the name of your entry.

The move method is a void and is called every time you need to move.

To submit the board you use SimpletonUtils.submitBoard

Entries are suggested (and very, very much encouraged) to verify the board using SimpletonUtils.verifyBoard (you have 3 minutes, no need to worry about speed). You will be disqualified if you submit an invalid board, however, you will not be disqualified for sending an invalid board to SimpletonUtils.verifyBoard. If you don't verify the board, a warning will be sent to console output if debug is on (edit SimpletonConfig.java).

Entry template

Here is an example entry to follow:

package SimpletonChess;
import SimpletonChess.SimpletonPlayer;
import SimpletonChess.SimpletonUtils;

public class MyEntry extends SimpletonPlayer {

/**
* Return the name of our bot to the controller
*/
public String getName(){
return "MyEntry";
}

/**
* Method to carry out the logic for our entry
*/
public void move(){
SimpletonUtils utils = new SimpletonUtils();
int[][] board = utils.read(); // Your own local copy of the board

/*
* TODO: Template. Add logic here
*/

utils.submitBoard(board); // Note that you will be disqualified if your board is invalid! Check it with utils.verifyBoard(board), just use an if statement.
}

}

** Remember to add your entry to the controller's main class, SimpletonTournament.java, when you're finished! **

### Controller

Your entries are expected to be written in Java (unless I find the time to write a console parser).

## Final words

Good luck simpletons! I would very much like to see an entry using the monte carlo method, that would be splendid!

Also, a fantastic link for all things chess programming related: http://chessprogramming.wikispaces.com/

That's it from me, send your entries over today!

Notes

• I know there is another KOTH chess tournament. I don't think this is a duplicate since it has simpler rules and different pieces
• Is this too similar to checkers?

TODOs

• Fix overbolding

• Fix possibility to mess up the board with illegal moves (feedback needed)

• Themed intro, since a lot of other people are doing it (feedback needed!)

• Finish controller

• Fix numerous typos and formatting errors

• "Any pieces that the board will be deleted" Did you mean "Any pieces that the board contains will be deleted"? Also, your KOTH seems to have too much boldness . Use bacticks() instead of bold for code formatting and try to use bold whenever appropriate.. – Spikatrix Jun 12 '15 at 4:54
• From your description of the move method, it sounds like an entry has the opportunity to change data that it shouldn't be allowed to change. We all tend to be sportsmanlike here, and I'm sure nobody would try to game the system like that, but you should try not to make such things available. And anyway, if somebody tries to obfuscate their code, or has a bug, an accident could end up catastrophic. I don't know how rigorous your movechecking will be, but be careful. – BrainSteel Jun 12 '15 at 5:12
• What size is the board? Does a piece which gets level with the rearmost of the opponent's pieces become irrelevant except as a guarantee that you can't lose? – Peter Taylor Jun 12 '15 at 8:57
• Thank you for your feedback everyone. CoolGuy: My apologies for over-bolding, will fix. I was editing in another editor, not on StackExchange. @BrainSteel I will play around with various ways of making sure moves are not illegal. Any ideas for how I can make it impossible to unfairly change the board? I'm not very sure about this one, and I'll have a look at other KOTHs to see how they handle it. If you have any suggestions please let me know. Peter Taylor: The size of the board is 8x8. – Matt Y Jun 13 '15 at 3:51
• @BrainSteel I have now finished a system for checking the move which should stop people from changing the board. They receive a local copy of the board and must submit it back with submitBoard (hence now move() is a void). So now I can do move checking. There will also be a method called verify which will verify the board. – Matt Y Jun 13 '15 at 5:52
• Thanks, that looks like a fine way to handle it! You can never be too careful. I await your controller! – BrainSteel Jun 13 '15 at 15:48
• Some diagrams/images would really help clarify the rules- for example the starting set up - I assume each player starts with two rows of pieces at their end of the board but this is not clear. Also a diagram showing the allowable moves would be really great. What happens when one of your pieces reaches the opposite edge of the board and cannot be taken. Other than that looks like a really interesting challenge and looking forward to it... :) – euanjt Jun 13 '15 at 16:38
• Thanks for the feedback! @TheE Controller is on its way. Might take a while... I code as slow as a tortoise ;) – Matt Y Jun 13 '15 at 22:31
• I don't think the themed intro adds anything. – mbomb007 Dec 12 '16 at 16:07

# How Many Isomers of Nonane / Undecane Are There?

Background

Hydrogen and carbon form various series of compounds called hydrocarbons. Carbon forms four bonds and hydrogen forms 1 bond. The alkanes are the series of hydrocarbons without any double bonds between carbon atoms. The first four alkanes are shown below. Hydrogen atoms are omitted for simplicity. We know each carbon forms four bonds, so the unused bonds must have hydrogen atoms on them.

Methane     Ethane    Propane    n-Butane    Isobutane
C           C-C       C-C-C          C-C     C-C-C
|       |
C-C       C

Note that Methane, Ethane and Propane have only one isomer, whereas Butane comes in two isomeric forms. Both have four carbon atoms but in n-Butane they are arranged in a continuous chain, whereas in Isobutane (also known as 2-Methyl Propane) they are arranged as a continuous chain of 3 atoms plus a side branch of one carbon atom.

In both cases, the ten loose bonds on the carbon atoms are occupied by hydrogen atoms. In general, for hydrocarbons with no rings or multiple bonds, the formula is Cn H(2+2n).

1. Your task is to create a program or function that accepts a single integer 0 < n < 10 and outputs to STDOUT or a file all the possible structural isomers of the hydrocarbon of formula Cn H(2+2n). That is to say, all the different ways in which n carbon atoms can be connected together, assuming freedom to twist about all bonds.

2. The carbon atoms shall be represented by the symbol C. In the interest of simplicity, hydrogen atoms shall be omitted. The bonds shall be represented by the symbols - and |. Only horizontal and vertical bonds are allowed. Each isomer shall be represented by a network of carbon atoms separated by bonds. As such the character C will appear on a grid of pitch 2x2.

3. Your program / function shall draw each possible isomer once and only once. The type of isomerism to be considered is structural isomerism. That is to say, compounds with different branching patterns shall be considered different. Different stereoisomers and different conformations shall be considered equivalent. Any conformation that complies with Rule 2 is valid.

4. The different isomers shall be displayed one below the other, in any order. To assist in checking, each isomer shall be preceded by a sequential number (starting at 1) on its own line. There shall be no more than 5 blank lines between any isomer and the preceding / following numbers. Unnecesary whitespace to the left and right of each isomer shall not exceed 10 characters in either direction.

5. To avoid extreme brute force solutions, execution time shall not exceed 1 minute on my machine for any input case.

6. Scoring: This code golf. Shortest code wins. If your program can handle up to n=11 instead of n=9 there is a -50% bonus. Above n=9 is significantly harder, because the sidechains can themselves have sidechains.

Above n=11 there exist some isomers that cannot be represented according to the rules of this question as some atoms would overlap.

The number of isomers for each value of n is given in https://oeis.org/A000602. Note that behaviour for n=0 can be undefined. The names of the isomers are here: http://www.kentchemistry.com/links/organic/isomersofalkanes.htm

n       0  1  2  3  4  5  6  7   8   9  10   11
isomers 1, 1, 1, 1, 2, 3, 5, 9, 18, 35, 75, 159

EXAMPLE OUTPUT n=6 (all 5 possible isomers) Note: you must display the isomers one below the other. They are displayed side by side here to save space. For further explanation, a video explaining structural isomerism with this example is here: https://www.youtube.com/watch?v=qOhEJK4Umds

1            2          3           4         5
C
|
C-C-C-C-C-C  C-C-C-C-C  C-C-C-C-C   C-C-C-C   C-C-C-C
|            |         | |       |
C            C         C C       C

EXAMPLE OUTPUT n=8 (only some of the possible isomers, you must display them all.)

n-Octane

C-C-C-C-C-C-C-C

3,4dimethyloctane. Those who know about stereoisomerism will know that in 3 dimensions the bonds are arranged in a tetrahedron around the carbon atom. This means that this compound can exist in 3 distinct forms: a lefthand form, a righthand form and a mirror symmetric form. For the purpose of this question these are equivalent and any one of the following is acceptable (and there are many other acceptable ways of drawing this isomer.)

C-C-C-C          C          C-C-C-C             C          C-C-C-C       C-C-C-C-C-C
|              |              |               |            |               | |
C-C-C-C      C-C-C-C-C-C        C-C-C-C       C-C-C-C-C-C    C-C-C-C           C C
|                                  |
C                                  C

EXAMPLE OUTPUT n=10 (only some of the possible isomers, you must display them all.)

triisopropylmethane, or 2(methylethyl)1,3dimethylpentane (n=10 is the smallest n where there can be a sidechain of three C atoms, and therefore also the smallest n where a sidechain itself can be branched.)

C   C
|   |
C-C-C-C-C
|
C-C-C

2,2,3,4,4pentamethylpentane (it can be shown that for n=10 a maximum of 2 carbon atoms can be completely surrounded by four other carbon atoms each.)

C   C
|   |
C-C-C-C-C
| | |
C C C
• I'm surprised this hasn't been asked before, but I can't find it. Is code challenge (with codegolf tie break) the best scoring? I'm not sure about making it a codegolf, because I think the higher n are probably quite hard and it would discourage participation. – Level River St Jun 14 '15 at 10:27
• Do enantiomers count twice? – feersum Jun 15 '15 at 5:37
• "Your task is to create a program or function that accepts a single integer 0 < n < 12 ... The winning entry will be the program that produces correct output for the highest value of n ... Above n=11 there exist some isomers ... that cannot be represented according to the rules of this question" What I understand from this is that every valid submission gets the same score, which seems a bit pointless. With the given tie-breaker, it's effectively just a code-golf. – Peter Taylor Jun 15 '15 at 7:13
• @PeterTaylor I've changed it to a codegolf for n=9, plus a generous bonus for n=11. n>9 is fiddly (more for display reasons than underlying maths) because sometimes the sidechains have sidechains. I want to see all the way to n=11, but I don't want to exclude people by making it too hard. – Level River St Jun 15 '15 at 14:20
• @feersum to avoid complication, enantiomers and other types of stereoisomers are considered equivalent, you should only include one of them for each structural isomer. In any case they can't be distinguished properly according to the display spec. Bond symbols such as < and > would be needed to show whether an atom is closer/further than another. I thought this was clear from rule 3 and example 3,4 dimethyloctane, but I'm not surprised someone asked. Is there a way to make this clearer? – Level River St Jun 15 '15 at 14:28

# Solve the nonogram

Nonograms, also known as Hankie or Picross, are fascinating. They are really simple is essence, but to solve the most complexe one, some tricks have to be learned.

## Basics

Nonograms are usually presented this way :

1
2 1 2
3 2 1 2 3
+-----------
3|
2 2|
1 1 1|
2 2|
3|

The numbers in lines and columns determine how much box in a row will be present, and how much sets there will be on this line/columns. The seconde line says 2 2which means "2 boxes in a row, at least one space, 2 boxes in a row" Let's give it a try with the 5x5 sample above. I will use #for boxes and .for blank confirmed.

1
2 1 2
3 2 1 2 3
+-----------
3|
2 2|
1 1 1|
2 2|
3|
As we said, second line says 2,some spaces,2.
As we are playing on a 5x5 board, there's only one space remaining after
putting the boxes, so their position is certain.
1
2 1 2
3 2 1 2 3
+-----------
3|
2 2| # # . # #
1 1 1|
2 2|
3|
There's some other 2 2 rows, let's fill them !

1
2 1 2
3 2 1 2 3
+-----------
3|   #   #
2 2| # # . # #
1 1 1|   .   .
2 2| # # . # #
3|   #   #

We can say this puzzle is over :
Look at the 1 1 1 rows, they have already 2 blank confirmed
which means there's only 3 spaces left. We can fill these, and complete the
puzzle.

1
2 1 2
3 2 1 2 3
+-----------
3|   # # #
2 2| # # . # #
1 1 1| # . # . #
2 2| # # . # #
3|   # # #

We didn't checked all confirmed blank, but it's not the matter, we only need
to check the boxes. Note that the 3 rows has been useless to solve this
puzzle.

There you got the basics, but some tips on the wikipedia page could be useful.

## Goal

Your job is to write a program in the language you want to solve nonograms.

There shouldn't be any problem, but here's some loopholes that are forbidden, just in case :).

I'd also like you to write which down command have to be run to execute your code, and

## Input

The input can be graphic, an array, a string via stdin, or whatever you want. You may hard-code it, I want to know how fast your program is to solve nonograms, not how fast it is to parse datas. I'll provide two format for each test case. A ASCII-Art'd one, as shown above, and one structured as an array in the form :

[[columns],[lines]]
columns and line will also be noted the same way, the array for the sample :
[[[3],[2,2],[1,1,1],[2,2],[3]],[[3],[2,2],[1,1,1],[2,2],[3]]]

## Output

You must produce the solved nonogram, formated as you want as long as it is clear. It should be outputed via stdout, or your language closest alternative, as an Image, Ascii-art or left on top of the stack.

## Test Cases

Puzzles will never be greater than 99*99, nor smaller than 2*2.They all are solvable by using basic techniques, the ones shown on wikipedia are far more than enough.

I might add some test cases latter, but big ones take time, a lot of time. If you want to give it a try, post one with your answer, and it will be added if it is solvable without any guess. Which means solving only those one won't be necessary nice, you need to be able to solve any "basic" nonogram : No multi-row - multi depth contradiction looking. Even contradiction shouldn't be necessary

5x5
[[[3],[2,2],[1,1,1],[2,2],[3]],[[3],[2,2],[1,1,1],[2,2],[3]]]

1
2 1 2
3 2 1 2 3
+-----------
3|
2 2|
1 1 1|
2 2|
3|

10x10

[[[3],[2,2],[1,1,1],[2,2],[3],[3,1],[2,7],[1,1,1,1],[2,2,2],[3,3]],[[3],[2,2],[1,1,1],[3,2,2],[2,2,3],[1,1,1,1],[2,4,1],[3,1,2],[4],[1]]]

1
1         1 2
2 1 2   3 2 1 2 3
3 2 1 2 3 1 7 1 2 3
+--------------------
3|
2 2|
1 1 1|
3 2 2|
2 2 3|
1 1 1 1|
2 4 1|
3 1 2|
4|
1|

30x30

[[[10,6,10],[9,8,9],[7,10,7],[7,14,6],[6,15,5],[6,15,5],[5,17,4],[5,19,4],[26,3],[4,2,10,2,3],[4,1,8,1,3],[3,12,3],[3,9,3],[3,16,3],[3,16,3][3,16,3][3,16,3][3,16,3],[3,9,3],[3,12,3],[3,1,8,1,3],[4,2,10,2,3],[4,25],[4,19,4],[5,17,5],[6,16,5],[6,12,7],[8,10,8],[8,8,10],[10,6,10]]

4 4                   3 4
2 1                   1 2
10 9 7 7 6 6 5 5  10 8 3 3 3 3 3 3 3 3 3 810   4 5 6 6 8 810
6 810141515171926 2 112 91616161616 912 1 2 41917161210 8 6
10 9 7 6 5 5 4 4 3 3 3 3 3 3 3 3 3 3 3 3 3 325 4 5 5 7 81011
+------------------------------------------------------------
30|
30|
30|
11 9|
9 6|
6 3 1 1 3 5|
4 3 1 1 3 3|
2 3 2 2 4 3|
2 6 5 4 1|
1 6 5 5 1|
7 5 6|
9 7 8|
30|
30|
30|
30|
30|
30|
28|
26 1|
1 7 1 5 1 6 2|
2 6 1 3 1 4 2|
2 5 1 3 1 4 3|
3 3 1 1 1 3 4|
4 3 1 3 4|
6 3 3 6|
8 8|
30|
30|
30|

## Solution

For those who are interested, here's the solution for the test cases.

5x5

1
2 1 2
3 2 1 2 3
+----------
3| . # # # .
2 2| # # . # #
1 1 1| # . # . #
2 2| # # . # #
3| . # # # .

10x10
1
1         1 2
2 1 2   3 2 1 2 3
3 2 1 2 3 1 7 1 2 3
+--------------------
3| . . . . . . # # # .
2 2| . . . . . # # . # #
1 1 1| . . . . . # . # . #
3 2 2| . # # # . # # . # #
2 2 3| # # . # # . # # # .
1 1 1 1| # . # . # . # . . .
2 4 1| # # . # # # # . . #
3 1 2| . # # # . # # . # #
4| . . . . . . # # # #
1| . . . . . . # . . .

30x30
Hope you'll like it, it took me a lot of time :)
4 4                   3 4
2 1                   1 2
10 9 7 7 6 6 5 5  10 8 3 3 3 3 3 3 3 3 3 810   4 5 6 6 8 810
6 810141515171926 2 112 91616161616 912 1 2 41917161210 8 6
10 9 7 6 5 5 4 4 3 3 3 3 3 3 3 3 3 3 3 3 3 325 4 5 5 7 81011
+------------------------------------------------------------
30| # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
30| # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
30| # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
11 9| # # # # # # # # # # # . . . . . . . . . . # # # # # # # # #
9 6| # # # # # # # # # . . . . . . . . . . . . . . . # # # # # #
6 3 1 1 3 5| # # # # # # . . # # # . . # . . . # . . # # # . . # # # # #
4 3 1 1 3 3| # # # # . . . # # # . . . # . . . # . . . # # # . . . # # #
2 3 2 2 4 3| # # . . . . # # # . . . . # # . # # . . . . # # # # . # # #
2 6 5 4 1| # # . # # # # # # . . . . # # # # # . . . . # # # # . . . #
1 6 5 5 1| # . . # # # # # # . . . . # # # # # . . . . # # # # # . . #
7 5 6| . . # # # # # # # . . . . # # # # # . . . . # # # # # # . .
9 7 8| . # # # # # # # # # . . # # # # # # # . . # # # # # # # # .
30| # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
30| # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
30| # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
30| # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
30| # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
30| # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
28| . # # # # # # # # # # # # # # # # # # # # # # # # # # # # .
26 1| . . # # # # # # # # # # # # # # # # # # # # # # # # # # . #
1 7 1 5 1 6 2| # . . # # # # # # # . # . # # # # # . # . # # # # # # . # #
2 6 1 3 1 4 2| # # . # # # # # # . . # . . # # # . . # . . # # # # . . # #
2 5 1 3 1 4 3| # # . . # # # # # . . # . . # # # . . # . . # # # # . # # #
3 3 1 1 1 3 4| # # # . . . # # # . . # . . . # . . . # . . # # # . # # # #
4 3 1 3 4| # # # # . . . # # # . . . . . # . . . . . # # # . . # # # #
6 3 3 6| # # # # # # . . # # # . . . . . . . . . # # # . # # # # # #
8 8| # # # # # # # # . . . . . . . . . . . . . . # # # # # # # #
30| # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
30| # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
30| # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
60x60
Not completed, not tested

60| # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
6 3 1 1 335| # # # # # # . . # # # . . # . . . # . . # # # . . # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
6 3 1 1 3 6 6 5 5 1| # # # # # # . . # # # . . # . . . # . . # # # . . # # # # # # . . # # # # # # . . . . # # # # # . . . . # # # # # . . #
647| . # # # # # # . . . . . . # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
5 1 1 3 2 1 4| # # # # # . . . . . . . . . . . . . . . . # . . . . . . . . . . . . . . . . . . . . # . # # # . # # . # . . . . # # # #
1 2 1 2 2 1 4| . # . # # . . . . . . . . . . . . . . . . # . . . . . . . . . . . . . . . . . . . . . . . # # . # # . # . . . . # # # #
1 2 1 2 1 3| # . . . # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . # # . # . . . . . # # #
2 2 1 1 2| # # . . # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # . . # . . . . . . . . # #
3 2 2| # # # . # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # #
3 2 1| # # # . . # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #
3 3 1| . # # # . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #
1 8| # . # # # # # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1 4 4 1| # . # # # # . # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #
1 3 2 2| # . # # # . . . . # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # #
1 3 2 1| # . . # # # . . . . # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #
2 4 3 1| # # . # # # # . . . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # .
4 3 3 2| # # # # . # # # . . . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # #
3 4 3 1| . # # # . . # # # # . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #
1 3 8| # . # # # . # # # # # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
1 3 1 5 1| # . # # # . # . # # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . #
1 5 4 2| # . # # # # # . # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # #
2 4 2 3 2| # # . # # # # . # # . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # .
2 2 2 1 3 2 1| # # . # # . # # . # . . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # . #
1 2 2 1 3 2 2| . # . # # . # # . # . . . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # . # #
3 1 2 2 4 2 2| # # # . # . # # . # # . # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # . # # .
3 1 2 4 3 2 2 1| # # # . # . # # . # # # # . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # . # # . #
1 2 2 3 2 3 2 2 2| # . # # . # # . # # # . # # . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # . # # . # #
1 2 2 3 2 3 2 2 2| # . # # . # # . # # # . # # . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # . # # . # # .
4 2 6 4 2 2 2 1| # # # # . # # . # # # # # # . # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # . # # . # # . #
6 6 4 2 2 2 2| . # # # # # # . # # # # # # . # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # . # # . # # . # #
3 3 2 3 5 3 2 2 2| # # # . # # # . # # . # # # . # # # # # . . . . . . . . . . . . . . . . . . . . . . . . . . . . # # # . # # . # # . # #
1 1 3 2 6 3 4 2 2 2| # . # . # # # . # # . # # # # # # . # # # . . . . . . . . . . . . . . . . . . . . . . . . . . # # # # . # # . # # . # #
1 5 2 2 1 1 3 2 2 2 2 1| # . # # # # # . # # . # # . # . # . # # # . . . . . . . . . . . . . . . . . . . . . . . . . # # . . # # . # # . # # . #
1 3 1 2 2 1 1 4 3 2 2 2| # . # # # . # . # # . # # . # . # . # # # # . . . . . . . . . . . . . . . . . . . . . . . # # # . . . # # . # # . # # .
1 3 1 2 2 3 4 4 2 2 2| # . # # # . # . # # . # # . # # # . . # # # # . . . . . . . . . . . . . . . . . . . . . # # # # . . . . # # . # # . # #
1 1 1 1 2 2 3 4 2 2 2 2 1| # . # . # . # . # # . # # . # # # . . # # # # . . . . . . . . . . . . . . . . . . . . # # . . # # . . . . # # . # # . #
3 6 2 4 1 3 3 2 2 2| # # # . # # # # # # . # # . # # # # . # . # # # . . . . . . . . . . . . . . . . . . # # # . . . # # . . . . # # . # # .
2 2 3 2 4 1 4 4 2 2 2| . # # . # # . # # # . # # . # # # # . # . # # # # . . . . . . . . . . . . . . . . # # # # . . . . # # . . . . # # . # #
2 2 3 2 1 1 1 4 2 2 2 2 1| # # . . # # . # # # . # # . # . . # . # . # # # # . . . . . . . . . . . . . . . # # . . # # . . . . # # . . . . # # . #
2 6 2 1 2 1 2 3 3 2 2 2| # # . . # # # # # # . # # . # . # # . # . # # . # # # . . . . . . . . . . . . # # # . . . # # . . . . # # . . . . # # .
4 5 4 2 1 1 3 4 2 2 2| # # # # . # # # # # . # # # # . # # . # . # . . # # # . . . . . . . . . . . # # # # . . . . # # . . . . # # . . . . # #
3 5 4 2 1 1 2 2 2 2 2 1| . # # # . # # # # # . # # # # . # # . # . # . . # # . . . . . . . . . . . # # . . # # . . . . # # . . . . # # . . . . #
8 4 4 1 2 1 2 2 2 2 1| # # # # # # # # . # # # # . # # # # . # . # # . # . . . . . . . . . . . # # . . . . # # . . . . # # . . . . # # . . # .
3 4 1 2 4 1 3 2 2 2 2 2| # # # . # # # # . # . # # . # # # # . # . # # # . . . . . . . . . . . # # . . . . . . # # . . . . # # . . . . # # . # #
3 6 2 4 1 6 4 2 2 2 1| # # # . # # # # # # . # # . # # # # . # . # # # # # # . . . . . # # # # . . . . . . . . # # . . . . # # . . . . # # . #
3 6 2 4 1 4 2 2 2 2 2 2 1| # # # . # # # # # # . # # . # # # # . # . # # # # . # # . . . # # . # # . . . . . . . . # # . . . . # # . . . . # # . #
3 6 2 4 1 5 1 1 3 2 2 2 1| # # # . # # # # # # . # # . # # # # . # . # # # # # . # . . . # . # # # . . . . . . . . # # . . . . # # . . . . # # . #
3 6 2 4 1 212 2 2 2 1| # # # . # # # # # # . # # . # # # # . # . # # . # # # # # # # # # # # # . . . . . . . . # # . . . . # # . . . . # # . #
3 6 2 4 1 2 1 1 3 2 2 2 1| # # # . # # # # # # . # # . # # # # . # . # # . # . . . . # . . . . # # # . . . . . . . # # . . . . # # . . . . # # . #
3 6 2 4 1 4 1 4 2 2 4| # # # . # # # # # # . # # . # # # # . # . # # # # . . . . # . . . . # # # # . . . . . . # # . . . . # # . . . . # # # #
3 6 2 4 1 4 1 2 2 2 2 4| # # # . # # # # # # . # # . # # # # . # . # # # # . . . . # . . . . # # . # # . . . . . # # . . . . # # . . . . # # # #
3 6 2 4 1 4 1 2 2 2 2 3| # # # . # # # # # # . # # . # # # # . # . # # # # . . . . # . . . . # # . . # # . . . . # # . . . . # # . . . . # # # .
3 6 2 4 1 4 1 2 2 2 2 4| # # # . # # # # # # . # # . # # # # . # . # # # # . . . . # . . . . # # . . . # # . . . # # . . . . # # . . . . # # # #
3 6 2 4 1 4 1 2 2 2 2 2 1| # # # . # # # # # # . # # . # # # # . # . # # # # . . . . # . . . . # # . . . # # . . . # # . . . . # # . . . . # # . #
3 6 2 4 1 4 1 2 2 2 2 2 1| # # # . # # # # # # . # # . # # # # . # . # # # # . . . . # . . . . # # . . . # # . . . # # . . . . # # . . . . # # . #
3 6 2 4 1 4 3 2 2 2 2 2 1| # # # . # # # # # # . # # . # # # # . # . # # # # . . . # # # . . . # # . . . # # . . . # # . . . . # # . . . . # # . #
3 6 2 4 1 4 1 1 1 2 2 2 2 2 1| # # # . # # # # # # . # # . # # # # . # . # # # # . . # . # . # . . # # . . . # # . . . # # . . . . # # . . . . # # . #
3 6 2 4 1 4 2 1 2 2 2 2 1 2 2 1| # # # . # # # # # # . # # . # # # # . # . # # # # . # # . # . # # . # # . . . # # . . . # # . . # . # # . . . . # # . #
3 6 2 4 1 4 2 1 2 2 2 2 1 2 4| # # # . # # # # # # . # # . # # # # . # . # # # # . # # . # . # # . # # . . . # # . . . # # . . # . # # . . . # # # # .
3 6 2 4 1 4 2 1 6 4 412| # # # . # # # # # # . # # . # # # # . # . # # # # . # # . # . # # # # # # . # # # # . # # # # . # # # # # # # # # # # #

## Winning criteria

Puzzle solving might be long, who will find the best heuristics? Who will find the best implementation? Fastest code will win (code will be running on my computer, i5-4440, and must not use more than 4GB of RAM). You'll be scored using the 60*60 nonogram sandbox note : have to be added. Other test cases are here to help you while developing your submission. If there's a need of a Tie-breaker, i'll provide more complex test case (maybe a 90*90?)

## Sandbox

I have two questions for the sandbox :

• Do I need to put more explanations?

• Is there too much grammar/others faults? (I'm not native, sorry :()

As suggested by @steveverrill, I changed it to a fastest-code contest, some basic things changed. It makes much more sense, thanks.

I added the first part of the 60x60 nonogram, still have to form the array, and do the columns. I know it is ugly, but I wasn't able to come with a nice one which would be viable AND long to solve. T

• You really need some time limit on this, and for a specified size. "don't try to brute force it" is vague. The shortest-code way of solving this will be to try every possible combination of 0's and 1's and check. That will take less than a second for example 1, a lifetime for example 2, and something like the current age of the universe for example 3. There are other marginally less naive ways of doing it, like generating all possible rows then checking the colums, which will also take too long. I'd go as far as to say this might go better as fastest code (largest example solved in 1 minute.) – Level River St Jun 16 '15 at 13:55
• Did you make that batman yourself? Are you sure it's the only valid solution? (doesn't matter so long as you specify that the program can terminate when it finds any valid solution.) Note that a human will immediately note the completely full rows and the (near) symmetry, which it will make it easier, while a computer will not. – Level River St Jun 16 '15 at 14:00
• @steveverrill I was thinking of 2~3 minutes for the 30*30 one, I don't want it to take some billion years :). But I'll take your fastest code in consideration, as it may have more sense, and could be interesting to see what people will bring. – Katenkyo Jun 16 '15 at 14:25
• @steveverrill Yes I did, and there shouldn't be any other solution. But as per the rules of a nonogram, any solution satisfying lines/columns is a good one, just less prettier than the intended one. Using symettry is useless to solve this one. I solved it only using the "30 is length of the row, I fill", "27 2 means w+27+x+2+y=30, 30- 27+2=29 so w=y=0 and x=1" plus an other strategie designed as "simple boxes" on the wikipedia page. This is the basic movement a beginner learn, and they shouldn't be hard to code them as they can be done line-by-line and column-by-column – Katenkyo Jun 16 '15 at 14:30
• Are you sure your 30x30 has only one solution? – Sparr Jun 16 '15 at 15:15
• @Sparr I'm still testing to find other ones, but I can't find an other one – Katenkyo Jun 16 '15 at 16:44
• I see you're aware fastest code means you must take reponsibilty for running the code. Score should either be: 1. time to solve a given grid size, or 2. max (square?) grid size solved in a given time. simply "fastest code" is not enough. The trouble with 1 is you've no idea how long it will take (see meta.codegolf.stackexchange.com/q/5360/15599). The trouble with 2 is you may have to define additional grids, but I think that's preferable over 1. Users can time themselves on the test cases to give an idea of the winner - probably there will be vast differences in timing.. – Level River St Jun 16 '15 at 19:40
• @steveverrill I'm going for 2., surely with a 60*60 or 70*70 grid (would be hard to design a greater one). I think it has enough cells to see who's the best. If not, i'll push myself into a 90*90 one. – Katenkyo Jun 17 '15 at 7:05
• According to Wikipedia this problema is NP-hard. That means grid size will have a massive impact on time. It's not at all clear whether 30x30 will run in reasonable time. If you want to score by time to complete a certain grid, I suggest you start with the smallest grid, eliminate all entries that run a measurable time (say 1 second) slower than the leader, then proceed to do the same with larger and larger grids until only one entry remains. That way you can avoid the problem of timings that are ridiculously fast or ridiculously slow. It also means the entries get tested on a variety of grids – Level River St Jun 17 '15 at 9:07
• Oops- just seen the new note about "solveable without any guess"! If anyone encodes an algorithm for that (I'm guessing a máximum of 2 people will do that, it's easy for a human to do but quite difficult to code) it should run very fast. If it is guaranteed that no guessing is required this becomes quite a different challenge. Is it guaranteed? – Level River St Jun 17 '15 at 9:16
• @steveverrill I might try to code a submission, to see how much time it would take. It could be used by others as a scale to see how far they are from it. A real nonogram must be solved by logic only. It can be complicated logic (while you predict what 2+ boxes placed would do on the board(depth-reasoning)). I don't think I'll be able to prove that point, but I tried for those 3 every way I could to solve them, and each time no guesses were needed. That's the reason it is long to design one ^^'. – Katenkyo Jun 17 '15 at 9:23
• The challenge is currently self-contradictory, asking "Who will find the best heuristics?" but promising "they are all solvable using basic techniques." If it is going to be a fastest-code and not a code golf, then the puzzles should be as difficult as possible. – feersum Jun 18 '15 at 22:26
• @feersum The fact they are all solvable by basics is because it was initially a code-golf. The 60*60 I'm designing will be a bit more trickier to solve, and I might prepare a 40*40 as an intermediate tricky case. But yeah, thanks for denoting this fact, I might have forgotten. – Katenkyo Jun 19 '15 at 7:12
• i know this game and i cant solve it another way aside bruteforce, sorry but i thnk this challenge wouldnt give desired results – Abr001am Jun 25 '15 at 10:50

# 4-Way Intersection Simulator

Consider an intersection as follows:

Cars will drive up any of the above Input lanes, and will exit out of any of the 3 other Output lanes. The goal is to take the list of cars, their arrival time, and their destination, and to return the times they will exit the intersection.

We will measure the time that it takes a car to cross an intersection as 1 Tick. We will assume that the time it takes for a car to approach and leave the intersection to be 0 ticks.

Each input acts as a queue of cars. Each tick, the car that has been at the front of its respective lane the longest will cross the intersection in his respective direction.

# Priority

If multiple cars have been waiting for the same amount of time, the rightmost car has priority. If there are 2 cars that are on opposing sides, they will both cross at the same time (as described below), unless only one of them is turning left. If that is the case, the car not turning left will have priority. Two cars may turn left at the same time. If there are 4 cars that arrive at the same time, the car in Input 1 will have priority.

After the car to cross has been chosen, other cars may cross at the same time, assuming their paths don't cross. Priority is given to the lane directly across from the crossing car, then to the car to right, then to the car to his left.

# Input/Output

Input will be a list of cars. Each car will be passed as a tuple containing the cars' unique ID, arrival time, arrival lane, and destination lane. The arrival lane will never be the destination lane.

Your program should output a list of cars, where each car is a tuple containing the cars' unique ID and the time it reaches its destination.

I don't care if the input format exactly matches the examples below. What I do care is that you input a list of tuples/lists and output a list of tuples/lists.

# Examples

[(0, 5, 2, 3)] -> [(0, 6)]
Car 0 arrives in lane 2 at tick 5.  He leaves in lane 3 at tick 6

[(0, 3, 1, 3), (1, 3, 3, 1)] -> [(0, 4), (1, 4)]
Car 0 and 1 arrive in lanes 1 and 3 at tick 3.  They both leave at tick 4.

[(0, 0, 3, 1), (1, 0, 4, 2), (2, 1, 4, 2)] -> [(0, 2), (1, 1), (2, 3)]
Car 0 and 1 arrive in lanes 3 and 4.  Their paths intersect, so car 1 leaves first
because it is the rightmost car.  The next tick, car 2 arrives, but car 0 has been
waiting the longest, so car 0 leaves next.  Finally, car 2 leaves at time 3.

[(0, 0, 1, 2), (1, 0, 2, 3), (2, 0, 3, 4), (3, 0, 4, 2)] -> [(0, 1), (1, 3), (2, 1), (3, 2)]
All four cars arrive at the same time.  Car 0 has the priority as it is in Input 1.
Car 2 is directly across from it, and both are turning left, so they cross at the same
time.  Car 1 is turning left, so car 3 will cross next, followed by Car 1.

[(0, 0, 1, 4), (1, 0, 2, 1), (2, 0, 3, 2), (3, 0, 4, 3)] -> [(0, 1), (1, 1), (2, 1), (3, 1)]
All four cars arrive at the same time, all are turning right, so all leave at tick 1.

[(0, 0, 1, 3), (1, 0, 4, 2), (2, 0, 3, 2), (3, 1, 1, 4), (4, 1, 4, 1), (5, 1, 2, 1), (6, 2, 3, 4), (7, 2, 1, 3), (8, 3, 1, 4), (9, 3, 4, 2), (10, 3, 3, 2)] -> [(0, 1), (2, 1), (1, 2), (3, 2), (5, 2), (6, 3), (4, 4), (10, 4), (7, 5), (9, 6), (8, 6)]
Car 2 is the rightmost, and has priority.  Car 0 is also able to cross at Tick 0
Car 1 has now been waiting the longest, and has priority.  Both Car 3 and 5 are able to
cross as well.  Car 4 was waiting behind Car 1, and so Cars 4, 6, and 7 arrive at the
same time.  Car 6 is the rightmost, so he exits at tick 3 while cars 8-10 arrive.
Car 4 is the next rightmost, so he makes his turn next, while Car 10 makes his right turn.
Car 7 finally has his turn, and crosses.  Car 8 is behind Car 7, and Car 9 intersects with
Car 7, so neither cross at the same time, but both are able to cross the next tick.

# Black and White Morphing

Given two black and white images, the goal is creating a animated black and white gif that transforms one image into the other and back.

The catch is, that for all frames the number of black pixels (as well as the number of white pixels, obviously) stays the same. You can assume that the two input images have the exact same size and the exact same number of black pixels.

### Discussion

@PeterTaylor suggested making the restrictions that from one frame to the next you can only swap adjecent pixels. Otherwise this challenge would be almost the same as this one, so we need a further restriction.

My goal is enforcing a 'slow' transition that can produce nice effects. One way of picturing that was considering the white pixels as fluid or sand that has to be rearranged step by step into the other image.

@trichoplax suggested making the limit that e.g. only 5% of the pixels may change in each transition.

### Test Cases

This is a first series of test cases, all 320x386px and 33844 white pixels.

• Is the stark contrast how you want to the challenge to look, or just what you happen to have at the moment? How would you feel about including dithered images that use the same number of white pixels as these but give the impression of grayscale, and make more detail visible in the currently pure black and pure white regions? – trichoplax Jun 20 '15 at 21:04
• Would it provide more challenge and more variety to include more than one value for number of white pixels? Perhaps the same 5 images could be provided in 3 categories: black heavy, white heavy and balanced. Then the results for each category can be shown so we can judge whether a given technique gives good results across the board. – trichoplax Jun 20 '15 at 21:07
• Of course there should be more series, and I like your suggestion of black heavy, white heavy and balanced. My idea way that people should come up with creative transitions from one image to the other and back, I imagined something like the 'powerponit' slide transitions. The images are black and white only for making the challenge somewhat easier. – flawr Jun 20 '15 at 21:09
• I like the restriction to black and white only. I don't necessarily think it makes it easier, but I think restriction is very important for popularity contests otherwise they get too open ended. It might be worth adding more restriction otherwise it risks being closed as too broad. For example, you might restrict how much difference there can be from one frame to the next. Maybe only 5% of pixels can change each frame (or whatever percentage you feel is best). You might feel that particular restriction detracts from some potential solutions so that's just an example. – trichoplax Jun 20 '15 at 21:31
• The answers to this question might have some useful code for creating nice dithered images for your sample images. It converts greyscale to strictly only black and white. – trichoplax Jun 20 '15 at 21:55
• It might be worth thinking up a few examples of transition effects and then adding restrictions that don't rule out any of the effects you thought of. To make it an interesting challenge but without losing potential answers. – trichoplax Jun 20 '15 at 21:56
• For example, the effect of paint running down from the top of the picture overwriting the old picture with the new. – trichoplax Jun 20 '15 at 21:57
• Or a simple slide across (with or without the old image moving too). – trichoplax Jun 20 '15 at 21:58
• Or "burn through" from a hole appearing in the centre, like old cinema projectors if left on one frame too long. – trichoplax Jun 20 '15 at 21:59
• Cf codegolf.stackexchange.com/q/33172/194 , although the morphs there don't preserve the number of pixels of each colour in the intermediate frames. At present I would vote to close this as too broad, and suggest adding a restriction that in each frame the changed pixels must pair up into adjacent pairs which swap with each other. – Peter Taylor Jun 20 '15 at 22:01
• @PeterTaylor I was aware of that challenge (I did even participate=), but I did not realize that this one would be so similar to the other one. I really like your idea of the swapping restriction, but I am not sure whether this is perhaps too restrictive. Another idea I had (very vague so far) is considering the white pixels as some kind of 'fluid' that can only move with a certain velocity (or another property) and your suggestion would really match that idea. The question is for each frame transition, should we limit the number of swaps? Or the number of swaps per pixel? – flawr Jun 21 '15 at 10:04

# Find the maximum of ax+b online

You are given a list of (a,b), and a list of x. Compute the maximum ax+b for each x. You can assume a, b and x are non-negative integers.

But this time, items in the list are added dynamically. Your program should support the following operations (you can rename the operations if that's convenient):

• Add a,b, to insert (a,b) into the list.
• Query x, to find the maximum ax+b in the current list, with the given x.

Your program or function must run in expected (to the randomness if your code involves that, not the input) O(nlogn) time where n is the total input length (or total number of operations).

You can write a complete program, a function, a list of functions or methods doing each operation, or a function taking one operation each time. For the later two cases, you can either return or print the result after each operation, or add an "output" operation, or output automatically when the program ends.

### Examples

This is code-golf. Shortest code wins.

If you used a builtin having a good average-case complexity, and it can be randomized to get the expected complexity easily in theory, you can assume your language did that.

That means, if your program can be tested to be O(nlogn) (in theory), with edge cases for your code, but not the implementation of your language, we'll say it is O(nlogn).

• Can we assume our language's built-in sorting is O(n lg n)? – xnor Mar 5 '15 at 2:58
• @xnor Usually they are O(n lg n). But if you meant some language with a built-in sorting function not in O(n lg n) (or nobody is bothered to check the real complexity), I'm not sure. Strictly speaking they may be not in O(n lg n) and invalid. But it seems nobody is downvoting or deleting those answers. – jimmy23013 Mar 5 '15 at 4:38
• @user23013 They are very rarely O(n log n). Most languages implement quick sort, which is O(n log n) on average but has a worst case complexity of O(n^2). That being said, I'd always include a statement along the lines "you may assume that your language's built-in sorting function runs in O(n log n)". – Martin Ender Mar 6 '15 at 21:10
• @MartinBüttner Allowed expected complexity. Is it better now? – jimmy23013 Mar 7 '15 at 2:06
• I don't know... it just seems unnecessarily complicated to me and puts some esolangs at a disadvantage that might have a naive sort implementation, but ultimately it's your call. – Martin Ender Mar 7 '15 at 2:09
• @MartinBüttner Do you have ideas about the stronger version (allowing inserting (a,b) dynamically)? I'm trying to make it consistent. And esolangs can answer the convex hull question anyway. – jimmy23013 Mar 7 '15 at 2:41
• @user23013 I don't think I'm qualified to have an opinion about the stronger version. ;) – Martin Ender Mar 7 '15 at 3:02

# Diffusion Battle

## Overview

Players are all present on a toroidal grid. Each player has 16 particles to start with. The total number of particles is fixed but they can change colour. Each turn a player decides what type of action to take for each particle of their colour, but cannot control the direction, which is always random.

All players' particles then move in a random direction at the same time, possibly resulting in some of them changing colour. The player with the most particles of their colour at the end of the game is the winner.

## Action types

A player chooses from the following actions for each particle:

• Drift: do not attempt to change the colour of other particles
• Eat: attempt to change the colour of other particles

Each of these actions is applied after all players' particles have aimed in a random direction. This may result in two particles aiming for the same cell. No cell will end up with more than one particle, but aiming for the same cell results in interaction, with no movement and the following rules being applied:

• If both particles chose Drift, nothing happens.
• If both particles chose Eat, nothing happens.
• If one particle chose Eat, the particle that chose Drift will become the colour of the particle that chose Eat.

Clearly choosing Eat is always an advantage when two particles aim for the same destination. However, if a particle aims for a cell that no other particle is aiming for, it will move there, with the following rules being applied:

• If the particle chose Drift it will move with no change.
• If the particle chose Eat it will move and take on a random colour (which may be its own colour or that of any other player).

### N particles colliding

The case where N particles are all aiming for the same destination cell is a generalisation of the case for 2 particles. None of them will move to the destination cell and the following rules will be applied:

• If all of the N particles chose Drift, nothing happens.
• If all of the N particles chose Eat, nothing happens.
• If some chose Drift and some chose Eat, none will move and all those that chose Drift will change to a colour chosen randomly from those exhibited by those that chose Eat. If there is more than one particle of a given colour that chose Eat, that colour will have a correspondingly higher probability of being chosen.

When N = 2 this reduces to the case described for 2 particles.

It follows that if the N particles are of the same colour, then regardless of their individual choices none will move and they will all remain the same colour.

### Collision with a particle that was unable to move

What happens to particles that were aiming for an empty cell but the cell is not empty because its occupant was unable to move?

# Sandbox thoughts

EITHER

• ALL THOSE THAT AIMED FOR THE SAME CELL AFFECT EACH OTHER

OR

• THOSE THAT AIMED FOR THE SAME CELL DO NOT MOVE, ALL THOSE THAT END UP ADJACENT AFFECT EACH OTHER

I favour the second but I need to consider how it would work with large numbers of particles adjacent.

• Zgarb pointed out in chat that it would be better to have a small probability of changing if failing to eat, so that the penalty for failure is not so extreme. I'm likely to use this as it is fine tunable.

# Minimum? Vertex Cover

<insert definition of (minimum) vertex cover here>

Given a graph, you must output a valid vertex covering of that graph. The entry with the smallest total size (number of vertices) over five test cases (TBD) wins.

### Input

Your program will be run with one argument given: a file name. For example:

python findacover.py graph_1.txt

Submissions will read the graph from the file specified. The format of the file will be:

5
0:1 2 3
1:0 3
2:0
3:0 1 4
4:3

The first line is simply the number of vertices in the graph (V). The next V lines are the list of vertices. Each line consists of the vertex number and a colon, followed by a space-separated list of vertices connected to that vertex by an edge.

Note that each edge will be listed twice, once for each vertex it connects. You can see in the example that the edge connecting 1 and 3 is present on the line for both vertices.

### Output

Output is simply a list of vertices that represent a valid vertex covering of the input graph. Output should be written to STDOUT (so my validator can score it.

I will strip all non-digit, non-space characters ([^0-9 ]) from your output and interpret the remainder as a space-separated list. For example, outputs [0, 1, 2, 3] and 0 1 2 3 will be treated the same.

For the example graph above:

Valid:

0 1 2 3 4

or

0 3

among others.

Invalid:

0 1 2

This does not cover the graph, since the edge between 3 and 4 is not covered.

### Rules

• Submissions will be run once for each graph.
• You have a time limit of five minutes for each graph. You cannot "roll over" unused time to the next graph. This time is clocked on my computer, an i7-3770K CPU with 16GB RAM, running Ubuntu 14.04. If you might bump against this limit, make sure you send a "best-yet" output before time is up.
• Feel free to use multiple threads, but keep it on the CPU. My graphics card is not your playground.
• Your submission must be deterministic. If you use a PRNG, seed it with a constant value.
• You cannot use any built-in or third-party function designed to solve vertex covering problems.
• Standard loopholes apply. This means (for example) that you cannot hardcode your submission to these test cases. If I choose five more test cases to run, you should get comparable (obviously not exact) results.

### Scoring

Your score is the number of vertices in your cover. If you return anything except a valid covering, or do not return anything within the time allotted, your score for the graph will be 200000.

Score is summed over five test cases, each consisting of a graph with 20k to 100k vertices. The lowest total score wins.

<insert generator/validator/scorekeeper here>

### Sandbox

• Does the "function designed to solve vertex covering problems" need to be better specified? If so, how could I word that?
• Are the graph sizes and time limits reasonable? They are designed to prevent a straight brute-force attack, but I don't believe they are too large to prevent a good approximation. Are they too small?
• "Function designed to solve NP-complete problems?" Not sure, but I'm assuming you also want to rule out equivalent things like independent set. – Sp3000 Jun 27 '15 at 6:28

# Be the shortest in your own standard

This was cops-and-robbers at the beginning. But I'm thinking of changing it to a user scored challenge instead, where each user can propose a limit number of regex, and for each regex, the shortest matched program gets one point.

Working in progress. More details to be added

In each answer, you should write a program with length n for the above task, and optionally a regex with no more than n/2 bytes.

The regex should consist of only character literals (including escaped ones) and [...] (...) ? * + |. You cannot use other features such as specifying number of repetitions or the beginning/ending anchors.

If you choose to include a regex, you should also specify whether programs should be nearly-matched or nearly-unmatched by the regex, defined as following:

• A regex nearly-matches a program, if there is a character C and a subset S of the set of all occurences of C in the program, that when everything in S is replaced by a character C', the program will be matched by the regex.
• A regex nearly-unmatches a program, if for every character C and every subset S of all occurences of C in the program, that when everything in S is replaced by a character C', the program will not be matched by the regex.

If you choose to nearly-match, it must nearly-match your own program in the same answer. And this program must be shorter than any other answer nearly-matched by the regex. The same applies if you choose to nearly-unmatch, where your program must be shorter than anything nearly-unmatched.

The programs and regexes should only use printable ASCII, tabs and newlines.

Each user can write any number of programs, but can write at most 5 regexes at the beginning. You can write one extra regex for each 5 upvotes you get.

## Scoring

For each regex, if one of your program is the first of the shortest of the programs nearly-matched/unmatched by the regex according to the specification, you get 2 points. If the regex is not your own, you get one extra point.

Each of your program can be scored more than one times if they are the shortest for more than one regex.

You should not post an answer that doesn't get any score at the time you post it. But you can leave it there if it loses all the score it had. And you can post an answer that is only the shortest for your own regex.

You can always edit regexes into an answer, if you are allowed to write more regex. But once a program is the shortest for a regex at the time you post the regex, you can't post another regex that makes this version of the program shortest.

You should not edit a program in a way that it loses scores from some regex. And if you edit, you should keep the version that is paired with a regex in your answer.

Regexes should not be modified after posting for any reason if they are valid.

You should not post programs/regexes that is the same as a previous submission.

• @githubphagocyte It is the program + regexes. I left an m there when there was only one regex... – jimmy23013 Dec 27 '14 at 1:58
• This doesn't seem to prevent people from just writing the best-golfed program. Bowling doesn't seem to work either (and will be a duplicate of the bowler-golfer fraction war). I'll think about it later... Shouldn't post this when I'm sleepy... – jimmy23013 Dec 27 '14 at 3:14
• It seems to me that the two regexes will be one character each, or at worst three characters in total. – Peter Taylor Dec 27 '14 at 19:27
• @PeterTaylor You can comment out the string matching the regex. The rule about replacing a character literal is to make sure the comment character is always available. But I'm going to abandon this post anyway if I can't find a better winning criterion... – jimmy23013 Dec 28 '14 at 5:33

Inspired by the last question asking for the masses of the elements, this challenge will be slightly more specific. In this challenge, you will find the molar mass of a sequence of amino acid peptides.

Amino acids, of which there are 21, are the units that combine into chains and then bend and change shape to form proteins, which serve widely varying functions in cells and in the body of most all living organisms. Scientists working with peptides, such as chemists and doctors, can easily synthesize a desired peptide chain in the lab thanks to the powers of modern technology. After some purifying and such, he will have the desired sequence in the form of a white powder/crystal like substance.

However, this is science! This means that he will eventually need to weigh out a desired amount of his sequence to perform some reactions or tests. To do this, he needs to know its molar mass.

Today, we know that there are 21 amino acids, and we have found their molar masses and given them names and symbols, just like the 118 elements on the periodic table. They are as follows:

Name           Symbol   Molar Mass
Alanine         A        89
Cysteine        C        121
Aspartic acid   D        133
Glutamic acid   E        147
Phenylalanine   F        165
Glycine         G        75
Histidine       H        155
Isoleucine      I        131
Lysine          K        146
Leucine         L        131
Methionine      M        149
Asparagine      N        132
Proline         P        115
Glutamine       Q        146
Arginine        R        174
Serine          S        105
Threonine       T        119
Selenocysteine  U        169
Valine          V        117
Tryptophan      W        204
Tyrosine        Y        181

BUT WAIT!! (how do I make this text bigger?)

# But wait!!

Unlike the elements, the mass of a peptide sequence isn't just the sum of the masses of the constituent amino acids! Amino acids combine in a reaction called a hydrolysis reaction that forms a bond called a peptide bond. Take a look at this diagram:

A hydrolysis reaction is a reaction in which two large molecules combine to make a larger one, but in the process lose a small molecule. In this case, they lose a water molecule (hence the name hydrolysis). Since the mass of water is 18, when two peptides bond together in a chain they lose 18 molar mass units. So if our sequence was AC (Alanine-Cysteine), the mass would be 89 + 121 - 18 = 192.

The Challenge

Your job is to golf a program that computes the molar mass of a given peptide sequence. The sequence will be specified by their one letter symbols, in all caps.

Examples: A returns 89

AC returns 192

WAGAKRLVLRRE returns 1453

Shortest byte count wins, no loopholes. Weights must be hardcoded in the program somehow.

• I would estimate a greater than 50% chance that this would be closed as a near-enough dupe of codegolf.stackexchange.com/q/35599/194 . (Although I thought the same of the elements one, and I was wrong about that). – Peter Taylor Jun 27 '15 at 20:51
• @PeterTaylor Do you know how to make the text bigger? – Faraz Masroor Jun 28 '15 at 3:44
• No. I know how to create headers, but that's not the same thing. – Peter Taylor Jun 28 '15 at 7:07
• @FarazMasroor "(how do I make this text bigger?)" -- You mean as I did in my "mass of elements" post? Select the text you want to format as code and press CTRL+K. Alternatively, add 4 spaces before each line. – Spikatrix Jun 28 '15 at 11:42
• The protein synthesis reaction you show is an example of condensation. Hydrolysis would be the reverse reaction (which incidentally occurs during digestion of proteins.) – Level River St Jun 29 '15 at 18:27
• If it's the text "but wait!!" that you wanted to make bigger, I've edited to show the different header text sizes available - just delete the ones you don't want. – trichoplax Jul 3 '15 at 16:52
• I've also edited to make your table of molar masses a single block (without the white lines running across it). This is just to show you how - click "rollback" from the edit history if you don't like it. – trichoplax Jul 3 '15 at 16:56

# Fundamentals of City Planning

In this challenge, you are a city planner. You have been given an N by M rectangle to fill with residential lots of size K and roads of width 1. You know that money is made based on the number of residents in the city, so your goal is to maximize the number of lots in your rectangle. However, the following rules are enforced:

• Roads have a width of 1 square, and all roads must be orthogonally connected to each other.
• Every lot must share at least 1 side with a road
• Lots must all be the same size K. They can be in the shape of any polyomino of size K.
• There must be at least 1 road that touches the edge of the rectangle, as your residents need to be able to get in and out!

The winner of the challenge is the one that:

1. Fits the most lots across all of the below examples. In the case of a tie:
2. Fastest solution, unless multiple answers are running under a second. In that case:
3. The earliest posted solution

Submitted answers must run in under a minute.

# STDIO

You will be passed three integers, N, M, K. You need to output the generated grid. Roads should be represented by .. Lots should be ordered and numbered, and when printed should be represented by their number mod 10. The ordering can be arbitrary, and is simply used to distinguish lots on output. Empty squares are allowed and are represented by #.

# Test Cases for correctness

Provided solutions can be numbered differently, rotated, and/or reflected

1 2 1
.1

1 3 1
1.2

2 2 1
1.
2.

3 3 1
123
...
456

3 3 2
11#      11.      #11
2..  or  2..  or  2..
233      233      233

# Test cases used for scoring:

20 15 1
20 15 2
20 15 3
20 15 4
20 15 5
20 15 6
20 15 7
20 15 8
• 1. I got to the bit about lots being the same size K and wondered why I would choose K to be anything other than 1. Only when I got to the input spec did I understand. Adding "of size K" to the end of the second sentence would probably avoid that confusion. 2. Do you have a reference implementation? I'm worried that "fastest solution" might not be a good tiebreaker because on the given test cases the answers may execute in under 200ms. – Peter Taylor Jul 4 '15 at 6:52
• I updated, tell me if it looks reasonable? – Nathan Merrill Jul 4 '15 at 11:45
• Are answers required to be deterministic? – trichoplax Jul 4 '15 at 13:53
• @trichoplax no, but deterministic will probably lead to better results. Updated the description. – Nathan Merrill Jul 4 '15 at 14:46

# Overview

A cop spots a robber and the robber runs and ends up in a basement. The cop then goes into the basement and locks the door.

# Gameplay

The basement consist of 49 rooms with dimensions 7 x 7. The top-left room has coordinates [0,0] while the bottom-right room has coordinates [6,6]. The cop starts on the room with coordinates [6,3] while the robber starts on the room with coordinates [0,3].

Cop

The cop moves first. The cop can move in one of these directions:

• Up
• Right
• Down
• Left
• Here

The direction here indicates that the cop will stay in the current room and will not move. The rest of the directions are self-explanatory. The cop can move in a particular direction if it is a valid one, i.e, the cop cannot move out of the grid or move into a room with a trap.

The cop can also put traps in a room. At the start of every match, the cop has 3 traps. Once a trap has been placed, the cop will not be able to move into the room where the trap is placed.

The cop also has 3 pressure sensors at the start of every match. The cop can move into a room where a pressure sensor has been placed.

If the robber moves into an adjacent room of the cop, the cop will be alerted.

Robber

The robber can move in the same directions as the cop does. The robber too cannot move outside the grid.

The robber has two TrapDetector5000 which can be used by the robber. It will detect if there is a trap in one of the adjacent rooms that the robber is in.

If the cop moves into an adjacent room of the robber, the robber will be alerted.

Goal

The cop must catch the robber as soon as possible. This can be done by moving into a room where the robber is. The cop will also catch the robber if the robber moves into the room where the cop is.

If the robber moves into a room where the cop has placed a trap or a pressure sensor, the cop will be alerted and the robber will not be able to move for 2 turns, if the room had a trap. However, the robber will be able to move if the room had a pressure sensor.

The robber will be alerted if the robber steps into a room with a pressure sensor.

# Controller

The controller is written in java and can be found here. As a cop or a robber you each have to each complete implement a Java class.

You have to implement the Cop interface if you are writing a Cop Bot and implement the Robber interface if you are writing a Robber Bot.

There is an enum direction with 5 directions Here, Up, Right, Down, Left which you can use when building your Bot.

You can use the Grid.isValidMove(direction) to check if that direction is a valid move. This is for Cops.

You can use the Grid.isValidPosition(direction) to check if that direction is a valid move. This is for Robbers.

You also may write additional functions within that class. The controller comes with one working example of a simple cop and robber bot.

Please use java 7 and please do not exploit stuff in the controller and cheat.

Note that your bot needs to return an int from takeTurn within 200 milliseconds. Failure to do so will result in the disqualification of your Bot.

# Scoring

Each cop plays 10 rounds against each robber and the number of moves each robber makes in each round will be added up and this is the score of that particular robber. The same goes for cops.

The robber with the highest score and the cop with the lowest score wins!

• This KoTH has potential, I believe. I might expand the room to ensure that traps aren't an insta-catch. Also, if a cop moves into a room next to a robber, only the robber knows? (and vice versa)? If that is true, its going to hard to beat the robber strategy of "stand until a cop moves next to you" – Nathan Merrill Jun 27 '15 at 2:08
• First of all. Thanks for reviewing this KoTH. What size should the grid be? And "if a cop moves into a room next to a robber, only the robber knows? (and vice versa)?" -- Yes. Because this is different from those KoTHs where a turn means movement of both the players. Any idea for making it more interesting? – Spikatrix Jun 27 '15 at 8:15
• I'd say that a 7x7 would be sufficient. If I am caught in the center, it is still possible that the cop won't catch me if he is on the edge of the room. I'm not sure how to make it more interesting, but an idea I had would be to allow both the cop and robber to place "pressure sensors" instead of traps. Their party is informed when stepped on, but they don't know which sensor has been stepped on (unless there is only 1 they placed) – Nathan Merrill Jun 27 '15 at 11:52
• "Their party is informed when stepped on" -- Party? There is just one cop. Should there be more than one cop? – Spikatrix Jun 27 '15 at 11:59
• No. I just used party to refer to either cop or robber depending on who placed it. – Nathan Merrill Jun 27 '15 at 12:04
• I was thinking of cops having 2 traps + 4(?) pressure sensors. Also, I've been thinking of giving robbers something... like a dummy (moves in a straight direction and tricks the cops will be alerted if it is in an adjacent room) or one trap-detector-5000 (which detects if there if there is a trap in an adjacent room and can be used only once). What do you think? – Spikatrix Jun 27 '15 at 12:28
• I'm not sure about the dummy idea. I think that this challenge is about calculating probabilities of the enemy's location. I'd personally would prefer abilities to be purely knowledge granting, but that's my opinion. – Nathan Merrill Jun 27 '15 at 13:37
• @NathanMerrill I've written some code, but I don't think I'll post this. See the answer for more info. – Spikatrix Jul 7 '15 at 9:01

# Blackjack

## How to Play

Blackjack is for any number of people, but there will be only one in this case. The goal is to get as close to 21 as possible without going over. Aces will be 1 for this program. All other face cards are worth 10.

To start, the player is dealt two cards. They can then choose to hit (take another card) or stand. This repeats until they go over 21 (bust) or decide to stay.

If the player busts, their score is 0. Otherwise, their score is the total of all the cards.

## Input/Output

1. The program should output 2 "cards" (randomly choose between 2, 3, 4, 5, 6, 7, 8, 9, 10, K, Q, J, and A).
2. The player then inputs a move, stand or hit.
3. If he/she stands, output Final Score: [total of cards].
4. If he/she hits, output another "card". Output Bust! if the score is over 21.
5. Repeat steps 2-4 until the player busts or stands.

## Test Cases

Output: 5 K
Input:  hit
Output: 6
Input:  stand
Output: Final Score: 21

Output: A Q
Input:  hit
Output: 7
Input:  hit
Output: 6
Output: Bust!

## Rules and Other Notes

• Aces are always 1.
• Each output/input should be on a new line.
• Any trailing spaces and newlines are okay.
• Assume that all input will be valid. You don't need to notify the player of invalid input.
• You cannot read from a file or other source.

## Scoring & Submissions

• This is code golf. Shortest code in characters wins.
• How to win: post the shortest working code within one week.
• Please include the language, number of characters, and code. Explanations are appreciated, but not required.

Good luck!

## Sandbox Questions

Anything I'm forgetting? Does anything need more clarification?

• @TNT code-golf, game, card-games. I'll edit my post. – Nick B. Jul 11 '15 at 2:54

# roll me back a game of hearts

Roll me back a game of hearts
given just a deck of cards

So, I've been playing a game of hearts (https://en.wikipedia.org/wiki/Hearts) with three of my friends but I'm not entirely sure if all of them were playing perfectly according to the rules. So I'd like to replay the game with everyone's cards openly visible. And because you like algorithms, you offered me your help determining everyone's cards from the final deck after each hand. However, I can't quite remember if you promised me a full program or just a named function.

A card is represented with two characters. The first character represents its value and is one of 23456789TJQKA (2-10, jack, queen, king, ace). The second character represents its suit and is one of CDHS (clubs, diamonds, heards, spades).

The input is a list of 52 cards. It can either be a list (array, vector...) of two-character strings or a single space-separated string. You will be given the cards in the exact order they were played. The list represents a valid deck and 2C is the first card in the deck.

Output four sets of cards, each representing the starting hand of one player. The first set may correspond to any player but the rest must be ordered in the order of play (so if the first hand to be output is the third one to play, the rest must be in the order of fourth, first, second). The cards in each player's hand may be output in any order (it's a set). If you choose to output a single string, separate the cards in each hand with spaces and the hands with newlines.

Game rules:

Rules irrelevant to this challenge have been formatted in small font

• There are variants for three to six players but the base variant is for four players so let's assume this one.
• Before the main game each player passes three cards to another player. Since this is a lossy operation, let's just ask for the hands after this passing moment.
• Each game consists of 13 tricks. Each trick consists of each player in clockwise order playing one card from their hand, then one player "taking" the trick.
• The first trick starts by the two of club. Each subsequent trick is started by whichever player took the previous trick.
• The first player in a trick can play any card. The first player cannot play hearts unless hearts have already been played in that game or he has no other cards, however. The other players have to play the same suit as the leading player if they have that suit, otherwise they can play any card. Scoring cards cannot be played in the first trick
• The player that played the highest valued card of the same suit as the leading card of that trick takes that trick. E.G.: in 2C AD KC 5C, the king of clubs takes the first trick. In 2H KS AS QS the leading player takes the trick (and fourteen points).
• The objective of the game is to end up with the fewest points possible. A player gets one point per each hearts taken, and 13 poins for the queen of spades.

You may assume that the deck of cards is valid (exactly one of each card) and that the two of clubs has been lead. You may also assume that the rules concerning the order of play and trick taking have been followed. You may not assume the rules concerning which cards can be played when have been followed. Heck, you don't even know that I haven't been cheating. Because a player may have been dealt nothing but hearts, you may not even assume only non-scoring cards have been played in the first trick (if everyone on the planet plays 100 games in their life, this may realistically happen to someone).

Should I loosen the I/O requirements? How much?
Formatting advice? Which parts (if any) should I trim down? What needs to be clarified?
Anything else?

• So the program you're asking me to write can actually ignore most of the rules of Hearts and I can think purely in terms of a no-trump game in any whist-like game? – Peter Taylor Jul 13 '15 at 12:13
• @PeterTaylor Correct. Spades does have trumps, however, and hearts is the only other whist-like game I've played. – John Dvorak Jul 13 '15 at 12:17

# How to Create a Dating Website

Dating websites make lots of money. You want lots of money, so you're going to make a dating website. However, we all know that the most important part of any dating website is the algorithm, so you need to build that first.

When your customers will sign up, they are going to fill out a short survey describing themselves*. On the survey, they filled out personal interests, personality traits, and other important data for you to process using your algorithm.

Your algorithm must then accept two things:

1. A list of people, where each person has a list of traits
2. A list of trait pairs (A, B), where each pair has a score S. A trait pair matches a couple if one of them has trait A, and the other has trait B. The score can be negative. If A and B are different, and both people have both of the traits, then the score is doubled.

Your algorithm must then output a list of couples. Each person must be included in a couple exactly once, and only two people is allowed in each couple**. Your score is the sum of each couple's score. A couple's score is the sum of each of the trait pairs they match.

# Input/Output

Input is given as shown in the following example. Ignore the # comments

4         # Number of customers
1,3,5,7   # Customer 1's list of traits
1,2,4,5,6 # Customer 2's list of traits
1,6,7     # Customer 3's list of traits
1,2       # Customer 4's list of traits
4         # Number of trait pairs
1,2,-2    # Trait 1 and 2 give a score of -2
1,6,4     # Trait 1 and 6 give a score of 4
2,3,-4    # Trait 2 and 3 give a score of -4
6,6,5     # Trait 6 and 6 give a score of 5

Let's say you output:

2,3 1,4

Then that would match Customer 2 to 3 and 1 to 4.

If we look at 2,3, they match:

• The first trait pair, because Customer 3 has Trait 1, and Customer 2 has Trait 2
• The second trait pair, because they both have Traits 1 and 6. (This means double the score)
• The fourth trait pair, because they both have trait 6. However, because the trait pair only references 1 trait, we don't double the score.

Adding it all up, we get -2 + 4*2 + 5 = 11. The other couple scores -2 + -4 = -6, so the final score is 11 + -6 = 5.

The person who generates the highest scoring pairing wins the challenge. In the case of a tie, the program that generates it the fastest wins. If programs are generating the answer in under a second, then the earliest posted answer wins.

Question: I'm planning on doing 10K people, 500 traits, an average of 50 traits per person, and 5K trait pairs. I'm doing large numbers because I want efficient algorithms, but I want to know if the numbers are feasible

*They clicked a check box saying that they didn't lie, so we know that the survey is accurate

**You can assume everybody is a hermaphrodite

• FYI there's a well-known polynomial-time algorithm. – feersum Jul 13 '15 at 4:25
• @feersum, that's for weighted matchings in bipartite graphs. This is maximum weight matching in a complete graph, for which the well-known polynomial-time algorithm is Edmond's blossom algorithm. PS Nathan, if you don't want a debate about your cover story, you should probably specify that this dating site is aimed specifically at bisexuals. – Peter Taylor Jul 13 '15 at 6:08
• ... or hermaphrodites. Poor snails, perpetually being asked about their gender and not being able to reply "both". – John Dvorak Jul 13 '15 at 8:31
• stdio is a standard header file for input and output functions in the C language. Why is it mentioned in this problem? – aditsu quit because SE is EVIL Jul 13 '15 at 10:11
• @aditsu STDIO stands for "Standard I/O" – Nathan Merrill Jul 13 '15 at 12:39
• Yes, and that doesn't change anything I said. – aditsu quit because SE is EVIL Jul 13 '15 at 15:14
• @aditsu then I don't see your point. I'm describing how to input/output (and giving an example at the same time) – Nathan Merrill Jul 13 '15 at 16:51
• My point is STDIO specifically refers to the C header file. What you are then actually showing is example input. If it really was stdio, I would expect some C macros and declarations. – aditsu quit because SE is EVIL Jul 13 '15 at 17:54