# 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]

• How are tags added to questions? – guest271314 Jan 9 '19 at 7:51
• @guest271314 You can use this markup to create a tag in a draft: [tag:code-golf] – DJMcMayhem Aug 29 '19 at 15:19
• Why no featured anymore? Can't we have it auto-added or something? – S.S. Anne Sep 26 '19 at 15:57
• @JL2210 We now have a permanent info box that links to the Sandbox, so the featured tag isn't necessary – caird coinheringaahing Sep 29 '19 at 13:43

# Convert ambiguous dates to "the correct way" (YYYY-MM-DD)

A problem I run into often with spreadsheets of data is dealing with dates of unknown ordering.

Your task is to take a series of dates that are in one of the following three formats, and output them as YYYY-MM-DD:

• DD/MM/YYYY
• MM/DD/YYYY
• YYYY-MM-DD

No other date formats are acceptable.

Since many dates are ambiguous, you must read all the dates to determine whether the set is MM/DD or DD/MM before outputting anything.

Your program must also detect the following error conditions and return an error code instead (with no other output):

• -1: Unable to determine date ordering. (All dates provided could be DD/MM or MM/DD)
• -2: Inconsistent date ordering. (There are dates provided that are definitely DD/MM and others that are definitely MM/DD, within the same set).
• -3: Bad data. (There are things included that are not valid dates, as defined above, including things like 31/04/2017 and 12/1/1980).

For the purposes of this challenge, February always has 28 days, April, June, September and November have 30 days, and all others have 31 days. All years, from 0001 to 9999 are equivalent.

## Sample input/output

['11/05/1988','12/12/1960'] => -1
['15/05/1988','03/18/2001'] => -2
['15/05/1988','31/06/1989'] => -3
['15/05/1988','2014-02-02', '18/03/2001'] => ['1988-05-15','2014-02-02', '2001-03-18']
['05/15/1988','03/18/2001'] => ['1988-05-15','2001-03-18']


## I/O

You can receive data in whatever way is normal for your language (line-separated stdin, array of strings, whatever). You may assume that the data you receive is of the correct type (ie, your array won't contain integers, nulls etc), but may contain empty strings.

If outputting to standard output, errors can be sent to stderr, or as program termination code. If implementing a function, you can return an integer instead of an array, throw an error, or whatever seems natural.

## Scoring

The score for your program is L - 2Y + 20D where:

• L is the length of your code, in bytes
• Y is 2017 minus the year in which the first version of the language you're using was published.
• D is the number of times the letters 'date', in any case, appear consecutively in your code.

For the purpose of Y, all versions of Lisp are 59, C is 39, C++ is 32, all EcmaScripts are 20 etc. Languages are considered the same if they have the same name (other than the version number). (No cheating by using some golf language that happens to be called C though.)

## Tags

(what else?)

• I think your scoring mechanism isn't going to work. It's probably best you stick to plain old shortest code. – Okx May 16 '17 at 11:33
• Any particular reason why? – Steve Bennett May 16 '17 at 22:11
• Possible dup – Digital Trauma May 16 '17 at 23:17
• @SteveBennett If your score decreases by 20 each time 'date' is in the code, then if someone fits an infinite amount of 'date' into a comment, they win. – Okx May 17 '17 at 9:28
• It increases, not decreases...? – Steve Bennett May 17 '17 at 11:21
• @DigitalTrauma They're both in the same ballpark but a lot of differences, including fundamental task (reformatting vs outputting a single probability), input formats (strict mm/dd/yyyy vs m-d-yy) etc. – Steve Bennett May 17 '17 at 11:24

## The Game

This game is an adaptation of a board game called Mammut, and basically an optimization problem.

Each match contains five players and five rounds, in which every player participates. Every round starts with a bunch of tiles being flipped at random on one of their sides, and put in the middle stack The tile composition will be fixed, but has not been completely decided yet There will be 30-35 of them, and each of them will have two different sides, with exactly 15 different types of tiles, and about half of those only having one single instance available. A random player is chosen as the starting player for the first round, and performance will decide the starter for the following four rounds. In order, each player that doesn't own any tiles will take an action, and this will keep going on until every player has at least one tile. The actions available are:

1. Take an arbitrary number of tiles from the middle stack.
2. Take all of the tiles owned by another player, and put one of them back in the middle stack.

Obviously, you can take the entire middle stack, but if there is at least one other player without tiles and you take too many, he will most likely steal your tiles right after.

## Scoring

Every player starts with 10 points, and if they end a scoring phase under zero, they will be given enough free points to go back to zero.

When everyone has tiles, the round is over, and we move on to scoring that round. Since this is played by bots and not humans, an infinite loop is possible, so after 1000 actions, the round will be stopped by force, and the players participating in the infinite loop who ended up empty ended will naturally end this round with a terrible score.

Scoring happens all at once, and you get (or lose) points according to the tiles you have, and the tiles the other players have. When scoring is done, we move on to the next round, or declare the winner if that was the fifth round.

## The Tiles

There are different types of tiles, and you job is basically to find the best balance between them while not having enough to make your stack worth stealing.

• Fire | The player who has the fewest fire tiles loses 5 points
• Meat | The three players owning the most meat tiles get 8, 5 and 2 points respectively
• Fur | Every fur tile gives you onw "fur point". During every round after the first, the player with the most fur points plays first. At the end of each round, the player with the most fur tiles gets the round number in points (1-5), while the one who has the least loses the round number in points.
• Ivory Tile | Every Ivory tile gives you two points.
• Axe Tile | (This one should be discussed) Every axe tile gives you one point, and every axe Tile obtained in the last round is Worth 3 points
• Animal Tiles | There are 7 different animals (Bat, Opossum, Bunny, Buffalo, Squirrel, Beaver and Duck), and only one of each in the game. When you end the round with one, you "obtain" this animal, and getting the same one again will do nothing. At the end of the game, depending on the number of animals you have obtained, you get points. (0: 0, 1:0, 2:0, 3:4, 4:9, 5:15, 6:22, 7:30)
• Mystery Tile | If you get a mystery tile, it will be turned around to reveal its other side during the scoring phase. The other side can't be another mystery tile or an animal tile.
• Tie-Breaker Tile | This tile serves as a tie breaker. One side is the "clockwise" side, and the other side is the "counter-clockwise", so every round will contain a tie-breaker tile. During any and all ties during scoring, the tie-breaker tile decides who wins or loses.

## Clockwise?

At the start of the game, every player will be given a random ID between 1 and 5. The player with ID 1 will start the game. Then, for the following rounds, the most fur points decides who starts, and the ID decides the order. Example: ID 3 has the most furs, then the order will be [3, 4, 5, 1, 2].

This is considered "clockwise". The counter-clockwise order would be [3, 2, 1, 5, 4]. This is important, because when dealing with ties, the tie-breaker tile takes the order into account.

If player 4 owns the clockwise tie-breaker tiles, and has 3 meats. Player 1 and 2 also have three meats. The first, second and third place in meat then go to players ID 4, 1 and 2 respectively. If everyone has 3 fires, except player 3 and 5 who have 1, then player 3 is the one to lose points. Having the tie-breaker tiles means you are first in the tie-breaking order, and that tile's visible side decide the rest of the order.

## Challenge specifications

You must make a C# class that inherits from a "Player" class. You must also override the method

List<int> ChooseTiles(Dictionary<int, List<Tile>> otherPlayers, List<Tile> center)


This method takes a dictionary of player IDs and List of tiles (could be empty), that are each player's tiles at the moment, plus a list of tiles in the middle. You must return a list of integer, which are the IDs of the tiles you want. If you try to get tiles illegally (not following the instructions for taking an action, which are either any number of tiles from the middle or all tiles except one from a player), you will be asked to choose one more time, and if you fail to follow the rules, you will be counted as "attempting to cheat" and removed from the "playing" pool during this round, so you will get scored for an empty hand. The same thing goes for throwing exceptions and infinite loops (Execution lasting more than 5 seconds). You are given one more chance then given an empty hadn for that round.

Here is the class Player you will be inheriting from:

public class Player
{
public int ID;
public int currentPoints;
public int currentFurs;
public List<Tile> currentTiles;
public List<TileType> animalsGotten;

public Player(int id)
{
ID = id;
currentPoints = 10;
currentFurs = 0;
currentTiles = new List<Tile>();
animauxGotten = new List<TileType>();
}

public virtual List<int> ChooseTiles(Dictionary<int, List<Tile>> otherPlayers, List<Tile> center)
{
throw new Exception("Fake players don't get to play!");
}

public virtual string GetName()
{
return "Player";
}
}


You should also override the GetName() function, but it is not required. You are allowed to create as many private functions or attributes as you want to store data during a game, but each match will create a new instance of your player.

## The Tournament

tournament will be played in a round-robin fashion. You are not garanteed a match with every single combination of four opponents available, but you are garanteed at least one match in common with every other bot, and everyone will play the same number of matches. You will also not play twice with the same 5 players. The total number of matches will depend on the number of participants. For each match, the first player will get 5 points, and the others will get respectively 3, 2, 1 and zero points depending on their points earned during the match. Furthermore, and ties in points will not be resolved, and the points of the occupied positions split between tied players. This means that if the points are (40, 37, 37, 37, 35), the points are (5, 2, 2, 2, 0)

• People usually don't like KotH challenges that are restricted to one language. See some other KotH challenges for ways to get around that. – Stephen May 16 '17 at 13:47

I have a large collection of fine art. My toddler is learning to use scissors and glue; lately she has started playing with my art collection. Fortunately she is really quite good with the scissors and cuts things up into perfect squares. She then uses glue to randomly tile the cut-up squares back into a new piece of art. For example, she reinterpreted my Mona Lisa (which wikipedia kindly hosts for me) as follows:

The following python script simulates what my toddler has done:

#!/usr/bin/python

import sys
import random
from PIL import Image

origname = sys.argv[1]

im = Image.open(origname)
width, height = im.size
width = (int(width + 99) / 100) * 100
height = (int(height + 99) / 100) * 100

im = im.crop((0, 0, width, height))

im2 = Image.new("RGB", (width, height), "black")

blocks = []
for x in range(width / 100):
for y in range(height / 100):
blocks.append(im.crop((x * 100, y * 100, (x + 1) * 100, (y + 1) * 100)))

random.shuffle(blocks)

im2.save("shuf" + origname)


Please excuse python skills - I'm still learning, but was happy to see how quick and easy it was to write this script. Polite code-reviews will be graciously accepted ;-)

It does the following:

• loads the image whose file name was given as a command-line parameter
• pads that image with black pixels such that the width and height are exactly divisible by 100
• divides the image into 100x100 pixel blocks
• randomly shuffles the blocks
• reassembles the randomly arranged blocks back into a new image with the same size attributes as the (padded) original
• saves the new image using the original filename prefixed with shuf

Your task is to write a program that takes the output of this script, analyses the edges of each 100x100 block and reassembles them back to the original picture.

### Input:

• an image filename. This may be passed at the commandline, via STDIN or even hard-coded, whichever is most convenient.

### Output:

• either output the a singular rearranged image to a differnent file, or display the singular rearranged output to the screen.

Input and output specs are intended to be lenient here, as filename-parsing is a non-goal of this question.

### Other rules

• The program must be able to correctly reassemble any random arrangement of the wikipedia Mona Lisa by the python script. Hard-coding of block transformations of the example image above is strictly not allowed.

• It is understood that for some degenerate cases (e.g. chequerboard of 100x100) blocks it is impossible to correctly rearrange the image. In those cases it is acceptable to produce incorrect/undefined output. However I think in general for photo images and almost all "famous" artworks, reassembly should be possible. Works by Mark Rothko are a possible exception.

• Common image manipulation libraries may be used (e.g. Python's PIL), but any APIs expressly designed for this purpose are strictly banned.

• Standard “loopholes” which are no longer funny

Now my toddler got a hold of The Scream. This is the result that needs to be fixed:

# Special thanks to Digital Trauma!

He wrote the original challenge and gave it up original post here

# META:

I need to update the images and the script to not have rotations and to not have black bars. Any ideas?

• The way to make this objective is to have a large list of images (like 50 or so), and require 100% accuracy. You should also reserve the right to regenerate the test cases if anybody is hardcoding the input. – Nathan Merrill May 16 '17 at 16:01
• Please credit the question that the inspiration (or direct copy ?!?) came from. Also, please note the comments to that question very carefully. In its current form, there significant problems (up to and including impossible to get 100% accuracy). – Digital Trauma May 16 '17 at 22:52
• @DigitalTrauma Sorry. I forgot to add that. It was a copy with edits based on you giving it up to gift exchange – Christopher May 17 '17 at 0:38
• Somebody suggested using lossless image formats, which would help a lot in terms of edges now being exact matches. That might be less interesting though. Nathan suggested a large list of images, which could give it the test-battery tag perhaps? My two suggestions I believe are at odds. – nmjcman101 Jun 20 '17 at 19:25

## Make some arrays

A recent post on The Daily WTF concerned the creation of four two-dimensional arrays of height n. Please write a function to create these arrays for me. Here is an example for n=4:

[[1] [[1 0 0] [[0] [[0 0 0]
[0]  [0 1 0]  [0]  [1 0 0]
[0]  [0 0 1]  [0]  [0 1 0]
[0]] [0 0 0]] [1]] [0 0 1]]


Rules:

• All four arrays must be two-dimensional. Arrays which have been flattened in any way are not acceptable.
• You can write separate functions for each array, in which case your score is the total of the scores for each function.
• Your functions can call each other, provided you include the name in your score. Otherwise unnamed functions are acceptable.
• Rather than returning the array(s), you can be passed them in as an input parameter (e.g. using int** in C).
• If your language has a builtin for inputting arbitrary data structures, then you can write a full program that outputs using the input format that the builtin would recognise.
• Alternatively, you can write a full program that outputs source code for the arrays in your language.
• All standard loopholes are banned.
• This is , so the shortest function wins.
• Hmmm, I wonder if you can reconstruct these four arrays if you just evaluate that code block as is. If so, that might be a fun challenge too. :) – Martin Ender May 17 '17 at 12:08

## Parse a 4-dimensional array

A 2D array is fairly easy to represent in ASCII art, something like this:

1  2
6 24


One approach for a 3D array is to have a number of 2D arrays, with an extra blank line between each array:

1  2
6 24

1  2
4  8


Things get a little more complicated for 4D arrays though. The best you can do is to arrange a number of 3D arrays side-by-side, but with at least two spaces between each array:

1  2   1  2
6 24   3  4

1  2   1  4
4  8  27 64


So that I don't have to ban full programs, the challenge will be to input 4 (numeric) indices along with a 4D array which will be as some sort of string in the above format, and output the (numeric) 4D array element at those indices. For example, if the 1-indexed indices were 1, 2, 1, 2 then the result would be 4. Rules:

• You must at a minimum support integers from 0 to 255, written in decimal.
• The array will not be ragged, but you will not be given the size of the array. Any of the dimensions may be 1, so 0 0 0 0 0 is a valid input in 0-based indexing.
• Numbers in the array will be consistently justified (please state whether you support left or right, or decimal justification if you support floating-point numbers), but the output must not contain any whitespace except for an optional trailing newline.
• You may choose 0 or 1-based indexing.
• You can choose row-major format instead of column-major format, as long as both outer and inner arrays have the same format. The first two indices will however always refer to the outer array and the last two indices to the inner array indexed by the first two indices.
• You can assume that the indices will always be valid.
• All standard loopholes are banned.
• This is , so the shortest program or function wins.
• some sort of string in the above format so no JSON? – Stephen May 17 '17 at 13:24
• @StephenS Correct, you won't be given an actual array, you'll be given an ASCII-art printout of the array. – Neil May 17 '17 at 13:26

# Prove the Undecideability of the Halting Problem

Either:

Create a program that, when given an input, no single program (which receives your source and your input) can determine if your program terminates, or

Create a function that, when given an input, no single program (which receives your source and your input) can determine if your function returns.

Your score is the byte count of your program plus the byte count of your input (or of the shortest input in the set of input that solves this problem).

Lowest score wins.

//I would love some input on my wording.

• Can I make a request to an external URL until I get a 404? – programmer5000 May 17 '17 at 18:21
• @programmer5000 can an external program determine whether your program will halt? For example, by pinging that URL themselves? – Stephen May 17 '17 at 18:24
• Oh. Could I make a program that stops when it finds 5 points that prove the Happy Ending Problem wrong? – programmer5000 May 17 '17 at 18:29
• @programmer5000 if your program stops with a given input, and another program can predict that it will stop with that input, your program does not match specs. No input is accepted input, but it is very unlikely that an undecidable program can come from no input AFAIK. – Stephen May 17 '17 at 18:32
• @programmer5000 from the Wikipedia page it seems like that problem is already solved, so that program will terminate, so another program could predict that. Could be wrong though. – Stephen May 17 '17 at 18:33
• Um. eval. It's one byte long in GolfScript. – Peter Taylor May 17 '17 at 21:35
• @PeterTaylor you need to provide an input that is undecidable, and that counts towards your score. – Stephen May 17 '17 at 21:38
• I don't think this is how the halting problem works... – Destructible Lemon May 17 '17 at 23:50
• @DestructibleLemon You may be right; Wikipedia says a general algorithm to solve the halting problem for all possible program-input pairs cannot exist. Do I need to require two inputs? This answer seems to contradict Wikipedia though. – Stephen May 18 '17 at 0:10
• hmmm, you definitely could do this (make it an interpreter) but I'm not sure how much you have to do to make this work... as in what the simplest program would be – Destructible Lemon May 18 '17 at 0:17
• @StephenS It doesn't require 2 inputs, it requires a pair (program, input). – Esolanging Fruit May 18 '17 at 1:07
• It's the problem which is undecidable, not the instances. If you want to ask for a program which cannot be proven to halt or not halt, you have to specify the axiom system which can be used for the proof. See e.g. codegolf.stackexchange.com/q/79470/194 , codegolf.stackexchange.com/q/79620/194 – Peter Taylor May 18 '17 at 6:19

# Generating strings of Rs and spaces

If a task is to make a string of 16 characters using 2 different characters, it can be done in 2^16=65536 ways. Let's generate them all!

Write a program or function which takes a number in range [0, 65535] as input and outputs a string of 16 characters consisting of R and  (space). One number corresponds to one string and must generate the same string each time the code is run.

## Example

Suppose that a program/function takes a binary representation of the number and replaces zeros with spaces and ones with Rs to make the string. The conversion from input to output will look as follows:

0     -> "                "
1     -> "               R"
2     -> "              R "
3     -> "              RR"
...
65532 -> "RRRRRRRRRRRRRR  "
65533 -> "RRRRRRRRRRRRRR R"
65534 -> "RRRRRRRRRRRRRRR "
65535 -> "RRRRRRRRRRRRRRRR"


## Sandbox notes

• This challenge probably needs a better name. If you have an idea, please mention it.
• I know that this challenge will be boring if making the string from binary representation is the shortest way in all languages. I hope that this isn't the case.
• The only reason I can think of that making it from the binary representation would not be the shortest way is if there's a shorter way with a Cartesian product built-in, but that's still boring. – Peter Taylor May 18 '17 at 8:23

# Boxes

N boxes are lined up in a sequence (1 ≤ N ≤ 20). You have A red balls and B blue balls (0 ≤ A ≤ 15, 0 ≤ B ≤ 15). The red balls (and the blue ones) are exactly the same. You can place the balls in the boxes. It is allowed to put in a box, balls of the two kinds, or only from one kind. You can also leave some of the boxes empty. It's not necessary to place all the balls in the boxes.

## challenge!

Write a program, which finds the number of different ways to place the balls in the boxes in the described way.

### Input

Input contains one line with three integers N, A and B separated by space.

### Output

The result of your program must be an integer written on the only line of output.

### Sample I/O

input
2 1 1

output
9


WIP.

# Split the atom

Input: 0 <= X <= 2³² - 1

Output: List of numbers in decimal, after recursive splitting in binary format.

Explanation:

Example 1:

Input: 255

Current Output is 255.

Binary representation of 255 is 1111 1111. Splitting it, we get 1111 and 1111, which in decimal are 15 and 15.

Continuing the Output, we will have 255 15 15.

Now the numbers 15 and 15 will serve as inputs and these numbers are to be split.

Continuing the Output, we will have 255 15 15 3 3 3 3.

Continuing the logic, final Output will be 255 15 15 3 3 3 3 1 1 1 1 1 1 1 1. And since 1 can no longer be split, the output stops.

Example 2:

Input: 225

Current Output is 225.

Binary representation of 225 is 1110 0001. Splitting it, we get 1110 and 0001, which in decimal are 14 and 1.

Continuing the Output, we will have 225 14 1.

Now the numbers 14 and 1 will serve as inputs and these numbers are to be split.

Since 1 is no longer split-able, the Output will be 225 14 1 3 2.

Final Output will be 225 14 1 3 2 1 1 1 0.

Example 3:

Input: 32

Output: 32 4 0 1 0.

Conditions:

1. If the number of binary digits are odd, the first number will have one fewer binary digit than the next one. Example, 20 (10100) will be split as 10 and 100, with decimal output being 2 and 4.
2. Standard loophole rules apply.
3. 0s and 1s do not propagate further.
4. Program crashing for trying to display too many numbers is a valid exit condition.
• Surely you reversed the inequality signs. – Leaky Nun May 18 '17 at 11:16
• s/Splitting it/Splitting it in half/ – Leaky Nun May 18 '17 at 11:17
• @LeakyNun Yes, yes I did :D – ctrl-shift-esc May 18 '17 at 11:20
• @trichoplax I updated the conditions. Is that clearer? – ctrl-shift-esc May 18 '17 at 11:34
• @trichoplax I hope 3 examples clears everything up. – ctrl-shift-esc May 18 '17 at 11:53
• I think this is a duplicate of an earlier question, but I haven't found it by searching for binary split. Perhaps someone else will be able to find it. – Peter Taylor May 18 '17 at 11:58
• @ctrl-shift-esc yes that clears up the treatment of the zeroes – trichoplax May 18 '17 at 14:05

# Introduction

So we've had the musical version The Sound of Pi, now its time for the movie.

# Challenge

Your challenge is to write a full program or function that outputs an animated version of pi to 100 decimal places.

For your convenience, here's Pi to 100 decimal places

3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679


# Input and Output

Input: No input required

Output: A single gif file

# Rules

• Only one digit or decimal point should be shown at a time
• Each digit or decimal point should be shown for for between 0.25 and 1.5 seconds (your choice).
• The font should be clearly visible (different colour to background)
• The characters should be at least 100 pixels high and have at least a 1 pixel boarder
• You can use built in values of pi as long as they're correct to 100 dp
• Standard loopholes apply
• This is , so the submission with the least amount of bytes wins!

# Sandbox questions

• Is the time constraint realistic?
• What tags should I use?
• I'd VTC this as "too broad". – Erik the Outgolfer May 18 '17 at 13:56
• @EriktheOutgolfer could you explain why? a VTC on its own doesn't help me improve it :) – Notts90 is off to codidact.org May 18 '17 at 14:01
• Basically there are many ways you could make a "video file" (file formats), the font size could be invisibly small, the background color may be the same as the foreground color, digits might not fully appear (i.e. be cut) etc. – Erik the Outgolfer May 18 '17 at 14:05
• i think a gif with fixed size would be better – Felipe Nardi Batista May 18 '17 at 14:06
• @EriktheOutgolfer added size and colour constraints. I've already specified the format should suitable for vlc or wmp. – Notts90 is off to codidact.org May 18 '17 at 14:18
• @Notts90 saying it's suitable for vlc or wmp does not say much, something that runs in my vlc may not run in yours (installed codecs and stuff) – Felipe Nardi Batista May 18 '17 at 14:48
• I'll go with the gif option then! – Notts90 is off to codidact.org May 18 '17 at 16:32

# Introduction

Wardialing was a very interesting way to try to hack people back in the '80s and '90s. When everyone used dial-up, people would dial huge amounts of numbers to search for BBS's, computers, or fax machines. If it was answered by a human or answering machine, it hung up and forgot the number. If it was answered by a modem or a fax machine, it would make note of the number.

# Challenge

Your job is to make a URL wardialer. Something that tests and checks if it's a valid website from one letter of the alphabet.

# Constraints

• Program must take user input. This input has to be a letter of the alphabet, no numbers. Just one letter of the alphabet and form multiple URLs that start with the letter.
• Standard loopholes apply.
• You must make 8 URLs from 1 letter, and test to see if it is a valid site.
• If you hit an error (not a response code), instead of leaving it blank, go ahead and return a 404
• If you hit a redirect (3xx), return a 200 instead.
• You may output the results in any reasonable format, as long as it includes the website name, status codes for all the websites and the redirects
• This is Code Golf, so shortest amount of bytes wins.

# What counts as a URL for this challenge?

http://{domain-name}.{com or net or org}

For this challenge, the domain name is should only be 4 letters long, no more, no less.

# What should I test?

For each 4 letter domain name, test it against three top-level domains (.com, .net, .org). Record all the response codes from each URL, remember from the constraints that any (3xx) should return 200 and be recorded as a redirect in the output and any error getting to the website should result in a 404.

a

# Output

+---------+------+------+------+------------+
| Website | .com | .net | .org | Redirects? |
+---------+------+------+------+------------+
| ajoe    | 200  | 200  | 200  | .com, .net |
+---------+------+------+------+------------+
| aqiz    | 200  | 404  | 404  | no         |
+---------+------+------+------+------------+
| amnx    | 200  | 503  | 404  | .com       |
+---------+------+------+------+------------+
| abcd    | 200  | 404  | 200  | .com       |
+---------+------+------+------+------------+
| ajmx    | 200  | 503  | 404  | no         |
+---------+------+------+------+------------+
| aole    | 200  | 200  | 200  | .com       |
+---------+------+------+------+------------+
| apop    | 404  | 200  | 200  | .net       |
+---------+------+------+------+------------+
| akkk    | 200  | 200  | 200  | .com       |
+---------+------+------+------+------------+

• I don't like the formatting aspect; it adds a whole unnecessary layer to the meat of challenge. I also don't like the fact that you have to go through .com, .net, and .org for the same reason. But I do like the concept, and I think if you stay closer to the actual challenge ("generate a few websites and check if they exist") it could be well-received on main. – ETHproductions May 22 '17 at 19:43
• but the formatting looks sooooo good – KuanHulio May 22 '17 at 19:44
• Well then, maybe you should post a challenge idea to format a table like that ;-) I think we may have already had that challenge though. – ETHproductions May 22 '17 at 19:45
• ehhh, nah. what should i replace it with – KuanHulio May 22 '17 at 19:47
• I'd allow users to output in any reasonable format they like: an array of arrays, a newline-separated string, etc. A table like that would still be allowed, though it probably wouldn't be the shortest. – ETHproductions May 22 '17 at 19:49
• URLs for websites all start with the letter h. If you want to make an argument about relative URLs, I will concede that they can also start with the non-letter /. But abusing a clearly defined term like URL to the extent to which it's abused in this draft only serves to confuse people. The task is: given an input of one letter of the alphabet, generate 8 alphabetic labels, from each of those labels to generate three domain names, and for each of those names test the response code of the URL http://{name}/ – Peter Taylor May 22 '17 at 21:46
• Also, in "Something has more than 4 letters in it", more than is exclusive, so this is not consistent with the example. – Peter Taylor May 22 '17 at 21:47
• There. I think this edit helps @PeterTaylor – KuanHulio May 22 '17 at 22:17

# Program Equilibrium Iterated Prisoner's Dilemma Tournament

This is an iterated prisoners dilemma tournament. You are to make a bot that plays the prisoners dilemma against the other contestants, but with a twist- you can perfectly simulate your opponent!

## Iterated Prisoner's Dilemma

The prisoner's dilemma is a two-player game in which players can choose to either "Cooperate" or "Defect" against their opponent. The payoff matrix for the prisoner's dilemma looks like this:

                           Player 2
C              D

------------------------------
|              |               |
C   |    (3, 3)    |    (0, 5)     |
|              |               |
Player 1        |------------------------------|
|              |               |
D   |    (5, 0)    |    (1, 1)     |
|              |               |
------------------------------


In the iterated prisoner's dilemma, multiple rounds are played in succession, and players can use their knowledge of the previous rounds when making a decision.

## The twist

Bots are also allowed to run their opponent and examine the output before making a move. This allows for significantly more complex strategies in which bots can simulate their opponents to determine if it is safe to cooperate with them, as well as attempt to exploit less sophisticated players.

## Simulation

There will be a program available in the path called simulate that you can use to simulate what your opponent would do against you

Usage:
simulate [instruction to your own bot] [fake history to the opponent]

Example:
simulate cooperate 00 10 01 11 01 10


All arguments are optional, and you may also use underscore _ for no argument. If you do not explicitly state the history, the real history will be used.

Example output from the simulate program:

01


The first number is you, the second is your opponent. 0 means defect, 1 means cooperate.

## The instruction

It wouldn't be much use to simulate what your opponent would do against you, because he'd probably simulate you right back, and then you'd be stuck in an infinite loop.
The instruction is your way to simulate what the opponent would do against another agent. You could for instance have a cooperate instruction that causes your bot to cooperate mindlessly, to see what the opponent would do if you were to cooperate.

## Input

Your program will be given the following input at the beginning of each round:

Instruction (if any)
Current round number
Complete history of past interactions with this bot. Space separated: the first number is you, the second is your opponent


Example:

cooperative
5
2
3
00 10


## Output

0 for defect or 1 for cooperate, with any number of leading characters. Trailing characters (including 0 or 1's) will be ignored.

Example:

1


## The tournament

The tournament will be round-robin elimination: Each bot will play one match against all other bots, where a match consists of 100 rounds of the prisoner's dilemma. At the end of the round-robin round, the lower-scoring half of the tournament pool will be eliminated. This process will be repeated until only one bot remains, or there is a tie.

## Rules

• Your program has to run on Linux. Please provide a brief description of how to run your program if possible
• Your program has to give an answer within 5 seconds. Failing to do so will be interpreted as defect.
• Your program may not perform multiple simulations at the same time
• You may only enter a single bot, this is to prevent people from entering multiple bots that cooperate
• You may not read or write any files. If this is required by your language, please state so in your answer.
• You may not in any way store state between rounds. This is to prevent bots from figuring out whether they are being simulated.
• If you exploit another loophole to figure out whether you are being simulated, you will be disqualified. Guessing (or strategical testing) is obviously allowed

## About the host computer

Arch Linux 4.10.13-1
Intel(R) Core(TM) i7-7500U CPU @ 2.70GHz, 4 cores
16 GB RAM
I will disconnect from the internet while running the tournament


## Disclosure

I got the idea as well as some of the text from this Github repository. I have not directly asked the author for permission to use the challenge, but he said that "if you want to run this tournament on your own, you are more than welcome to" in a blogpost.

I will update this periodically whenever new bots enter.

# Meta

How do I best discourage/prevent players from intentionally using every bit of their time limit to sabotage other players trying to simulate them? I am thinking random time limits and/or penalties

• Have you ever run a KotH? If not, I think you are about to learn how incredibly slow a round can be even if the programs have very simple logic. With the simulate instruction I anticipate taking hours to run a single round. – Peter Taylor May 22 '17 at 21:50
• @PeterTaylor That's good advice; I might not want to run this on my main computer – BlackCap May 22 '17 at 22:54

## Identify the variable case

Your task is to write a function which determines which casing convention a provided variable name belongs to:

• camelCase
• kebab-case
• Train-Case
• snake_case
• SCREAMING_SNAKE_CASE
• PascalCase
• Ada_Case (not a real term, but apparently the standard casing used in Ada)

Your function should return one of the above strings, either exactly as above, or as spaced title-case: "Train case", "Screaming snake case".

Casings that include - or _ may include leading or trailing -s or _s (eg, __MY_SNAKE__ or -webkit-kebab).

Multiple consecutive upper case letters are allowed in mixed casings, as long as they follow a lower case letter (MyXMLDocument, This-CSS-Crap).

Where an input fits multiple schemes (eg, F or foo), you may return any valid classification.

If an input does not fit one of the above schemes (eg stu-pid_case), you must return something different. You may also throw an error.

The input string is guaranteed to be at least one character, and begin with a character matching /[a-zA-Z_-]/. Every other character will match /[a-zA-Z0-9$-]/ This is , so shortest length in bytes wins. Standard loopholes forbidden. Standard input and output methods. ### Test cases myFunkyVariable => camelCase no-op => kebab-case TEST2 => SCREAMING_SNAKE_CASE __c => snake_case XML-Madness => Error Get_Input => Ada_Case i => camelCase (or snake_case) char2int_factory => snake_case  • You should specify exactly what each of the cases requires. (e.g. train case is separated by underscores with only the first character capital) Because this is a competition there should be no room for interpretation. – Post Rock Garf Hunter May 26 '17 at 4:56 • What ambiguity have I missed? – Steve Bennett May 26 '17 at 5:19 • You should define what each of the 7 cases entails. Currently you just list 7 examples, which is certainly helpful, but I don't think sufficient. – Post Rock Garf Hunter May 26 '17 at 5:30 • You really don't think they're sufficiently self-explanatory? I mean, I can add explanation, but I'm curious if you have an example of a variable name that you don't know how to classify? – Steve Bennett May 26 '17 at 5:35 • I think I get it based on the examples and I think any reasonable person would be able to jump to the correct conclusion, but we should strive to make questions as concrete as possible. Some people might not be aware of casing in the first place and definitions could help. It may seem like I'm making a fuss over nothing, and perhaps I am, but I think it could only benefit to add specific definitions of the terms, since the question is about identifying them. As far as examples go, I believe E_S_S is ambiguous between screaming snake and Ada. Definitions might help clear that up. – Post Rock Garf Hunter May 26 '17 at 5:46 • That one is ambiguous, which, as stated, means that either answer is ok. But I'll add an introductory paragraph about casing. – Steve Bennett May 26 '17 at 5:58 # 21 = (1 + 3 + 5 + 7 + 9) - (1 + 3) Sandbox question: Is this different enough from the original challenge? ### Background • This is a sequel to my previous challenge, but this time with a slightly more interesting practical application (the factorization of the input). • It is based on 1) the fact that any odd integer n can be expressed as the difference of two squares a² - b² and 2) the well known formula: ### The task You're given a positive odd integer n. Your task is to determine how many iterations of the following algorithm need to be processed to reach n. • Initialization: find the highest integer k such that k² ≤ n. Build the list L = [ 1, 3, 5, ..., 2k-1 ]. • Iteration: • Step #1: If the sum of the terms of L equals n, stop here. • Step #2: Increment k and append 2k-1 to L. • Step #3: While the sum of the terms of L is greater than n, remove the first term from the list. Go on with step #1. All iterations (either full or partial) must be counted. In other words, you must return the number of times step #1 was executed. ### Example #1 This is a trivial example for the perfect square n = 9: • Initialization: k = 3 because 3² ≤ 9 < 4², which leads to L = [ 1, 3, 5 ]. • Step #1: 1 + 3 + 5 = 9. We're done. We went through one iteration. So the expected result is 1. ### Example #2 Here is what we get for n = 21: • Initialization: k = 4 because 4² ≤ 21 < 5², which leads to L = [ 1, 3, 5, 7 ]. • Step #1: 1 + 3 + 5 + 7 = 16, which does not equal n. • Step #2: We increment k and we add 2k + 1 = 2 x 5 - 1 = 9 to the list: L = [ 1, 3, 5, 7, 9 ]. • Step #3: We remove the first term from the list: L = [ 3, 5, 7, 9 ]. The sum of the terms is now 24, which is still greater than n. So we remove another term: L = [ 5, 7, 9 ]. • Step #1 : 5 + 7 + 9 = 21. We're done. We went through two iterations. So the expected result is 2. ### Example #3 Below is a summary of all steps for a slightly more complex example with n = 145. Initialization: k = 12 because 12² ≤ 145 < 13². Iteration | Step | k | L | Sum ----------+------+----+-----------------------------------+---- 1 | 1 | 12 | 1,3,5,7,9,11,13,15,17,19,21,23 | 144 | 2 | 13 | 1,3,5,7,9,11,13,15,17,19,21,23,25 | 169 | 3 | 13 | 11,13,15,17,19,21,23,25 | 144 ----------+------+----+-----------------------------------+---- 2 | 1 | 13 | 11,13,15,17,19,21,23,25 | 144 | 2 | 14 | 11,13,15,17,19,21,23,25,27 | 171 | 3 | 14 | 17,19,21,23,25,27 | 132 ----------+------+----+-----------------------------------+---- 3 | 1 | 14 | 17,19,21,23,25,27 | 132 | 2 | 15 | 17,19,21,23,25,27,29 | 161 | 3 | 15 | 19,21,23,25,27,29 | 144 ----------+------+----+-----------------------------------+---- 4 | 1 | 15 | 19,21,23,25,27,29 | 144 | 2 | 16 | 19,21,23,25,27,29,31 | 175 | 3 | 16 | 23,25,27,29,31 | 135 ----------+------+----+-----------------------------------+---- 5 | 1 | 16 | 23,25,27,29,31 | 135 | 2 | 17 | 23,25,27,29,31,33 | 168 | 3 | 17 | 25,27,29,31,33 | 145 ----------+------+----+-----------------------------------+---- 6 | 1 | 17 | 25,27,29,31,33 | 145  We went through 6 iterations. So the expected result is 6. ### Factorization of the input This paragraph is for illustration purposes only. It describes how the factorization of the input can be deduced from the result of the algorithm. Factorization of 21: • 21 = 5 + 7 + 9 = (1 + 3 + 5 + 7 + 9) - (1 + 3) • 21 = 5² - 2² • 21 = (5 + 2)(5 - 2) • 21 = 7 x 3 ### Rules and clarifications • The input is guaranteed to be a positive odd integer. It may be either a composite integer or a prime. • You're required to process any odd n in [ 1, ..., 65535 ] in less than one minute on mid-range hardware. • Given enough time, your program/function should theoretically work for any value of n that is natively supported by your language. If it doesn't, please explain why in your answer. • You may use any other method instead of the described one as long as it returns the correct result. • This is code golf, so the shortest answer in bytes wins! ### Test cases To be completed • Typo: you wrote "k²=n", which can't possibly be correct (and contradicts the rest of the post). – user62131 May 26 '17 at 3:30 • @ais523 Thanks for catching that out. (I believe all my "less than or equal to" signs where turned into equal signs when I copy/pasted through Notepad++.) – Arnauld May 26 '17 at 7:10 • 1. There's also an extra = in the LaTeXified image. 2. You say it's a variant on an earlier question of yours, but it seems so similar that I don't see why it wouldn't be a dupe. If it isn't, I definitely think it's a dupe of codegolf.stackexchange.com/q/18349/194 : the two questions are essentially "Find the factorisation of n into two parts which are as close as possible to sqrt(n). – Peter Taylor May 26 '17 at 8:12 • @PeterTaylor Thanks for your feedback. Yes, I think it's a dupe indeed. – Arnauld May 26 '17 at 8:16 # Dungeon of Botdom Bots will play a variant of this game: https://boardgamegeek.com/boardgame/150312/welcome-dungeon (Our version will be played by one bot versus another bot, and there will only be one character, which may or may not be in the actual game, and it will be repeated a bunch.) Essentially, there is a deck of cards, with enemies on each card. players take turns either passing, or drawing a card and either a) placing it in the initially empty dungeon or b) removing a piece of gear and discarding the enemy. enemies have different hit points, which affects the damage done to a bot traversing the dungeon. When everyone but one player has passed, they enter the dungeon. when a bot is traversing the dungeon, they will encounter the enemies placed in the dungeon in LIFO order (the card on top is taken first) (if I take out some items this may be irrelevant). enemies are instantly defeated if the player has a corresponding item, otherwise the player takes damage equal to the enemies number. if a player makes it through the dungeon, they get one point. get two points to win the match. if they fall while traversing the dungeon, they lose one chance. fail twice, and the opponent wins the match. What this means, is that you might want to do one of two things: make the dungeon too dangerous to survive without your opponent thinking it is, and passing, or making the opponent bot believe the dungeon is too dangerous, when it is not, and running through the dungeon and succeeding. We'll have a good ol' round robin of a 1000 rounds each or some such. the nice thing about this game is that the rounds are short, because once you finish the deck, a player automatically enters the dungeon. • You may want to include a better description, not just the link. Describe the various cards, the game mechanics, the format of the bots, and include the code for testing bots. KOTH challenges tend to have lots of text. – Gryphon May 26 '17 at 13:29 • @gryphon did I not do that? Also I haven't decided on the exact deck yet, and exact items, and exact round formats. I have described the basics of the game anyway – Destructible Lemon May 27 '17 at 0:43 • @Gryphon also I haven't made the controller yet. we can't all get away with straight posting to main because of our incredible talent for Koths and making the controllers immediately – Destructible Lemon May 27 '17 at 0:54 • OK, sorry. I would just make sure I have the controller before I actually posted the question. – Gryphon May 29 '17 at 17:27 • I have the controller finished here – Destructible Lemon May 30 '17 at 8:24 • Nice Poem, @DestructibleLemon! – Gryphon May 30 '17 at 10:28 # Can my favourite team still become Football Champion? code-golf As a fan of an at most moderately successful footballBE team, towards the end of the season I often wonder whether my favourite team still has any theoretical chance left of becoming champion. Your task in this challenge is to answer that question for me. # Input You will recieve three inputs: the current table, the list of remaining matches, and the current position of the team we are interested in. Input 1: The current table, a sequence of numbers were the i-th number are the points gained by team i so far. For example, the input [93, 86, 78, 76, 75] encodes the following table (only the last column is of importance): Input 2: The remaining matches, a sequence of tuples where each tuple (i,j) stands for a remaining match between team i and j. In the above example, a second input of [(1,2), (4,3), (2,3), (3,2), (1,2)] would mean that the remaining matches are: Chelsea vs Tottenham, Liverpool vs Man. City, Tottenham vs Man. City, Man. City vs Tottenham, Chelsea vs Tottenham  Input 3: The current position of the team we are interested in. For example, an input of 2 for the above example would mean that we'd like to know whether Tottenham can still become champion. # Output For each remaining match of the form (i,j), there are three possible outcomes: • Team i wins: Team i gets 3 points, team j gets 0 points • Team j wins: Team i gets 0 points, team j gets 3 points • Draw: Team i and j both get 1 point You must output a truthy value if there is some outcome for all remaining games such that at the end, no other team has more points than the team specified in the 3rd input. Otherwise, output a falsy value. Example: Consider the exemplary input from the above section: Input 1 = [93, 86, 78, 76, 75], Input 2 = [(1,2), (4,3), (2,3), (3,2), (1,2)], Input 3 = 2 If team 2 wins all its remaining matches (i.e. (1,2), (2,3), (3,2), (1,2)), it gets 4*3 = 12 additional points; none of the other teams gets any points from these matches. Let's say the other remaining match (i.e. (4,3)) is a draw. Then the final scores would be:  Team 1: 93, Team 2: 86 + 12 = 98, Team 3: 78 + 1 = 79, Team 4: 76 + 1 = 77, Team 5: 75  This means that we have already found some outcome for the remaining matches such that no other team has more points than team 2, so the output for this input must be truthy. # Details • You may assume the first input to be an ordered sequence, i.e. for i < j, the i-th entry is equal to or greater than the j-th entry. The first input may be taken as a list, a string or the like. • You may take the second input as a string, a list of tuples or the like. Alternatively, you may take it as a two-dimensional array a where a[i][j] is the number of entries of the form (i,j) in the list of remaining matches. For example, a[1][2] = 2, a[2][3] = 1, a[3][2] = 1, a[4][3] = 1 corresponds to [(1,2), (4,3), (2,3), (3,2), (1,2)]. • For the second and third input, you may assume 0-indexing instead of 1-indexing. • You may take the three inputs in any order. Please specify the exact input format you chose in your answer. Side node: The problem underlying this challenge was shown to be NP-complete in "Football Elimination is Hard to Decide Under the 3-Point-Rule". Interestingly, if only two points are awarded for a win, the problem becomes solvable in polynomial time. # Test Cases All test cases are in the format Input1, Input2, Input3. Truthy: • [93, 86, 78, 76, 75], [(1,2), (4,3), (2,3), (3,2), (1,2)], 2 • [50], [], 1 • [10, 10, 10], [], 3 • [15, 10, 8], [(2,3), (1,3), (1,3), (3,1), (2,1)], 2 Falsy: • [10, 9, 8], [], 2 • [10, 9, 9], [(2,3), (3,2)], 1 • [21, 12, 11], [(2,1), (1,2), (2,3), (1,3), (1,3), (3,1), (3,1)], 2 # Winner This is , so the shortest correct answer (in bytes) wins. The winner will be chosen one week after the first correct answer is posted. Closely related to Words from periodic table of elements (but that one is closed due to unclear specification?). Closely related to Find the Chemistry of a name (probably a dupe, slightly different requirements though). Closely related to [Br]eaking Code Golf [Ba]d (allows strings to be not expressible as solely a sequence of element abbreviations). May I get a community consensus, whether this is better specified and/or sufficiently different to not be immediately closed as a dupe? ## Elementize a string Convert an input string to a concatenation of chemical element abbreviations. Write a program/function/procedure etc. which will take as input a string/array of characters/pointer to a string etc. and return/print/display the same string expressed as a concatenation of chemical element abbreviations. For example, takagi can be expressed as TaKAgI (i.e. the abbreviations for Tantalum(Ta), Potassium(K), Silver(Ag), Iodine(I)). For this challenge you must use the following element name abbreviations: {"H", "He", "Li", "Be", "B", "C", "N", "O", "F", "Ne", "Na", "Mg", "Al", "Si", "P", "S", "Cl", "Ar", "K", "Ca", "Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co", "Ni", "Cu", "Zn", "Ga", "Ge", "As", "Se", "Br", "Kr", "Rb", "Sr", "Y", "Zr", "Nb", "Mo", "Tc", "Ru", "Rh", "Pd", "Ag", "Cd", "In", "Sn", "Sb", "Te", "I", "Xe", "Cs", "Ba", "La", "Ce", "Pr", "Nd", "Pm", "Sm", "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm", "Yb", "Lu", "Hf", "Ta", "W", "Re", "Os", "Ir", "Pt", "Au", "Hg", "Tl", "Pb", "Bi", "Po", "At", "Rn", "Fr", "Ra", "Ac", "Th", "Pa", "U", "Np", "Pu", "Am", "Cm", "Bk", "Cf", "Es", "Fm", "Md", "No", "Lr", "Rf", "Db", "Sg", "Bh", "Hs", "Mt", "Ds", "Rg", "Cn"}  These are the elements with numbers 1 through 112. You may optionally also use the abbreviations for elements 113 through 118: {"Nh", "Fl", "Mc", "Lv", "Ts", "Og"}  You may not, however, use the placeholder three-letter abbreviations for not yet named elements, such as "Uuo" (Ununoctium). If the input string cannot be expressed by the above abbreviations, you shall return one of the following: • a falsey value (clearly distinct from element names, in other words A would not be valid, even though there is no element "A"; something like 0, null, false, newline is fine) • an empty string • exit without output • exit with an error • something similarly unambiguous signifying failure and not returning some incorrect output that could be accidentally misinterpreted as an answer (suggestions to make this specification clearer?) Possible output, using example input takagi: • an appropriately capitalized string: TaKAgI. • a flat array of characters {"T", "a", "K", "A", "g", "I"} with appropriate capitalization. • a list of strings (capitalized or not) separated by newlines or as separate members of an array, etc., e.g. ta \n k \n ag \n i. The rule of thumb is that the division into separate elements must be clear. Please comment if additional clarification is needed! You may assume the input to be a single word consisting only of letters. Compression is not the intent of this challenge! Boiler-plate code that fetches the list of elements from somewhere, hard-coding the lists of abbreviations, assuming the list of abbreviations to be stored in a variable or passed as a second argument to your function is OK and should not be included in the byte count. Sample input -> sample output no -> No // as in Nobelium, alternatively see next line no -> NO // Nitrogen-Oxygen, either one is valid helium -> falsey output heliam -> HeLiAm fog -> FOg // If using 118 elements, falsey otherwise. ppcg -> falsey // I'm really, really sorry  Suggestions of further test cases are appreciated. This is code-golf, shortest code wins. • Potassium is K, not P. – CalculatorFeline Jun 1 '17 at 2:44 • @calculator brain-fart, fixed, thanks. – LLlAMnYP Jun 1 '17 at 4:35 • I think it makes more sense to work on improving the existing closed question than to post a duplicate. – Peter Taylor Jun 1 '17 at 6:30 • @Peter I should have realized sooner, that a [chemistry] tag exists here. I'm not sure I'm at ease with modifying someone else' challenge (distorting their intent?) and potentially invalidating others' answers... – LLlAMnYP Jun 1 '17 at 6:37 # How many substitutions till palindromization? Given a string, find the minimum number of character substitutions needed so that the string is a palindrome. E.g. the string abchefa needs 2 substitutions, so it can take any of the following paths: abchefa -> afchefa -> afehefa -> afchcfa -> abehefa -> afehefa -> abeheba -> abchcfa -> afchcfa -> abchcba -> abcheba -> abeheba -> abchcba  You must return a minimal number, e.g. abc can use 3 substitutions (abc -> dbc -> ddc -> ddd) but it really only needs 1 (abc -> aba) so you must return 1. The string will only contain printable ASCII, no newlines. Additional testcases: Input Output 0 A 0 !@ 1 1234567890 5 !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_abcdefghijklmnopqrstuvwxyz{|}~
47

3

o_O WTF RLY?!
6


# Rules

• You can take the string as a string or as a list of chars, but not as a list of strings
• You must return a minimal value in a generally accepted output format.
• I thought there was a near-dupe somewhere, but I'm pretty sure this is the one I was thinking of... – ETHproductions Jun 1 '17 at 23:38
• Actually this might be a dupe of this: perform any answer for all indexes in the string, sum, divide by two. – ETHproductions Jun 1 '17 at 23:41
• @ETHproductions You spoiled the hidden way to do it... – Erik the Outgolfer Jun 2 '17 at 5:39
• I'm pretty sure I've seen an exact dupe, although it might still be in the sandbox; codegolf.stackexchange.com/q/95343/194 is a generalisation. – Peter Taylor Jun 2 '17 at 9:00

# Write machine code that also works when left rotated one byte

Write machine code for a CPU that runs and does something. The twist is that your code should run and do something else, without errors, if it is left rotated one byte.

Suggestions? Ideas? Thoughts? Let me know.

• So is this "any code that doesn't crash if rotated"? Generally it's best to give a specific task, not just "do something", or else it's quite broad. – Geobits Oct 26 '16 at 0:15
• This is completely uninteresting in any instruction set which has one-byte instructions. E.g. in x86 the byte that's rotated away can be INC, and then the "something else" is just the same function with an offset to one of the arguments. – Peter Taylor Oct 26 '16 at 7:53
• Far too broad, IMO. Also very, very easy in machine code dialects which have single-byte jump instructions, or any instruction that has a single-byte opcode plus X bytes of data, where X is no shorter than the length of the jump instruction; this describes almost every machine code dialect in existence. – user62131 Jun 2 '17 at 15:03
• What about reversing it? – dkudriavtsev Jun 2 '17 at 16:49

## Introduction

The divmod function is one that is included in many standard libraries and is defined as follows:

Or, in other words, divmod(a,b) returns a list containing the integer quotient of a/b (i.e. floor(a/b)) and mod(a,b) (i.e. the remainder in the division of a/b).

Your challenge is not to implement the divmodfunction, but rather reverse it.

## Input

You will take two integers x and y as input, in any reasonable input format (two integers, list, etc.). Both x and y are guaranteed to be in the range -2^31 to 2^31-1, inclusive.

## Output

The output of your code shall be two integers, in any reasonable output format (two integers, list, etc.). Note that you must output the two integers in such a way that a human is able to distinguish one from another. These two integers should be an a and b such that divmod(a,b)==(x,y) (i.e. floor(a/b)==x && mod(a,b)==y). Please specify in your answer how these two integers are outputted if it is not immediately clear (for example, if you output b before a).

Remember that this is , so shortest solution in bytes wins!

• Note to self: add I/O examples – GamrCorps Jun 3 '17 at 2:10
• So: given x and y output x*b+y, b for any b > y if y is positive or b < y if y is negative? Or have I missed something? – Peter Taylor Jun 3 '17 at 12:59
• @PeterTaylor No you haven't, I realized that the challenge is much simpler than I originally thought (because of the method you mentioned). I am going to try and increase the difficulty later. – GamrCorps Jun 3 '17 at 13:05

# Help me golf my numbers! (Part 2) code-challengetest-battery

Thanks for all your help in Part 1! I recently just found out that my language also supports expressions, and we can use those to make our numbers even shorter!

# Challenge

Write a full program that takes in a list of integers less than 2^53-1. For each integer, rewrite it in the shortest way possible using expressions, and output the result.

# Allowed operators

The operators below are given in order of precedence from highest to lowest, with groups separated by empty lines. (These precedence levels are the same as Python.) All binary operators are left-associative, except exponentiation, which is right-associative. Note that some operators are two bytes in length.

**: Exponentiation

* : Multiplication
/ : Integer Division
% : Modulus

- : Subtraction
~ : Bitwise NOT

<<: Left shift
>>: Right shift

& : Bitwise AND

^ : Bitwise XOR

| : Bitwise OR


You may use decimal, hexadecimal, or scientific notation to represent integers in your output (the answers to Part 1 will help you choose the shortest representation for each integer). You may also use parentheses to group subexpressions.

# Scoring

I will post a list of 1000 integers to be used as the test battery. A program's score will be the size of the output for the provided test, where the lowest score wins. A solutions is invalid if any of the expressions do not evaluate to the given integer. There will also be an execution time limit of 20 minutes for all 1000 inputs (roughly 1 second per input) in order to discourage brute-force solutions.

Numbers for the test battery will be chosen according to the following algorithm:

def choose():
msb = randint(0, 52)
return randint(0, 1 << msb)


with duplicates filtered out.

# Sandbox

• Is there anything here that can be clarified?
• Anything else that can make this challenge more fun?
• Sandbox #2 - I don't think bitwise operators will make it too broad. #3 The community has generally agreed that penalties do not make the challenge any more interesting. General advice- make some more rules. Clarify what you mean by "shorten them as much as possible", I had to read that three times to understand. And what do you mean by takes a list of integers? How does one shorten a list using arithmetic? – MD XF Jun 2 '17 at 22:32
• You should specify how your expressions handle precedence and associativity. I assume expressions can use any number literals? – xnor Jun 2 '17 at 22:38
• I think it would be good to say something about you're choosing numbers for the test battery. If they are random, heuristic solutions will be effective (or maybe just hardcoding?). Or, if you intentionally choose inputs that benefit from rarely-useful operations like %, that would be useful to optimize for. – xnor Jun 2 '17 at 22:41
• @xnor Yes, they may. I'll add information about precedence and associativity as well. – musicman523 Jun 2 '17 at 22:41
• @xnor Good point. My plan was to choose randomly, do you think this is a good idea? – musicman523 Jun 2 '17 at 22:42
• I think random would be good. Maybe with some bias towards shorter numbers so they're not all 50-ish bits. It might hard though to beat hardcoding, though the bitwise operations might help. Perhaps you could try to hand-optimizing some random numbers and see how well you do. I think you also need something to rule out brute-force solutions, like a run-time bound. – xnor Jun 2 '17 at 22:46
• I feel like this might be a dupe. – Shaggy Jun 3 '17 at 10:54
• @Shaggy could you link to the duplicate please? – musicman523 Jun 3 '17 at 12:12
• I haven't figured out the right search terms to get me there yet. – Shaggy Jun 3 '17 at 12:29
• @xnor I added a possible algorithm for choosing numbers as well as a time bound. Do you think this is ready for posting? – musicman523 Jun 3 '17 at 18:39
• @musicman523 Having thought about it a bit more, I worry hardcoding the number is too effective. It seems really unlikely a random number allows a shorter arithmetic expression than its digit length. I'm not even sure such a number would appear in 1000 samples. – xnor Jun 3 '17 at 19:14
• I agree. I previously entered 'there can be only one' ( codegolf.stackexchange.com/questions/92962/there-can-be-only-1 ), which was simliar but only allowed using '1'. I don't believe the operators will be useful for almost all numbers, and if you require an operator is used people will just use '+1' most of the time. While a break from your original plan, you could (for example) require using scientific notation, with one number before and after the 'e', so things like '2e5' and '3e7'. That would make operators required and useful. – Chris Jefferson Jun 4 '17 at 21:12
• Maybe make operators cost less than digits. e.g each operator is 2 and each digit is 5 in order to discourage hardcoding – H.PWiz Jul 9 '17 at 15:53
• Not a bad idea. I'll probably revive this at some point. Thanks guys! – musicman523 Jul 9 '17 at 18:43

## Insert a simulated Ken Thompson virus into a program code-golfcode-generation

A Ken Thompson virus is a virus that infects your compiler and other programs. Since it infects all your tools, you can not detect it without using tools from before the virus was introduced.

Your will create a prototype for inserting the Ken Thompson virus into code. The goal of this virus will be to allow you to (fake) destroy any computer running a program infected with it.

Inserting a Ken Thompson virus is defined as follows. Start with an input program P. Your program will output a modified program Q that works as follows:

• If the input to Q is aNouIQ5xKvUfdZVzo0Xs, it will output BOOM (in a real Ken Thompson virus, this would actually do something bad, but since it this is a fake virus, outputing BOOM is done instead).
• For any other input to Q, run program P with that input
• If the output of P is valid source code in the language you are using, insert the Ken Thompson virus into it and then Q will output the resulting infected program.
• Otherwise, the output of Q is just the output of P.

You will write a program that takes P's code as input and produces Q's code as output.

You can use either a currently (at the time of this post) existing programming language, or a subset of one, for this challenge. (The idea is that language you are using would be the target language of some self-compiling compiler, but this is not required.) Since you want to be as subtle as possible, the shortest code (in bytes) wins!

# Find the Harmonic Mean

The harmonic mean of a sequence of numbers is the reciprocal of the arithmetic mean of the reciprocal of each number. For example, the harmonic mean of [1, 2, 3] is 1/((1/1+1/2+1/3)/3) = 3/(1/1+1/2+1/3).

### Input

A list/array/tuple/string with some delimeter/etc. of positive integers which fit within the standard integer/float type of your language of choice.

### Output

The harmonic mean of those integers, accurate to at least 6 (?) decimal places.

### Test Cases

input => output

1 4 4 => 2.0

1 2 3 => 1.63636

527 => 527.0

52 33 400 => 52.6548

7 20 333 45 1 => 4.10481

• Sub-challenge of this. – FryAmTheEggman Jun 6 '17 at 1:28
• If you're going to specify the output accuracy in decimal places you need to restrict the input such that it's possible. A 64-bit floating point number (double) can represent about 16 significant decimal figures, but it can represent numbers up to a bit more than 10^300. – Peter Taylor Jun 6 '17 at 7:30
• @PeterTaylor not really sure how to handle this... I want people to be able to use the most natural method without allowing silly abuses such as "I can only handle one decimal place" or something. – Cyoce Jun 6 '17 at 7:40
• If you guarantee that there will be at most 20 numbers, all in the range 1E-8 to 1E8 then I think that should easily be sufficient. – Peter Taylor Jun 6 '17 at 8:46

## The problem

As I sometimes build bots, I often came across real time image reading. The goal in this problem is to be able to identify a character given pixel representation with the minimal amount of tests. For that, you will have to generate a tree that can identify any char.

## Input

• A list of frequency
• A png file containing each char in a 1 wide red box. Its exact color is #ed1c24 and it is not present in any of the chars.

## Output

A series of specific test that can identify any char. A test is defined by the pixel coordinates, the exact colour to check, the list of chars to have this pixel and the list of chars that donot.

## Example

Let's have a look at only four chars (number 1-4) of equal frequency.

Here we could say that we check for the for pixel in 0,0 (upper left corner). If it is white, it means it's a 1, otherwise we check for the pixel 1,0 (to the right of the upper left corner). If this one is white, it's a 4, otherwise we check for the pixel in 2,2 (the blanck beetween the 3 and the box). If it is white, it's a 3, otherwise it's a 2.

That way we can identify any number in 3 tests at most. If we calculate our score with this layout, it would be 0.25x1 + 0.25x3 + 0.25x3 + 0.25x2 = 2.25 so on average our tree needs 2.25 pixel reading to identify a number.

The solution that lead to that is written like this:

[0,0], [255,255,255], [1], [2,3,4]
[1,0], [255,255,255], [4], [2,3]
[2,2], [255,255,255], [3], [2]


However the best solution for this example has a score of 2. One of the trees that lead to that is

[0,1], [255,255,255], [1,4], [2,3]
[0,0], [255,255,255], [1], [4]
[2,2], [255,255,255], [3], [2]


## Rules

• Count each time you read a pixel.
• Use the number frequency to average your score
• Your score is the sum of the char frequency times the number of pixels read to identify this number.
• What do you mean by 'any number'? If it is more than 1,2,3,4, you should demonstrate what these additional numbers look like. – NonlinearFruit Jun 7 '17 at 13:26
• Good point. I meant any chars, I extended the problem while writting it. I will fix this – Philippe Jun 7 '17 at 13:48

# Sources and Strings

The challenge: Output a string with the same length as the source code.

The requirements:

• Standard loopholes apply, etc., etc.
• Input may not be taken
• The output must be deterministic (for scoring purposes)
• Output must be a string
• Functions and full programs are allowed, no snippets though

The scoring: This is , so the shortest code in bytes wins. However, for each individual character in the source that has a match in the outputted string, your byte score is increased by 2 bytes.

Examples of scoring (of course, most of these aren't working programs):

Program            Output            Score
nn                 ng                2+(1*2)=4
print('h'*14);     hhhhhhhhhhhhhh    14+(1*2)=16
print('prnt'*4);   prntprntprntprnt  16+(8*2)=32
q                  q                 1+(1*2)=3
qwertyuiop         mmmmmmmmmm        10+(0*2)=10
System.out.println("lol");           Invalid=Infinity points


# Prime Factors Zip

Take an integer strictly greater than 2, for example 66. Its prime factors are [2,3,11], when ordered from smallest to biggest. If we zip the digits of those factors, we get [231,1]. Multiplying them yields the integer 231.

If we apply this process back on 231, we get 371. If we apply this multiple times, we get the following sequence:

66
231
371
225
3355
5676
290082
770229
174999300
121860997014
6330393355581
40168037420160
6869559509647641812624
0


At this point, we stop because 0 cannot be factored. We say that 0 is the prime factors zip of 66.

If we start with 19, we get the following sequence:

19
9
33
31
3
3
…


Here, we can see that once we reach 3, we will always get 3. Therefore, 3 is the prime factors zip of 19.

If we start with 22, we get the following sequence:

22
21
37
21
37
…


Here, we can see that once we reach 21, we will always get the loop [21,37]. Therefore, [21,37] is the prime factors zip of 22.

Note that it is possible for an integer to be its own prime factors zip (e.g. 5) or that it is contained in its prime factors zip (e.g. 23 which has prime factors zip [23,6]).

Given an integer strictly greater than 1, output its prime factors zip.

This is , so the shortest answer in bytes wins.

### Test Cases

Input        Prime factors zip
7            7
46           0
48           [22103,72463]
100          0
113          3
1337         [337,63]


### Sandbox

I have no idea (nor have I checked extensively) if it is possible than this procedure never loops for some integers.

• I'd suggest explaining "zip" more precisely. I think it is more commonly called "transpose" and you could try to visualise it by drawing out a matrix? For the never looping thing, I think you can just say the programs don't have to handle that. – FryAmTheEggman Jun 9 '17 at 14:22

# Color the Grayscale

Given an image containing only grayscale colors (for RGB, R==G==B), and a RGB value (that is not grayscale), color the image with your given color.

//Is there a formula that does this? If so this can definitely have objective input and output.

Should this be like a lot of the other challenges?

# Draw an XBox

Here's an X:

\  /
\/
/\
/  \


And here's a Box:

+----+
|    |
|    |
|    |
|    |
+----+


So, for an XBox, just draw an X in a Box:

+----+
|\  /|
| \/ |
| /\ |
|/  \|
+----+


Your input will be a number (in any standard way) that will represent the size of the box. To output the above box, this could be the number of -/|\s (4), or the number of lines/columns (6), or even the intercept of the second diagonal (5) would be acceptable. (Don't ask me to accept the base256 encoding of the output though, as that's one of the many banned standard loopholes.)

Your program or function should then output (in any standard way) the XBox of the given size. If the \/s cross in the same character, place an X (as per Draw a big slash X). For example, here's an XBox three sizes larger than the one above:

+-------+
|\     /|
| \   / |
|  \ /  |
|   X   |
|  / \  |
| /   \ |
|/     \|
+-------+


This is , so the shortest program wins!

• in some obvious way unclear/subjective – MD XF Jun 9 '17 at 16:35
• @MDXF 4 examples weren't sufficient? – Neil Jun 9 '17 at 17:04
• I'm just warning you that it could get closed for being too broad due to that statement. – MD XF Jun 9 '17 at 17:05
• I agree with @MDXF – Beta Decay Jun 9 '17 at 18:03
• @BetaDecay That's all very well, but I'm unclear as to what you want. – Neil Jun 9 '17 at 19:15
• Just a basic explanation of how scaling works. Some examples would suffice – Beta Decay Jun 9 '17 at 21:32
• I've added an example. – Neil Jun 10 '17 at 0:42
• @MDXF Here's my problem. I just tried implementing this in Charcoal, and came up with Try it online!. As it turns out, to produce those example XBoxes I actually need sizes of 7 and 10, but I didn't want to penalise that choice of input just because I hadn't predicted that particular scaling. – Neil Jun 10 '17 at 13:42
• @BetaDecay If you still have any further input it would be appreciated. – Neil Jun 12 '17 at 12:06
• Related – Kevin Cruijssen Jun 15 '17 at 11:57
• @KevinCruijssen Ugh, I even have an answer on that question... I guess the use of specific characters doesn't really sufficiently distinguish this one. – Neil Jun 15 '17 at 12:42
• @Neil Well, using /+x\ instead of just * does make it a bit trickier, but it's indeed a bit too similar imho. – Kevin Cruijssen Jun 15 '17 at 13:11

# Battle of the Bots

Program a bot to compete in a battle with other bots. Each robot has fifteen flags situated around their exterior. Your goal is to have at least one flag left on your robot for as long as possible. Each turn you will move diagonally (or not at all) on a square grid with a width/length equal to the number of bots competing squared (attempting to move off the edge of the grid will result in either you moving adjacent to your previous position, or no movement at all if attempting to move from a corner), and use two or less of the four weapons/shields that are situated facing along the horizontal and vertical rows of the grid. You will choose which weapon you would prefer to have in each of your four slots at the beginning of the game. After 2,500 turns, each bot with flags remaining will receive a 500 point bonus, and the game will end. If all flags have been destroyed before this time, the game will end then. The winner will be the person with the most points at the end of 1,000 matches.

Each bot will begin in a randomly chosen location on the playing field (bots may be on top of each other). Your code will take the form of two python 2.7 functions, one named (name of your submission) start, which will take no input and return 4 values, one for each weapon/shield slot. The first value will be the top of the bot, and they will continue in clockwise order. The integer values to be returned and weapons/shields they represent are shown below:

1: Firestarter, a weapon that will start a fire adjacent to the bot. Fires start at class 1 and increment upward every turn. If, at the start of a bot's turn they are on top of a fire they lose flags equal to the level of the fire. If a fire is at level 3, it spreads fires of level 1 to all directly (not diagonally) adjacent squares that are not already on fire. When a fire reaches level 8, rather than becoming a level 8 fire, it dies, turning back to an "O" on the map, having used up all available burning material. It may then be lit on fire again in the future.

2: Laser, a weapon that destroys one flag on any bot in a straight line from its firing point outwards from the bot.

3: Buzzsaw, a weapon that destroys five flags on any bot adjacent to the bot using it on the side it is used on.

4: Shield, a defensive mechanism that protects flags from lasers and buzzsaws, and is unaffected by our next weapon.

5: Acid Sprayer, a weapon that destroys the weapon facing it on any bot within three spaces of the bot using it in a straight line (not an arc) from its mounting point

Your second function will receive, first the turn number, second a map of the battlefield in a string, with "R" representing robots (including itself), "O" representing empty space, and the level a fire is at representing any fires. The end of a row will be shown with a semicolon ";". For example, if the battlefield looks like this:

OORO131OO
OOOOO1OOO
ROOOOOOOO
OOOOOOOOO
OOOOOOOOO
OOOOOOOOO
OOOOOOOOO
OOOOOROOO
OOOOOOOOO


Each bot will receive this:

OORO131OO;OOOOO1OOO;ROOOOOOOO;OOOOOOOOO;OOOOOOOOO;OOOOOOOOO;OOOOOOOOO;OOOOOROOO;OOOOOOOOO


Next, the bot will receive its X coordinate, and then its Y coordinate, 0 indexed and with the top left corner being 0,0. Finally, the bot will receive how many flags it has remaining.

If multiple bots are in the same square, only a single "R" will be shown. If a bot is standing on the same square as a fire, only the fire will be shown. A bot can tell if it is standing on a fire if its own X and Y coordinates show an integer rather than a "R".

## Sample Bots

Will show sample bots here when they are completed

## Controller

Will show controller here when it is completed

• No copying other bots, or copying with only minor changes.

• No messing around with the judging process, other bots, or writing programs to acquire information that does not come from the inputs given to them, randomizers, or other legitimate sources of information.

• No writing bots specifically designed to prop up other bots.

• Maximum of three submissions per user.

# Meta:

Is the explanation clear enough?

Are there any loopholes for programs to exploit?

Any tags other than ?

• There are a few points which I think could be clearer. 1. The description of the goal ("on average ... one or more flags left on it for the longest period of time") doesn't seem to match the actual scoring mechanism. 2. Must the weapon selection be deterministic? 3. Does a fire spread to adjacent cells on the turn that it becomes level 3 or on the next turn? 4. How do multiple fires interact? 5. Having burnt to level 8, can a cell be set on fire again in the future? 6. Does the acid sprayer work along the same axis-aligned line as the laser, or does it hit in a semicircle? – Peter Taylor Jun 5 '17 at 11:00
• 7. How does a bot know whether the cell it is currently standing in is on fire? 8. I assume that movement is blocked at the edges, but this could be more explicit. – Peter Taylor Jun 5 '17 at 11:01
• Edited to fix concerns. – Gryphon Jun 6 '17 at 17:15
• you should probably use classes rather than two functions, since the ability to remember how opponents behave is useful. – Destructible Lemon Jun 7 '17 at 23:23
• @DestructibleLemon, I've actually moved on from this challenge now, so consider it abandoned. If you want, you can take it over. – Gryphon Jun 7 '17 at 23:25
• But... if I did that I would have three koths on the waiting list! – Destructible Lemon Jun 7 '17 at 23:29
• Wow, that is a lot. I dropped it because I'm working on a new language, but I may readopt it if no one else does after I'm finished. – Gryphon Jun 7 '17 at 23:36