# 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 at 7:51
• @guest271314 You can use this markup to create a tag in a draft: [tag:code-golf] – DJMcMayhem Aug 29 at 15:19

# Sesquiprimes

Given a non-negative integer N, output the Nth sesquiprime integer.

We say that a positive integer I is sesquiprime if I + ⌊I/2⌋ is prime (where ⌊...⌋ is the floor function).

For example, 25 is a sesquiprime because 25 + ⌊25/2⌋ = 25 + 12 = 37, which is prime.

Sequence A158708 is the sequence of prime sesquiprimes.

### Inputs and outputs

• N may be 0-indexed or 1-indexed, please indicate which of the two your solution uses.

• Inputs and outputs must be in the decimal base.

• N may be taken through STDIN, as a function argument, or anything similar.

• The output may be printed to STDOUT, returned from a function, or anything similar.

### Test cases

The following test cases are 0-indexed.

N        Output

0        2
1        5
2        9
4        21
8        45
15       93
16       101
23       149
42       305
100      853
1000     11693


### Scoring

This is , so the shortest answer in bytes wins.

• I don't think the link to prime sesquiprimes adds anything other than a possibility for mistakes by people too lazy to read specs fully (like me) – Jonathan Allan Sep 4 '16 at 17:34
• @JonathanAllan True. Would adding it as a comment be better to make it less appear like part of the challenge? – Fatalize Sep 4 '16 at 17:40
• Including the link as a comment and/or prefixed by Related: would probably be clearer. – Dennis Sep 4 '16 at 18:11
• This seems close to finding primes that are 1 mod 3. – xnor Sep 5 '16 at 10:18

# Slay

This KoTH is based off of the computer game, Slay. Try it out, its way fun.

# TLDR

• You start off with a bunch of small territories: you try to merge them and capture as much land as possible.
• Each territory has its own economy: each hex gives you 1 gold per turn.
• Warriors can capture and protect territory, but cost money to maintain.
• If you run out of money, all units on that territory die

# Map

• A hexagonal map is generated using Perlin noise.
• Each hexagon is randomly assigned to a player. Players will start with a similar number of hexagons, as well as a similar number of territories (see below)
• Hexagons that touch the edge of the map (or a hole in the middle), are on the beach
• Each tile has a 1/5 chance of starting with a tree: Palm tree if on the beach, pine tree otherwise
• Hexagons may contain a warrior, house, tower, grave, or palm/pine tree

# Territory

• A block of 2 or more hexagons with the same owner is considered a territory
• All territories contain exactly 1 house.
• If a territory ever doesn't have a house, it gets one in a random location, preferring: empty hexes, trees, graves, towers, and then warriors. (in that order)
• A territory "death" occurs when it is reduced/split into a single hexagon.
• Houses turn into a pine/palm (if on the beach) tree
• Warriors die (turn into graves) at the start of their next turn
• Towers disappear
• If two territories grow so that they touch, they merge and the smaller territory's house disappears.

### Finanaces

• Each territory has its own reserve/income
• Each territory starts with 10 gold in its reserve
• Territories generate 1 income at the end of each turn for each tree-less hexagon
• If you don't have enough money to pay for your units at the end of your turn, then all of your units in that territory will die (turn into graves) at the start of your next turn.
• If a territory splits, then the larger of the two gets all of the reserve.
• If a territory combines, their reserves combine

### Defense

• Certain objects give defense to its hexagon and all adjacent friendly hexagons:
• Houses (1): cannot be built, but every territory has exactly one
• Towers (2): can be built for 15 gold
• Warriors (strength): see below

# Map objects

### Warriors

• A warrior has a strength between 1 to 4 (inclusive)
• A warrior costs 10*strength to build
• A warrior costs 2*3^(strength-1) gold each turn. This means that a 4-str warrior costs you a whopping 54 gold per turn
• A warrior can move a maximum of 4 hexes each turn. Moving through enemy lands is not allowed. Capturing enemy lands ends the warrior's turn.
• If you move/build a warrior onto a friendly warrior, they combine, and their strength is summed.
• Trying to make a warrior of strength > 4 doesn't work
• If the friendly warrior hadn't moved yet, the new unit can still move
• A warrior can capture an adjacent hexagon if its defense rating is lower than its strength

### Trees

• Trees prevent a hexagon from generating income
• Trees grow at the end of each round:
• Palm trees grow onto all unoccupied adjacent beach tiles
• Any unoccupied tile that is adjacent to two pine trees grows another pine
• Trees can be removed by moving a unit onto them
• Graves turn into a pine/palm (if on beach) tree at the end of the round

# Game flow

• Between 2 to 6 players can play on a single map. (The size of the map depends on the number of players. You can expect about 50 hexagons per player)
• Turn order is randomized, but is consistent within a single game
• Once a player owns all hexagons, they win!
• @zyabin101 still not ready yet. – Nathan Merrill Aug 31 '16 at 21:35
• @zyabin101 + others finished my post! It took me a bit to ensure I got all corner cases correct. – Nathan Merrill Sep 6 '16 at 15:41

# Flexagonal datastructures

Being programmers, watching us flex aren't very interesting. Today we change that! In this challenge you will lex and flex hexaflexagons.

For a video introduction, watch viharts video(s) on flexagons

A flexagon is a shape that you can flex to reveal faces other than the top and bottom one; we are making a hexahexaflexagon, which has 6 faces. See the image below on how to fold a hexahexaflexagon out of a strip of paper.

A shows both sides of the strip. The two white triangles are glued together. This is how you would flex it:

Below is a diagram of possible states and their relationships:

The colored circles represent the 6 triangles with the same number from the first image. Each of the circes have two colors- the bottom most represent the back face (what you would see if you where to flip your flexagon around), which you don't have to consider in this challenge.

The gray circles represent how you can flex your flexagon in any given state: there are 4 different ways to flex it, we call these Left, Right, Up and Down. You don't actually flex in these directions, the important bit is that some are opposite to each other.
If you are in the center you can use Left and Right to go to the other center ones. To get out of the center you use Up and Down. If you aren't in the center you cannot use Left or Right.

Left/Down = clockwise
Right/Up  = anti-clockwise


# Challenge

Create a function or program that take as input what should be on the 18 front faces and the 18 back faces of a flexagon, a sequence of left, right, up and down flexes, and return the 8 visible faces after the flexes.

Example computation:

flex "hexaflexaperplexia"
"flexagationdevices"
[Right, Right, Left]

Divide a strip of paper into 19 triangles:
1/2\3/1\2/3\1/2\3/1\2/3\1/2\3/1\2/3   Front
4/4\5/5\6/6\4/4\5/5\6/6\4/4\5/5\6/6   Back

Write "hexaflexaperplexia" to the front of the paper strip:
1/2\3/1\2/3\1/2\3/1\2/3\1/2\3/1\2/3

hexaflexaperplexia
123123123123123123
h  a  e  p  p  x     Face 1, Initially the front face
e  f  x  e  l  i    Face 2, Initially the back face
x  l  a  r  e  a   Face 3, Initially hidden

Write "flexagationdevices" to the back of the paperstrip:
4/4\5/5\6/6\4/4\5/5\6/6\4/4\5/5\6/6

flexagationdevices
445566445566445566
fl    at    ev       Face 4, up from 3
ex    io    ic     Face 5, up from 2
ag    nd    es   Face 6, up from 1

Flex it [Right, Right, Left]
The initial visible face is 1: "haeppx"
flexing Right ..
The current visible face is 2: "efxeli"
flexing Right ..
The current visible face is 3: "xlarea"
flexing Left ..
The current visible face is 2: "efxeli"
flexed [Right, Right, Left]!

outputting "efxeli"


Example input and expected output:

> hexaflexaperplexia flexagationdevices RRL
= efxeli

> loremipsumdolorsit hexaflexamexicania LUU
= riuort

> abcdefghijklmnopqr stuvwxyz1234567890 UL
= I can't flex that way :(

> abcdefghijklmnopqr stuvwxyz1234567890 RRRRLLUDDUUUULDD
= uv1278


# Rules

• You may take input and return output in any reasonable way
• If the input is impossible, you should indicate so in some way that is distinct from regular output
• Standard loopholes apply
• This is Codegolf. Shortest code in bytes win.
• The diagram is at best confusing. The overlapping arrows are hard to read, and the fact that they're directional is just plain wrong. Then the example computation is very cryptic. To be useful the examples need to explain what each line of text means, and they should avoid duplicating letters. It would be good to make the first example show the output with zero flexes. I made my first hexaflexagon at least 25 years ago, and I carried one in my wallet for years to play with when bored, so if I find this spec lacking imagine how it must look to people who don't know anything about them! – Peter Taylor Sep 9 '16 at 22:11
• @PeterTaylor Is this remotely better? – BlackCap Sep 9 '16 at 23:09

# Draw me a Brick Wall!

I'm drawing up a plan for my house extension - and I need a simple graphic for walls...

# The Challenge

Your task is to create a program, which takes an input of the wall's dimensions and draws a brick wall, in the style of the one below.

[__][__][__][__]
_][__][__][__][_
[__][__][__][__]
_][__][__][__][_
[__][__][__][__]
_][__][__][__][_


Please notice that the rows alternate between beginning on a full brick ([__]) and a half brick (_]), to create a more realistic, stable wall.

The input will be two integers, separated by a single comma, such as 4,3 or 2,6. You can assume both integers are positive and larger than 0.

The first integer specifies the width (in bricks) and the second specifies the height (in rows of bricks).

# Rules / Notes

• This is , so the shortest code (in bytes) wins. However, don't feel like you have to beat everyone else to post your solution - I'd love to see your code!
• Standard loopholes apply, no reading from external files.
• You may optionally take the input with brackets/braces, for example (4,3) or [4,3] as long as you specify this in your answer.
• You should take the input from STDIN and output on STDOUT - if your language does not have these, please use the nearest equivalent.

## Test Cases

Input: 1,1

[__]


Input: 2,4

[__][__]
_][__][_
[__][__]
_][__][_


Input: 5,10

[__][__][__][__][__]
_][__][__][__][__][_
[__][__][__][__][__]
_][__][__][__][__][_
[__][__][__][__][__]
_][__][__][__][__][_
[__][__][__][__][__]
_][__][__][__][__][_
[__][__][__][__][__]
_][__][__][__][__][_


# Example: Python 3, 65 bytes

This is somewhat golfed but still readable.

w,h=eval(input())
for i in range(h):print(('[__]','_][_')[i%2]*w)

• very closely related or dupe – Emigna Oct 28 '16 at 13:11
• this one is related too I think – Dada Oct 28 '16 at 13:12
• Hi, welcome to PPCG! This seems like a great first challenge. There are a few related challenges regarding brick walls, like this one (inputs as different sized bricks) or this one (is it stable). But, I think this challenge is different enough. Instead of having different sized bricks as input, this simply asks for two inputs for an NxM wall, which is imho different enough from the first challenge. – Kevin Cruijssen Oct 28 '16 at 13:12
• @Emigna I'd like to think they're different, as this one is a 'more static' string to print and doesn't require an algorithm to work out a stable wall first - however I understand that they are closely related. – FlipTack Oct 28 '16 at 13:13
• @Dada Hmm, that one might be more related than the two related ones linked by me, and more towards a dupe (despite the different ASCII used for the bricks themselves). But we'll perhaps wait on some more feedback from other users. – Kevin Cruijssen Oct 28 '16 at 13:14
• The one Dada linked is similar, but not quite a dupe. The brick structure is quite a bit more flexible in Luis' challenge, given that the input is total character width and height plus a horizontal offset, whereas here it's in number of bricks. – AdmBorkBork Oct 28 '16 at 13:21
• I'd still call the previous brick printing one a dupe. The offsetting pattern is the same, and in most of the answers it would be easy to replace constants with inputs. – xnor Oct 29 '16 at 6:11

# The smallest circles

Challenge

This is a variant of the smallest-circle problem, but instead of one circle, you get three. Given a list of coordinates, output three circles such that the following conditions are met:

1. Each input coordinate must be located inside or on the perimeter of a circle.
2. The sum of the radii of all three circles must be minimal.
3. The coordinates and radii of all three circles must be non-negative integers.

You must place all three circles. You may place overlapping circles. A circle with a radius of zero that is directly on top of an input coordinate is considered to be covering that input coordinate.

Input

A list containing between 1 and 1000 pairs of integers, inclusive. Each pair of integers represents an xy-coordinate. Use whatever input format you want to use.

For example, the input...

1,1;1,2;2,2;3,3

... can be drawn like this:

Output

A list of three integer triples. Each triple contains an x coordinate, followed by a y coordinate, followed by a radius. The triples, and the integers within each triple, must be distinguishable from one another. Otherwise, the output format is not important.

Example:

1,1,1;2,2,1;3,3,2

Given this example output, circles would be drawn at (1,1), (2,2), and (3,3). The first two circles would have a radius of 1, and the third would have a radius of 2. The sum of the radii would be 4.

Test case explained

Given the input...

1,1;1,2;2,2;3,3

... you could output...

1,2,1;3,3,0;0,0,0

... or you could output...

1/2/1
3/3/0
0/0/0

The radii sums to 1, and since it is not possible to draw three circles whose radii sum to less than 1 that encompass or touch all four points, this is the correct answer.

(maybe too)

• The text says that the list is colon-delimited, but the example is semicolon-delimited. It would help readability to mention that you can place three circles at some point before "The sum of the radii of all three circles is minimal". It's not clear whether the coordinates and radii of the circles must be integers, nor whether the radii must be non-zero. Finally, some test cases would be nice. – Peter Taylor Nov 7 '14 at 18:50
• If I didn't fully address any of the comments above please let me know. – Rainbolt Nov 7 '14 at 19:41
• If the input can contain up to 1000 points it might help to have a large test case too. – trichoplax Jan 20 '16 at 22:30
• For large numbers of input points, how will you assess whether the output is of minimal total radius? Is a proof required or is it sufficient that no other answer/person can find a counterexample? You could also have a judge program / reference implementation to define the correct total radius. – trichoplax Jan 20 '16 at 22:31
• @trichoplax Hopefully I'll have a reference implementation before I post. If I decide that I am too lazy for that, then I will assume answers are correct until someone finds a counterexample. I will come up with a larger test case. – Rainbolt Jan 20 '16 at 22:37
• Does the rigid I/O format really add anything interesting to the challenge? meta.codegolf.stackexchange.com/a/8077/8478 – Martin Ender Jan 21 '16 at 10:55
• @MartinBüttner I completely relaxed the input format, and I somewhat relaxed the output format. Thanks for the feedback. – Rainbolt Jan 21 '16 at 14:12
• @Rainbolt If I read the output section right, you're allowing any distinguishable delimiters for the output now? Then it might be clearer if one of the two example formats didn't use commas as the inner delimiter (maybe use spaces for the second example or so). – Martin Ender Jan 21 '16 at 14:15
• The rewrite states two conditions which must be met, but there's a third one hidden down in the output section: that the coordinates and radii must be integers. That should be up in the first section. – Peter Taylor Jan 19 '17 at 21:13

# Make A Rotating Emoji Globe

Your task is to make a globe out of the following characters, with the line being cleared ever 1/3 of a second:

🌍🌎🌏


You must clear the line your emoji globe on it and print the next one every approximate 1/3 of a second.
Output may be to the terminal or elsewhere.
The program must also continue until interrupted on purpose.
Also, your code may not contain the emoji globes themselves, but it may contain Unicode escapes.

This is , so standard loopholes & rules apply.
May the best coder win...

• Simple, fairly identical to this in that you simply display a cycle of things, Most answers from that will fairly easily work copied over. – ATaco Feb 7 '17 at 2:47
• @ATaco How could I make it more challenging? – ckjbgames Feb 7 '17 at 2:50
• @ATaco I think it's sufficiently distinct--it requires clearing the line (an option in the other challenge), display unicode characters, and only displaying one character at a time. – Conor O'Brien Feb 7 '17 at 3:24
• @ConorO'Brien I still feel I could distinguish my challenge a bit more, though... – ckjbgames Feb 7 '17 at 17:48
• Define clear the line? Does it have to clear the line, or does the whole terminal suffice? – Rɪᴋᴇʀ Feb 7 '17 at 18:13
• @EasterlyIrk Clearing the screen can be done in any way, as long as the globe appears to rotate onscreen. – ckjbgames Feb 7 '17 at 21:40
• It's even more similar to codegolf.stackexchange.com/questions/101289/loading-forever. Printing a single character that cycles – 12Me21 Feb 7 '17 at 22:26
• @12Me21 How can I make it different, then? – ckjbgames Feb 7 '17 at 22:35
• Maybe you could require them to draw an actual rotating globe, given a map image. (It's a lot more complicated though) – 12Me21 Feb 7 '17 at 22:37
• @12Me21 I just had the idea to add a moon rotating around the earth. Help me think of how to implement it. – ckjbgames Feb 7 '17 at 22:59
• You could make it use the different moon phase emoji to display the proper phases or something – 12Me21 Feb 7 '17 at 23:05
• @12Me21, an actual rotating globe is potentially a dupe of codegolf.stackexchange.com/q/24326/194 - certainly some of the answers could be copied across. – Peter Taylor Feb 9 '17 at 9:02
• Take as input the "spin speed" (ms delay), althought that's fairly trivial to handle. – Carcigenicate Feb 10 '17 at 22:13
• @Carcigenicate I will do that. – ckjbgames Feb 12 '17 at 21:54

# Tron Game

Write a Tron bot!

The aim of the game is to make as many moves on a grid as possible without moving onto a space that has already been occupied in the current game. If your bot is unable to make such a move, it loses the round. The board does not wrap so bots can not go off the side of the arena.

## Game IO:

Your bot will be written in python and will create a class that inherits from BotSkeleton. An example test bot is shown below.

from bot_skeleton import BotSkeleton
from typing_hints import PositionDict, Position
from board import Board
from typing import List

import random

class Test(BotSkeleton):
def make_move(self, board: Board, positions: PositionDict) -> Position:
self.board = board
self.position = positions[self.bot_id]
valid_moves = self.get_valid_moves()
try:
return random.choice(valid_moves)
except IndexError:
return None

def get_valid_moves(self) -> List[Position]:
moves = filter(self.board.position_valid, ((self.position[0]+1, self.position[1]),
(self.position[0]-1, self.position[1]),
(self.position[0], self.position[1]+1),
(self.position[0], self.position[1]-1)))
return list(moves)


(Type hints are not required but illustrated here to help understanding)

• position is a 2-long tuple containing 2 integers.
• positions is a Dict[bot_id, position]
• board can be indexed with a position.
• get_random_empty_pos() -> position - returns a empty position at random in the board
• position_valid(position) -> bool - returns if this move is valid (but not next to the position given)
• copy() -> List[List[int] - returns a 2d list that can be modifiable of the current board state
• EMPTY - the id for an empty space
• The value you return must be a position, and must also have a distance of 1 from this, not including diagonals.

Built in attributes for BotSkeleton:

• log - contains a file object that you may write to
• no_bots - the number of bots the game began with
• bot_id - you're bot's id number.

Methods in Board:

• get_random_empty_pos() -> Position - Returns a position at random that is empty
• position_valid(pos: Position) -> bool - returns if a position is inside the board and is currently empty
• copy() -> Board - return a copy of the board that is writable

## Tournament structure

• Every bot will get pitted against every other bot in a giant arena
• That is to say every single bot will be in every battle
• The size of the arena will be (30, 30). This may be increased depending on number of bots entered.

### General rules that I can't find better places for

• Your bot may NOT use any file storage except for write-only access to the log file provided
• Your bot must be written in Python 3. Sorry java people
• You may enter as many bots as you want
• Your bot must not attempt to subvert the game state

### I reserve the right to disqualify any bot from the competition

(but shall only do so after telling you I will do so and you not making any changes required)

• Results here

## Sandbox notes:

• Should there be a minimum starting distance between players?
• What happens if two bots go on the same position at the same time? – Katenkyo Mar 23 '16 at 11:10
• Is the goal really to survive as many moves as possible, and not to survive longer than the other guy? – feersum Dec 7 '16 at 14:03
• probably change "sorry" to "sorry not sorry" – Destructible Lemon Feb 11 '17 at 12:20

# Part II: Triangular Chebyshev Distance

The Chebyshev distance on a regular grid is the number of orthogonal or diagonal steps one needs to take to reach one cell from another. That is, we can move either through the edge of a cell, or through a corner, to a neighbouring cell.

We can define a similar distance on other grids, for example the triangular grid. We can address the individual cells in the grid with the following indexing scheme, where each cell contains an x,y pair:

    ____________________________________...
/\      /\      /\      /\      /\
/  \ 1,0/  \ 3,0/  \ 5,0/  \ 7,0/  \
/ 0,0\  / 2,0\  / 4,0\  / 6,0\  / 8,0\
/______\/______\/______\/______\/______\...
\      /\      /\      /\      /\      /
\ 0,1/  \ 2,1/  \ 4,1/  \ 6,1/  \ 8,1/
\  / 1,1\  / 3,1\  / 5,1\  / 7,1\  /
\/______\/______\/______\/______\/___...
/\      /\      /\      /\      /\
/  \ 1,2/  \ 3,2/  \ 5,2/  \ 7,2/  \
/ 0,2\  / 2,2\  / 4,2\  / 6,2\  / 8,2\
/______\/______\/______\/______\/______\...
\      /\      /\      /\      /\      /
\ 0,3/  \ 2,3/  \ 4,3/  \ 6,3/  \ 8,3/
\  / 1,3\  / 3,3\  / 5,3\  / 7,3\  /
\/______\/______\/______\/______\/___...
/\      /\      /\      /\      /\
.  .    .  .    .  .    .  .    .  .
.    .  .    .  .    .  .    .  .    .


Now the Chebyshev distance on this grid is again the minimal number of steps across edges or corners to get from one cell to another. So you can move from 3,1 to any of its 12 neighbours:

2,1 4,1 3,2 (through edges)

3,0 1,2 5,2 (the opposite triangle through corners)

2,0 4,0 1,1
5,1 2,2 4,2 (the other triangles through corners)

For instance, the distance from 2,1 to 7,2 is 3. The shortest path is generally not unique, but one way to make the distance in 3 steps is:

2,1 --> 4,1 --> 5,1 --> 7,2


## The Challenge

Given two coordinate pairs x1,y1 and x2,y2 from the above addressing scheme, return the Chebyshev distance between them.

You may assume that all four inputs are non-negative integers, each less than 128. You may take them in any order and arbitrarily grouped (four separate arguments, a list of four integers, two pairs of integers, a 2x2 matrix, ...).

You may write a program or a function and use any of the standard methods of receiving input and providing output.

You may use any programming language, but note that these loopholes are forbidden by default.

This is , so the shortest valid answer – measured in bytes – wins.

## Test Cases

Each test case is given as x1,y1 x2,y2 => result.

1,2 1,2 => 0
0,1 1,1 => 1
1,0 1,1 => 1
2,1 7,2 => 3


Will add more test cases when I have a reference implementation.

• @trichoplax Yes, thank you. With the slow response to the Manhattan variant, I do wonder whether this one will be a bit too tricky, but we'll see. :) – Martin Ender Apr 4 '17 at 21:28
• "I do wonder whether this one will be a bit too tricky, but we'll see. :)" I've found a solution for this one, but not for the other one yet. ;) – Kevin Cruijssen Apr 5 '17 at 12:01
• @KevinCruijssen Oh, would you mind sharing it? :) – Martin Ender Apr 5 '17 at 12:06
• I always make my answers in Java 7 btw, so I'll still be beaten by golfing answers. But this is what I came up with (I've also added an explanation of how I came up with the solution in the TIO footer): Try it here. – Kevin Cruijssen Apr 5 '17 at 12:23
• Hmm, I just took another look at your part 1 challenge and realized my solution above for part 2 is incorrect.. :( Based on your current test cases I falsely assumed x1,y1 is always smaller than x2,y2. So my code fails for a test case like 4,1 1,3. Back to the drawing board.. Also, as to why I think this challenge is easier than part 1: In part 1 you had to determine whether the triangle was facing upwards (available: left; right; below) or facing downwards (available: left; right; above). With this challenge all 12 surrounding triangles - regardless of orientation - are accessible. – Kevin Cruijssen Apr 7 '17 at 8:22
• @KevinCruijssen but the exact coordinates/orientations of those 12 neighbours also change, right? – Martin Ender Apr 7 '17 at 8:24
• Yeah, was about to edit my comment again when I realized that.. If you have more test cases I'll take another look at this part 2. I'll start with part 1 for now. (PS: Have a nice weekend - apparently I can use it.. >.>) – Kevin Cruijssen Apr 7 '17 at 8:25
• Me again, more than one year later. I've currently set a bounty for your Part 1 challenge to give it more attention, which you may or may not have noticed based on the new answers given. If you have time, could you add more test cases for this one? – Kevin Cruijssen Jun 29 '18 at 8:40
• @KevinCruijssen I'm not sure how soon I'll get around to that, because I'd want to write a reference implementation for that. If you want it post it soon, feel free to add them yourself (and optionally post the challenge yourself if you like). – Martin Ender Jun 29 '18 at 16:26
• Oh no, I'll patiently wait. I'm going on vacation soon anyway, so I won't have time to answer during that time. I just made that comment above as a reminder so it can hopefully be posted in the not to distant future. :) – Kevin Cruijssen Jun 29 '18 at 16:42

# Mark Duplicates

Given a list of non-negative integers, find the values which are duplicates and mark their positions.

For example, given [1, 2, 3, 2, 1], the output could be [1, 1, 0, 1, 1] where each 1 signifies that the value at that position is duplicated elsewhere in the array and each 0 signifies that the value at that position is unique.

Your output may use either 0 and 1, boolean values for false and true, or any other two distinct values as long as you remain consistent.

This is so minimize the length of your code.

## Test Cases

[] -> []
[5] -> [0]
[0, 1] -> [0, 0]
[2, 2] -> [1, 1]
[1, 2, 3, 2, 1] -> [1, 1, 0, 1, 1]
[6, 3, 6, 3, 5, 2, 3] -> [1, 1, 1, 1, 0, 0, 1]

• Ironically, I feel this is a duplicate of (or at least closely related to) and existing challenge but I can't find it at the moment. – Shaggy May 24 '17 at 10:43
• Would we have to use 0 & 1 or could we use any 2 distinct & consistent values? – Shaggy May 24 '17 at 11:06
• I.e Nub Sieve? – Adám May 24 '17 at 11:27
• @Adám I previously made a challenge for nub sieve. This is slightly different since we aren't choosing positions to filter for only the unique values. – miles May 24 '17 at 18:43
• @Shaggy Yes, any choice of output values is fine as long as its two distinct values that you use consistently. – miles May 24 '17 at 18:45
• Isn't this just NOT nub sieve? – Adám May 24 '17 at 18:47
• @Adám For the [1, 2, 3, 2, 1], nub sieve could be [1, 1, 1, 0, 0], [0, 1, 1, 0, 1], [0, 0, 1, 1, 1], [1, 0, 1, 1, 0], and the not of each is [0, 0, 0, 1, 1], [1, 0, 0, 1, 0], [1, 1, 0 ,0, 0], [0, 1, 0, 0, 1]. – miles May 24 '17 at 19:21
• I think this would be interesting if the first time an entry appears it's not counted as a duplicate. – xnor May 24 '17 at 19:37
• @xnor Wouldn't that be not( nub-sieve( x ) )? – miles May 24 '17 at 20:23
• How does nub-sieve work? My suggestion is because it means the position of the item matters rather than just its value, so it's not just mapping each entry x to l.count(x)>1. – xnor May 24 '17 at 20:26
• The first occurrence of a value is marked true and all subsequent occurrences of the same value are marked false. Nub-sieve. My previous challenge for distinct sieves is a relaxed variant to nub-sieve. For [1, 2, 3, 2, 1], a proper nub-sieve would be [1, 1, 1, 0, 0], and not of that would be [0, 0, 0, 1, 1]. I do agree with that last sentence about how most solutions in golfing languages would probably just count occurrences. – miles May 24 '17 at 20:44
• @miles can I adopt and post this abandoned proposal? – programmer5000 Jun 9 '17 at 1:34

### Table parser, code golf

Input

|===========|=============|==============|
|Left align |  Right align| Center align |
|===========|=============|==============|
|This       |         This|     This     |
|-----------|-------------|--------------|
|                column                  |
|-----------|-------------|--------------|
|will       |                            |
|-----------|          will be           |
|be         |                            |
|-----------|-------------|--------------|
|left       |        right|    center    |
|-----------|-------------|--------------|
|aligned    |      aligned|   aligned    |
|-----------|-------------|--------------|
|and can be |    vertical-|              |
|multilined | align middle|  as default but a bit long line |
|with <br>  |             |              |
|-----------|-------------|--------------|

Output should be valid HTML. And I am thinking of following requirement specs.

• alignments (left, right, middle)
• border thickness (normal -, |, bold, =,||)
• with table headers or without
• rowspans, colspans
• multiline & vertical-align is always middle

What do you think?

• I guess figuring out cells and row/colspans is enough work, so handling bold and italic could be omitted, maybe. – Joey May 9 '11 at 12:15
• Also, should this be a code golf or a challenge? – Joey May 9 '11 at 12:18
• code-golf @joey. and I am gonna leave bold and italic out. I was not sure it was hard enough :D – YOU May 9 '11 at 13:22
• Can cells contain more than a line of text? I.e. do long contents wrap or do they extend the cell? – Joey May 9 '11 at 13:35
• @Joey, yeah, a bit more complicated now, multiline involve vertical-align, so I set that as middle as default, what do you think? – YOU May 9 '11 at 13:49
• Yikes :D. Well, I was just pondering a few ways of figuring out the layout and determining rowspans would be much easier if all rows are the same height ;). Should be ok, but bear in mind that it makes judging correct vertical align difficult. Given the current last row the valigns could be either one of mmm, ttm, tmm, btm, bmm. No show-stopper but something to keep in mind for test cases and scripts. – Joey May 9 '11 at 13:53
• @Joey, yeah, to judge top, middle, and button, we need a blank row between every table row, just like a space in right, right, and center, so I guess I need to make vertical-align as middle as default. – YOU May 9 '11 at 14:06
• So vertical align will not vary and always be middle, if I understand you correctly? – Joey May 9 '11 at 14:07
• @Joey, yeah .. and for multiline items you just need to put <br> between and can be, multilined, and too, if those are supposed to be same line, input will be |and can be multilined too | ....... | ..... | . – YOU May 9 '11 at 14:10
• I think your multi-column cells are ambiguous: the last row shows that text can extend beyond the ASCII art column width, so we cannot use the horizontal alignment of |s to judge colspans. Therefore, the 4th and 5th rows could span 1 and 2 columns (as visually, but unreliably indicated) or 2 and 1 columns. Example – Adám Jun 5 '17 at 7:20
• @Adám, thanks for taking a look. Yeah, might be that's the reason there is not much interest on this. – YOU Jun 5 '17 at 10:33
• @YOU Also, this is a very complex challenge, pretty much implementing a large subset of the Wiki markup for tables. Maybe you should narrow the scope by removing all formatting; alignment, borders, headers (these are also ambiguous), and just focusing on converting the -| style table into HTML. Maybe even remove the row and column spans? – Adám Jun 5 '17 at 10:42
• I don't remember why I put all those things in, may be similar challenge was there already, for simple tables, but I don't know. I need to look up more. – YOU Jun 5 '17 at 14:11
• @Adám, removed rowspan, colspan, multiline and vertical align. Not sure it could be duplicate entry now. – YOU Jun 5 '17 at 14:17
• @programmer5000, became duped, because of you guys suggestion. I rollbacked. – YOU Jun 9 '17 at 15:37

# Line up for golf!

• The comments in the test cases reduce their usefulness as test cases. Moreover, the first one contradicts the "full specification", and the second one adds to it. The spec should contain everything needed to justify the correctness of the test cases. You also need to specify desired behaviour when there is no solution, and to include a test case for that scenario. – Peter Taylor Mar 7 '14 at 14:04
• How are conditionals to be interpreted when mixed in a single full condition? Alice is 1st or 1st to last and in front Bob or 1 space behind Bob – John Dvorak Mar 7 '14 at 14:12
• This seems like a good challenge, but Peter Taylor and Jan Dvorak's concerns should be addressed. – Hosch250 Mar 8 '14 at 18:42
• @PeterTaylor Edited, but how does the first one contradict? – Doorknob Mar 10 '14 at 2:32
• @JanDvorak Edited to clarify. – Doorknob Mar 10 '14 at 2:32
• Another concern: What if there is no solution? What if there is more than one? – John Dvorak Mar 10 '14 at 6:04
• Please delete this now that it is posted. – programmer5000 Aug 1 '17 at 16:07

This message is open for anyone to adopt and post to main. For more details, see the chat room or meta post.

# Ping an IP address continually and report the dropped to returned ratio

Create a console program that pings an IP address at most once per second and reports the ratio of dropped to returned packets to the screen in real time.

The IP address will be provided on the command line in standard IPv4 notation. (eg. 192.168.0.1)

The 'ping' method should be ICMP echo (See here for a summary of ICMP packet structure) with a packet size of at least 32 bytes.

Your program must be "standalone" and cannot rely on external programs, libraries, or resources.

This is so let the shortest answer win

• ping isn't enough? – TheDoctor Apr 7 '14 at 19:31
• ping works great, except you have to tell it when to stop to get the final tally – David Wilkins Apr 7 '14 at 19:32
• I think you're assuming that everyone will interpret this as sending the same ICMP control packet that ping sends, but it would be an improvement to the question both to make this explicit and to link to some documentation about ICMP. – Peter Taylor Apr 7 '14 at 22:46
• Actually I left it ambiguous. Any IP request that elicits a response can be considered a ping. – David Wilkins Apr 8 '14 at 1:00
• Alright, lets make it easier and say ICMP specifically... – David Wilkins Apr 8 '14 at 12:16
• Well this doesn't have enough upvotes...I'll leave it in the sandbox, but likely it will not be posted – David Wilkins Apr 9 '14 at 12:17
• Hello! This looks like a good but abandoned meta post, would you be willing to offer it for adoption? (If you want to, you can still post to main.) Due to community guidelines, if you don't respond to this comment in 7 days I have permission to adopt this. – programmer5000 Jun 9 '17 at 16:34
• @programmer5000 be my guest :) – David Wilkins Jun 9 '17 at 16:40

This is a proposal adopted by programmer5000. Any feedback before I post it?

# Seven-segment usage

I have an old digital clock and I am concerned the individual segments of the digits might run out of magical binary energy or whatever powers them. To know which of the segments on the clock will fail first I want to know what is the percentage of time each segment is lit.

The challenge is to compute the percentage of time any segment on a digital clock is lit.

## Input

The input will be in the form X.L, where:

• X is a number from 1 to 4. 1 is the left-most number of the clock, 4 the right-most
• L is a letter from a to g or a number from 1 to 7
• the separator can be changed to fit your needs (no separator is an option)

## Output

The output, is a percentage, given with at least 2 figures after the decimal point. It can be rounded or truncated to the closest value if you want to keep a limited number of digits.

Valid outputs: 0.74, 32.47, 7.5 (for 7.50)

The clock is in 24 hours format (so 22:45 is a valid time).

We consider the clock started working at 0:00 so the challenge is effectively working out what percentage of a complete day a single segment is lit.

The first number is not lit when it is 0.

Lit segments for each number:

• 1: b c
• 2: a b d e g
• 3: a b c d g
• 4: b c f g
• 5: a c d f g
• 6: a c d e f g
• 7: a b c
• 8: a b c d e f g
• 9: a b c d f g
• 0: a b c d e f

## Examples

• 1.b => 58.33
• 3.e => 33.33
• 2.d => 70.83
• 4.d => 70.00

Full list of outputs here

## Winner

Code golf, most probably, though I am not sure yet this is the best format (I am not too interested in the input parsing and the output formatting, they might be an obstacle to golfing?)

• AIUI there are 28 valid inputs, so you could provide a full list of test cases as a pastebin. I would remove "No hard coding of results": if hard-coding the 28 cases is shorter than the calculation, then IMO that's a flaw which makes the question not worth bothering with at all rather than something which can be worked around; and the issue of whether or not an answer "hard-codes the results" is likely to be grey rather than black or white. – Peter Taylor Mar 3 '16 at 10:54
• List of results added, I'll need to double check them. Hard coding removed, yes I don't see how "cheating" would be an issue. Any hard-coding would have to be quite constructive to be efficient. – drolex Mar 3 '16 at 11:29
• I am removing limitations on the output as well, I don't think it brings anything to the challenge. I have started to golf a solution in python, I think there are a few interesting possibilities to optimise the use of strings describing segments used for each digit. – drolex Mar 3 '16 at 15:56
• Can I post this abandoned proposal? – programmer5000 Jun 9 '17 at 13:00
• @programmer5000 certainly, just try to make it better :) – drolex Jun 9 '17 at 13:05

# What is your Operating System?

I can't believe we haven't had this one before

To avoid any doubts about what constitutes a separate OS, you must return an index into your chosen subset (containing minimum two) of the following OS families. You may order your set as you like, so include your ordered set, and state if you use zero or one based indexing. You may also bunch together families you cannot distinguish between.

Windows, Minix, Linux, macOS, BSD, HP-UX, AIX, Solaris, Unix, Z/OS, OS/2, QNX

Your score is your byte count divided by the square of the number of indices your code can return – given that it is run on the appropriate OSs, of course.

You do not have to account for virtual machines, emulation layers etc., e.g. WSL and Wine.

### Examples

Your code can detect Windows, macOS, AIX, and Linux. It returns 0 for Windows, 1 for macOS, 2 for AIX, and 3 for Linux. Your score is a sixteenths of your byte count.

Your code can distinguish between Z/OS, OS/2, and UNIX/Linux/AIX. It returns 1 for Z/OS, 2 for OS/2, and 3 for any UNIX-like OS. Your score is a ninth of your byte count.

• 2 is definitely better than 1. After that I think it may just be your preference for the kinds of answers you want. I think 3 will promote more answers that reach, while 2 will promote more 2 answers. However, if you really want to reach maybe make the denominator grow as a square? These scoring mechanisms are unfortunately very important to these kinds of challenges as well as very hard to figure out beforehand. I'd ask around and see what other people think! – FryAmTheEggman Jun 15 '17 at 0:37
• @FryAmTheEggman Thanks. – Adám Jun 15 '17 at 0:39
• Are not macOS, BSD, and Linux Unix? Is OSX considered the same as macOS? – Sriotchilism O'Zaic Jun 21 '17 at 14:53
• The I/O requirements are rather strict, could you not just print/return the name of the OS? – musicman523 Jun 21 '17 at 14:56
• @WheatWizard Yes, but you may pick whichever many you want from that list, so you can bunch all Unixes together or keep them separate, or you can detect specific flavors while also detecting vanilla Unix. – Adám Jun 21 '17 at 15:02
• @musicman523 I'd rather have comparable output from all solutions. – Adám Jun 21 '17 at 15:03
• It seems like people with access to proprietary OSs will have an advantage in this problem. For example, to ensure my code runs on Windows I have to buy windows, because I don't own it. I happen to own a copy of OSX, but other users might not given me an advantage. I feel like this is problematic. (also is OSX considered the same macOS?) – Sriotchilism O'Zaic Jun 21 '17 at 15:09
• @WheatWizard You're right, but that will be problematic in detection of OSs no matter what the challenge is. And yes, good luck testing your solution on Z/OS… – Adám Jun 21 '17 at 15:34
• It's not just that. If I claim to detect Windows, which versions of Windows do I have to test it on? And what can I assume about e.g. the C header files that are available? – Peter Taylor Jun 21 '17 at 15:35
• @WheatWizard Oh, and yes, OSX and macOS are the same (I don't expect anyone to submit an answer that will run on MacOS 9-) – Adám Jun 21 '17 at 15:35
• @PeterTaylor Good point. Any ideas how to fix this or is it doomed? – Adám Jun 21 '17 at 15:36
• I suspect that the difficulties around specification and testing might explain why this hasn't been asked already. – Peter Taylor Jun 21 '17 at 15:44
• Why numbers only? Why not just outputs? – CalculatorFeline Jun 21 '17 at 16:00
• Is the set of OSes listed there exhaustive? (I've done some programming on SunOS in the past, for example, although I don't have access to it right now.) Also, "Unix" seems a bit strange to have in the list; many of the listed OSes (e.g. BSD and Solaris) are flavours of Unix. It's also worth being aware of cases like WSL and Wine; which OS should they count as? – user62131 Jun 22 '17 at 10:28
• @ais523 "Unix " allows submissions to bunch together various flavors as one, and also allows differentiating the other Unixy OSs from vanilla Unix. I'll add a note about virtual machines etc. – Adám Jun 22 '17 at 14:54

# A Game of Knights

In this King of the Hill, you control 10 Knights. You need to surround your enemy before they surround you.

Each Knight has 3 possible actions:

• Dash: Move 3 squares in a cardinal direction. If there is a knight in your path, move as far as you can.
• Leap: Move 2 squares in a cardinal direction. If there is a knight on your destination square, don't move at all.
• Push: Move 1 square in a cardinal direction. If there is a knight on your destination square, and no knight or wall behind him, you both move 1 square.

Each round will have a Planning Phase and then an Action Phase.

Planning:

During the planning phase, players will alternate creating a plan until both players have created 10 plans.

• A plan consists of either an action type or a cardinal direction (not both).
• A plan also includes the knight that will perform the action
• All plans are revealed to both players

Action:

• Actions occur in the same order that they were planned.
• If you planned an action type, you will be able to choose the direction. If you planned a cardinal direction, you will be able to chose the action type you want.

After the action phase, if any knights are on the same location they started at (at the start of the round) are captured and removed from the game. You win by capturing all other knights.

Other info:

• Cardinal means North, East, South, or West
• The board is a 10x10 board. Your knights start as a line at the bottom of the board.
• Walls block movement and cannot be pushed.
• You don't have to plan an action for every knight, and a knight can take multiple actions.
• There are a maximum of 1000 rounds. After those 1000 rounds, the winner is the player with the most knights. (A tie is allowed).
• The starting player for a game is randomized, and that player starts every round.

You have won the game when you opponent cannot make any mobility actions.

• Man, now I want to play this in person. – DLosc Feb 18 '17 at 21:17
• Isn't it possible to form your knights into a solid 2×5 rectangle (thus immune to pushing), away from the starting squares, before the enemy can move and push it? That would guarantee you couldn't lose. Also you should clarify whether you can plan two actions for the same knight, and if you can, whether it gets to take both or only one. – user62131 Feb 18 '17 at 23:14
• @ais523 movement is not simultaneous. You start as a 1x10 line. A knight could take 10 moves on a round – Nathan Merrill Feb 18 '17 at 23:52
• To be clear, as long as you have 10 knights, you need to move each of them every round or lose the ones you didn't move, assuming you don't push. Correct? – isaacg Jun 23 '17 at 21:30
• Does the same player go first in each round, or does that alternate? – Peter Taylor Jun 23 '17 at 21:31
• @isaacg correct. – Nathan Merrill Jun 23 '17 at 23:51
• @PeterTaylor I've debated about this, and I think the same player will go first in each round. The player that goes first will be randomized each game, but it will be consistent round to round. Otherwise, you end up with a player being able to move twice in a row. – Nathan Merrill Jun 23 '17 at 23:52

# Invisible Ink, Easy code-golf

In the physical world, invisible ink usually becomes invisible when it dries, and is then is readable if it is exposed to heat or chemicals of some kind. The invisible ink in this challenge will be readable when exposed to highlighting.

Create a full program or function that takes in text from the console (using a prompt) and outputs it the console so it cannot be seen unless highlighted.

## Notes:

• Assume that the console is a solid color (black, white, green, etc.).

# Swap the frogs!

Given 2 integers N >= 1, representing left-side frogs, and M >= 1, representing right-side frogs, return all the steps required so that the frogs change sides with the minimum number of steps. The frogs start with one empty spot between the two sides. A frog can jump to the empty space if there is at most 1 frog from either side between the frog and the empty space. A frog can jump either forwards or backwards.

An example, with N = 3 and M = 2:

LLL.RR
LL.LRR
LLRL.R
LLRLR.
LLR.RL
L.RLRL
.LRLRL
RL.LRL
RLRL.L
RLR.LL
R.RLLL
RR.LLL


The corresponding output would be (1-indexed):

[3, 5, 6, 4, 2, 1, 3, 5, 4, 2, 3]


Each one is the index of the column that the frog that must jump is before jumping.

# Rules

• You may perform I/O in any reasonable format.
• Maybe start with a small example, because now the main output specification is tucked under a huge block of text, which will be TL;DR for many people. – Sanchises Aug 8 '17 at 10:52
• 1. The questions in the section headed "Sandbox" make no sense because their context has been deleted. Are they still relevant? 2. "What you have to print" should presumably be "What you have to output". 3. "A frog can jump either forwards or backwards" so there should be at least one test case where all optimal paths only involve jumping forwards and at least one where all optimal paths involve jumping backwards. – Peter Taylor Aug 8 '17 at 14:55
• Maybe a testcase where no steps are necessary, too. – Sanchises Aug 8 '17 at 15:13
• @PeterTaylor Please, don't be too meta :-) :p – Erik the Outgolfer Aug 8 '17 at 16:46

# Learning your strengths and weaknesses king-of-the-hill

• Fighters have a unique, random Strength (between 1 and 1000)
• When two fighters fight, the stronger one wins.
• Your goal is to accurately guess your fighter's Strength.

## Gameplay:

1. We start by randomly ordering all 1000 fighters.

2. Each fighter fights his neighbor (The even fighters fight the fighter 1 above)

3. The fighter is given two pieces of information: His opponent's last guess, and who won the fight. The fighter then guesses his strength.

4. We perform a stable sort based on the guessed strength, and go back to step 2

5. After 10 guesses, the fighter's score is (RealStrength - GuessedStrength)^2. Lower is better.

# Other details:

• There will be duplicate bots in a single game.

• A stable sort is a sort that (effectively) uses the past ordering as a tiebreaker. In essence, if players [A,B,C,D] guessed [10,5,10,5] then the new order would be [B,D,A,C]

• Bots aren't allowed to share information between each other, but are allowed to persist information within a single game.

• I will run a large number of games. The exact number will be dependent on how much variation there is. Your final score will be all of your scores summed up.

• I like this a lot. Sounds like a very interesting challenge. A couple thoughts though. 1) What's the point of squaring your score? If there was some kind of polynomial scoring I could see that, but it doesn't really have any purpose at the moment. 2) personally, I think it should be more than 10 rounds. – DJMcMayhem Jan 29 '18 at 17:17
• @DJMcMayhem I think 10 rounds is enough for good bots to get a reasonable score without providing so much information that many will get a perfect score. I do think the process should be repeated though. Maybe a terminology change: 10 guesses per round, each round scored as indicated, average of X rounds is the final score. Also, the squaring is a way of getting absolute value (result is always positive even if guess > real) and if averaging multiple results it weights wildly incorrect guesses to increase the score by a lot. – Kamil Drakari Jan 29 '18 at 17:45
• @DJMcMayhem Squaring means that being 50 off is far worse than being 25 off. I picked 10 rounds because log2(1000) is 9.97. This requires bots to be efficient with their time. If I make it much higher, then its going to be hard for me to differentiate the top bots. – Nathan Merrill Jan 29 '18 at 18:24
• @KamilDrakari Updated, thanks. – Nathan Merrill Jan 29 '18 at 18:30
• In step 3, each fighter is provided "His opponent's last guess". What will be provided during the first round? – Kamil Drakari Jan 29 '18 at 19:21
• That'll be part of the API spec. Something like -1. – Nathan Merrill Jan 29 '18 at 19:31
• This will probably be my last suggestion (for now): a link and/or description for "stable sort" will probably be helpful; I certainly needed to look it up, and is quite useful for informing strategies, as well as answering a question I otherwise had about handling ties. – Kamil Drakari Jan 29 '18 at 22:00

# Efficient Tab Completion

Many tools that programmers use on a daily basis, like bash and Emacs, have tab completion.

• Pressing Tab in certain situations will attempt to complete the text at the cursor, from a set of possibilities. The term is "completed" by filling in the remaining text.
• For the aforementioned, if there are multiple candidates for completion, you will instead be shown a list of the candidates.
• If there are multiple possibilities but they all start with the same substring/prefix, the rest of that substring will be filled in.

For example, to reach pydoc3, you only have to type

pyd<TAB>3


where Tab is shown as <TAB>. The tab key will insert oc, since all options starting with pyd also start with pydoc (in the set below).

## The Challenge

Given a collection of strings called S and a target string called T, figure out the minimum number of keystrokes to reach T, assuming we're using tab completion and S is the set of possibilities.

• Tab completion here is modeled after bash and Emacs, so it is case-sensitive.
• The keystrokes/moves don't matter, only how many. A "keystroke" is:
• Some character in the string
• Tab
• If S is [abc, ab] and T is ab, then either a<TAB> or ab will get there. Tab counts as one keystroke, so the method doesn't matter.
• You may assume terms will only contain alphanumeric characters, underscore, and hyphen ([A-Za-z0-9]_-), for the purpose of this challenge.
• You may assume no strings are empty.
• You may assume S contains T (unsure about this one)
• The input can be taken in whatever format is appropriate for your platform or language (array of strings, string with separators etc.) S and T are considered separate inputs.
• I/O format is flexible and defaults apply (full program, function etc.)

This is , so shortest answer in bytes wins.

## Test Cases

Set                                                 Target         Output
--------------------------------------------------  -------------  ------
[ab, abc]                                           ab             2
[lisp-mode, list-abbrevs, list-packages]            list-packages  5
[heck, hell, help_me, hello, goodbye, hello_world]  hello          5


## Feedback

• Is anything vague or underspecified?
• Is something too specific or cumbersome?
• Is this too similar to an existing question?
• Should we assume S will always contain T, or require a special case?
• Should something be changed about case-sensitivity? Assume everything is lowercase?
• Any tags I should use?
• Hmm. wouldn't it be l<TAB>t-p<TAB> for #2? Also how to get hello in 4 keystrokes? – ASCII-only May 2 '18 at 0:48
• You're right about list-packages, I'll fix it. And it looks like hello should be 5 keystrokes at hello. Good eye. – snail_ May 2 '18 at 0:55
• You can get symbols for keys using <kbd> (<kbd>tab</kbd>) – 12Me21 May 2 '18 at 1:41
• I like this challenge! A couple of questions: is it illegal to start typing with a TAB (could be useful when all the strings in S start with the same prefix)? Why is . not in the allowed characters, since it is present in your first example of pydoc? – Leo May 3 '18 at 1:15
• You can use <TAB> wherever you want as long as it produces the minimum keystrokes. The image is supposed to be illustrative and not necessarily representative of the challenge itself; I worry that requiring too large or too specific a subset of characters will make the challenge more complicated than it needs to be (or maybe it won't affect much at all?) – snail_ May 3 '18 at 1:38
• Assume S is [abcde] and T is abcdf. What should be the output? – user202729 May 4 '18 at 14:02

# Existential Golf

• Proofs could be simple: it supports NAND, and NAND is functionally complete. – tsh Jul 5 '18 at 7:23
• @tsh Currently there is still no winning criteria. – user202729 Jul 5 '18 at 9:54
• This is quite interesting (not sarcasm!), but what's the actual challenge? – Nathaniel Jul 7 '18 at 7:02
• @Nathaniel When I actually finish it this will be the next installment of proof-golf. – Sriotchilism O'Zaic Jul 8 '18 at 3:19
• It's great to see an unfinished idea, ready for feedback until it's postable. I see this as an important purpose of the sandbox. – trichoplax Jul 10 '18 at 19:43
• @trichoplax Not everyone think so. – user202729 Jul 11 '18 at 3:46
• I definitely disagree with having to make sandbox posts "finished". I agree with not being lazy though. I see this post as a great example of unlazy and unfinished (when posted). There was clearly effort made, and it was made available for feedback early, which can avoid going too far down a path that others already know won't work. Posting early prunes impossible or impractical challenges so challenge authors have more time for writing the challenges that will make it to main. – trichoplax Jul 12 '18 at 19:05
• @user202729 For context, I said that in response to a 1-sentence sandbox post. I also said it bothers me when people "just post the bare minimum they can get by with and edit it later". The first revision of this challenge was clearly not the bare minimum to get by with. – DJMcMayhem Jul 12 '18 at 19:14
• @DJMcMayhem So you're measuring effort? That's usually not a good idea. – user202729 Jul 13 '18 at 2:48

# Split and recombine a number

This challenge has two related parts. Your task is to write two functions/programs as per the below specifications. You may share code across your submissions, the submissions may call one another, and you may even submit a single submission which handles both conversions. In the latter case, conversion direction may be determined by whether the input is a single number vs a list, or by an additional consistent second value (not a function) input.

## Part 1

Given a floating point number, return a list with one element per digit of its integer part, if any, and if the number is a non-integer, one additional part which is the fractional part. If the number is negative, negate all elements in the output. If the number is zero, return a 1-element list with a zero in it.

When the result list is recombined as per Part 2, it must be precise to within an absolute or relative error of 10⁻¹⁰, whichever is more permissive.

## Part 2

Given a list generated as per Part 1, return the number which would have generated that list in Part 1.

When the result number is split as per Part 1, each element must be precise to within an absolute or relative error of 10⁻¹⁰, whichever is more permissive.

## Examples

Part 1 <-> Part 2
-123       [-1,-2,-3]
2.71828    [2,0.71828]
-800.6     [-8,0,0,-0.6]
321.7001   [3,2,1,0.7001]
-0.01      [-0.01]
100        [1,0,0]
0          [0]

• (1) Technically infinities are floating point numbers (or, at least, they're not NaNs). What should the output be for an infinity? (2) How about for 1E45? (3) For numbers which are small enough to have a fractional part, what restrictions are there on the precision of the output? E.g. to take the fourth test case, 321.7001 - 321 in IEEE 754 double format gives 0.7001000000000204. – Peter Taylor Nov 18 '18 at 21:18
• Do we need the leading 0 in the list? Seems cleaner without it – Quintec Nov 18 '18 at 22:11
• @Quintec What leading zero? – Adám Nov 18 '18 at 22:28
• @PeterTaylor I'll exclude infinities. I'm not sure what do do about inexactness. I guess I could allow stopping at 16 digits of precision. Any ideas? – Adám Nov 18 '18 at 22:31
• Now that I think about it, string output for part one doesn’t make sense. But if it did, then I meant [2, .718] instead of [2, 0.718] – Quintec Nov 18 '18 at 22:43
• I don't see any reason to reject 0 <-> [], given that 0.01 <-> [0.01]. – Bubbler Nov 19 '18 at 1:21
• For the precision, how about something in the line of "correct up to absolute/relative precision of 1e-16"? Partly because big numbers stored in double are not accurate even in the integer parts. – Bubbler Nov 19 '18 at 1:29
• @user202729 Yes, I'll add that. Also, see tolerance text now. – Adám Nov 19 '18 at 12:36
• @Bubbler Tolerance specs added. – Adám Nov 19 '18 at 12:41
• Suggested test cases: 4.4 <-> [4,0.4] and 44.44 <-> [4,4,0.44]. Also, can we assume there will not be any unnecessary trailing zeros? I have a working solution, even with workaround for 0 <-> [0], but for 0.0 it outputs [0.0], but vice-versa for [0.0] it outputs 0 instead of 0.0. Hence the question that there won't be test cases like 0.0, 4.0 or 6.4000 with unnecessary trailing zeros. My programming language outputs 4.0 -> [4,0] -> 40 due to the implicit conversion of 0.0 to 0.. – Kevin Cruijssen Dec 4 '18 at 10:44
• @Adám FWIW Composed a solution using JavaScript for the specification at this question, and a solution for the specification at the original question (that currently has a bug for two test cases at "Part 2" portion, though is not incapable of being fixed). – guest271314 Dec 17 '18 at 23:47

Progress: Updated the rules again, and also add the timed function to the bots.

# Sylver Coinage KotH king-of-the-hillnumber-theorypython

Sylver Coinage is a 2-player mathematical game that has the following rules:

1. Two players take turns announcing a natural number each time.
2. Each number announced must be unrepresentable as the sum of non-negative multiples of the numbers announced before.

Eg. if the first three numbers announced are $$\\{6, 11, 15\}\$$, then you cannot announce any numbers representable as $$\6n_1+11n_2+15n_3\$$, where $$\n_1,n_2,n_3\ge0\$$. You can announce, for example, $$\16\$$, though.

3. The player who announced a number not complying with Rule 2, or the number 1, loses.

Here is a twist -- R. L. Hutchings proved that announcing a prime number as the first play provides a winning strategy for the first player, although the detail of the strategy is not yet known. So I put a restriction here: the first player cannot announce a prime number in the first step. Now the first two numbers will be generated randomly by the driver at the beginning. No more restriction on prime numbers now.

## Technical Information

A bot playing the game will have to implement a Python 3 class, extending TimedBot, with two methods: announce() and learn(). announce() should receive a list of numbers (possibly empty) and return a single integer, and learn() should receive two integers (id of the first move and second move) and the complete list of the numbers in the last game played.

Here is a sample implementation. Note: DO NOT use this as your submission -- this sample only serves as a demonstration, and it may announce numbers that violate Rule 2.

class SampleBot(TimedBot):     # must not be changed.
def __init__(self, id):
super().__init__()     # must not be changed.
self.id = id

def announce(self, list):
import random
return random.randint(1, 101)

def learn(self, first, second, list):
pass


### Test Drive

class TimedBot:
def __init__(self):
self.time = 20.0

def timed(func):
def f(self, *args):
import time
a = time.time()
b = func(self, *args)
self.time -= (time.time() - a)
print(self.time)
return b
return f

class SampleBot(TimedBot):
def __init__(self, id):
super().__init__()
self.id = id

@TimedBot.timed
def announce(self, list):
import random
return random.randint(1, 100001)

@TimedBot.timed
def learn(self, first, second, list):
pass

# very inefficient
def islinearcomb(n, l):
if len(l):
for i in range(0, n + 1, l[0]):
if i == n:
return [n // l[0]]
elif len(l) > 1:
isl = islinearcomb(n - i, l[1:])
if isl:
return [i // l[0]] + isl
return None

lose = -1
turn = 0
nums = []
bots = [SampleBot(0), SampleBot(1)] # replace with your bots here.

import random
while (len(nums) < 2):
a, b, c, d = random.randint(1, 10), random.randint(1, 10), random.randint(1, 10), random.randint(1, 10)
if 2**a * 3**b != 2**c * 3**d and 2**a * 3**b > 100000 and 2**c * 3**d > 100000 and 2**min(a,c) * 3**min(b,d) > 12:
nums = [2**a * 3**b, 2**c * 3**d]
while lose < 0:
v = bots[turn].announce(nums)
print("{0}({1}) announced {2}".format(type(bots[turn]).__name__, bots[turn].id, v))
w = islinearcomb(v, nums)
if w:
str = ""
for i in range(0, len(nums)):
if i:
str += "+"
str += "{0}*{1}".format(nums[i], w[i] if i < len(w) else 0)
print("{0}({1}) announced {2} that is equal to {3}".format(type(bots[turn]).__name__, bots[turn].id, v, str))
lose = turn
elif v == 1:
print("{0}({1}) announced 1".format(type(bots[turn]).__name__, bots[turn].id))
lose = turn
nums += [v]
turn = 1 - turn
print("{0}({1}) wins".format(type(bots[1 - lose]).__name__, bots[1 - lose].id))


## Restrictions

Each bot will have 20 seconds of time for deciding a move todo: adjustments. Running out time during the move results in a lose, and failing to finish a method within 20 seconds will lead to disqualification and rerun of all 100 rounds with the remaining bots.

## Schedule

Submissions will be open until todo: date here. After that 100 complete round-robin rounds will be done. Each pair of bots will compete twice in each round, one with the first bot announcing first, and one with the second bot announcing first. Each win brings 3 points, each draw brings 1 point, and each lose brings no points. The bot with the highest points after 100 rounds wins. The tiebreaker will be as follows:

1. Points got
2. Wins achieved
3. Drawing lots
• Probably needs some time limit for responses to prevent solutions which attempt to generate a full game tree. – Peter Taylor Dec 17 '18 at 9:26
• @PeterTaylor Oh yes I thought about the time limit but I turned out forgetting to put that ;p – Shieru Asakoto Dec 17 '18 at 9:31
• "The player who announced a number not complying with Rule 2 ... loses." I've been thinking about this. I presume that your intention is that the controller will validate the responses. An alternative would be to say that you don't automatically lose, but to add a type of response where the bot can return a proof that the opponent broke rule 2. Then bot programmers have to make a decision as to how much time to spend trying to show that their opponent lost vs computing a valid response. – Peter Taylor Dec 17 '18 at 20:48
• What if a game goes on for a billion turns? – isaacg Dec 18 '18 at 1:13
• @PeterTaylor I'd say my intention is that the controller will validate the responses. (in the test drive there is the code doing exactly that) – Shieru Asakoto Dec 18 '18 at 9:29
• @isaacg If the number does not start out too large a game should end quite quickly. It is because two coprime numbers already make the number of possible moves finite. But If I pose a criteria on how large a number can at most go, then I'm feared that there may be a problem that the game tree is restricted. – Shieru Asakoto Dec 18 '18 at 9:30
• I'd say: don't restrict the highest move, but give each bot a 'chess clock': they start with (say) 10s, and gain 1 second per move (and pass their clock's time as a parameter). Running over time is an automatic loss, and some percentage of time losses is a disqualification. Playing high moves will quickly exhaust their stock of time if they attempt to calculate extensive game trees, which will force the bots to either play quickly or lower their numbers. Adding a decay function to the time per move will encourage smart bots to play smaller numbers to not run out of time to think. – Spitemaster Dec 24 '18 at 16:47
• @Spitemaster That's a good idea, but what I concerned about on large numbers is that the validation may take too long (because we are solving Diophantine equations in many unknowns) – Shieru Asakoto Dec 25 '18 at 5:48
• Do you realise that guaranteeing that the first two numbers are coprime guarantees that the first player will win with correct play? If you want an interesting game then you should generate the first two numbers randomly as 3-smooth numbers with a GCD which is a multiple of 6 and greater than 12. – Peter Taylor Jan 9 at 11:16
• @PeterTaylor Great catch! During discussion only the suggestion of giving two initial numbers was achieved, so I didn't realize that. – Shieru Asakoto Jan 10 at 0:39
• I would remove the submission deadline, why not keep it open and update once a new entry comes? Also you might be interested in this (I adapted the code originally written for another KoTH), the easiest thing will be to enforce a certain formatting on the first line and adapt code_matcher to that formatting, st. that it won't break because everyone is using different formatting. – ბიმო Jan 10 at 13:48
• @BMO Wow that's a good one! And I saw my code in the source lol BTW for the certain formatting part you mean the lines around class FooBar(TimedBot):? – Shieru Asakoto Jan 10 at 15:19
• @ShieruAsakoto: Yeah, I added the header to bots.py which will be used, all the users' code will be appended to that and written to auto_bots.py.. Basically you'll only need to checkout the few variables (lines 12-20) and the main (from line 117) to see how it works. About the formatting, yes, that's probably the most sane: Make sure every code starts with class NameOfBot(TimedBot):, all definitions are in that class and it's valid Python 3 code (I updated the code_matcher like this it should work fine). – ბიმო Jan 10 at 15:33
• If they/you use that bots.py you'll need to manually update the imports or do it inside the bot itself, atm. bots could use random and time, maybe add math too. – ბიმო Jan 10 at 15:34

# Interleave Invariance

There is an infinite sequence that does not change when interleaved with the natural numbers. Consider these few terms:

1 1 2 1 3 2 4 1


Interleave them with the naturals:

1   2   3   4   5   6   7   8
1   1   2   1   3   2   4   1
-------------------------------
1 1 2 1 3 2 4 1 5 3 6 2 7 4 8 1


As you can see, there is no change in the initial eight. Now, this sequence can be extended indefinitely rather easily by repeating this interleave operation. Your task is to choose and implement one of three output formats:

1. Take as input a nonnegative integer n and output the nth term of this sequence, zero- or one-indexed (your choice).

2. Take as input a nonnegative integer n and output the first n terms of this sequence.

3. Output terms in order forever, starting from the beginning.

For options 2 and 3, there must be no numeric characters and at least one non-numeric character between terms; this separator need not be consistent. 1+1=2 would be fine for input 3. Leading and trailing non-numeric characters are allowed.

Here are the first 64 terms. This is OEIS sequence A003602.

1 1 2 1 3 2 4 1 5 3 6 2 7 4 8 1 9 5 10 3 11 6 12 2 13 7 14 4 15 8 16 1 17 9 18 5 19 10 20 3 21 11 22 6 23 12 24 2 25 13 26 7 27 14 28 4 29 15 30 8 31 16 32 1


Your submission can be a program or a function; "input" and "output" are as defined by the community. Standard loopholes are forbidden.

As this is , the shortest solution (in bytes) wins! Good luck, and happy golfing!

# Sandboxy Stuff

Am I clear enough on what the sequence is? Any suggestions for rewording?

Is this a duplicate? I've searched for "interleave" and "3602" and found nothing.

Anything else worth mentioning? What thoughts ya gots?

Thanks to Martin Ender for the output formats, taken almost straight from the Kolakoski challenge.

• related (not a dupe though) – dzaima Feb 13 at 19:35
• You could consider removing the option to output just the n'th term, making answers output a sequence. Otherwise I think it will be shortest in most languages to take n, halve until non-whole, then add 1/2 (ceiling), rather than use the interleaving property which I think is cooler. – xnor Feb 15 at 0:46
• It looks like n/(n&-n)/2+1 would work for a lot of languages such as Python. – xnor Feb 15 at 1:09
• @xnor Do you think removing that option will help much? I can't really think of a case where the solution won't be to wrap your expression in a looping construct if the expression was the shortest. I don't think knowing the history of this function is that helpful to finding the future value. – FryAmTheEggman Feb 25 at 22:09
• @FryAmTheEggman You're probably right, answers would mostly just do the expression in some loop. In Haskell I think the interleaving definition wins out (even with option 1 allowed), but maybe that's just Haskell. – xnor Feb 26 at 6:22

## Evaluate C−− expression parsing

Your goal is to a evaluate an expression in "C−−" (not this one) which uses only the characters are C and -. C is an variable holding an integer whose initial value you're given, and the - symbol is used in many ways including as a decrement operator:

• C-- decrements the value stored in C, then evaluates to that value.
• --C evaluates to C, then decrements the value stored in C.
• -expr negates the value of the expression expr.
• expr1-expr2 takes the difference of the two expressions.

Unfortunately, the C−− specification doesn't state how expressions are parsed or in what order parts are evaluated, saying these are "implementation dependent". So, it's up to you. For example, --C---C could be interpreted as -(-(C--)-C) or (--C)-(--C) or others, and each --C might be evaluated before or after other parts of the expression.

Input: A string consisting of C and -, and an integer initial value for C.

The string will be parseable in at least one way. You can take the string as a list of characters, but they must be exactly the characters C and -.

Output: A value this expression could evaluate to.

You don't need to worry about issues with overly large values like overflows or loss of precision.

TODO: test cases

• Can --C---C  be parsed as -(-(C-(-(-C))))? – H.PWiz Apr 13 at 17:44
• @H.PWiz Yes. Unfortunately, it looks like as is --C, can always be interpreted as -(-C), which is golfier but more boring, so I'll probably restrict the parsing or removing the unary negation option. – xnor Apr 13 at 17:50
• @xnor Note: -C is the same as (C-C)-C, but there are no parentheses here so nobody can say it can't also be parsed as C-(C-C). An added rule can be "You can't parse --C as -(-C), as a double negation would be meaningless." – Erik the Outgolfer Apr 13 at 17:55
• Do you want to include or exclude simple eval implementations? – Phil H Apr 29 at 15:22
• @PhilH That's a good question. Eval-style solutions seems pretty boring for C-style languages, but I don't know if there's a clean way to even specify what would be disallowed. I don't have time to work on this challenge, so you're welcome to spruce it up and post it if you want. – xnor Apr 30 at 1:05
• if the C-- in question is not the one linked, could you link the one you're referring to? You mentioned a C-- specification, so I assume there is one – Skidsdev May 3 at 17:29
• @Skidsdev I meant it as a thing I'm making up for the challenge. – xnor May 3 at 22:02

# An Auction in St. Petersburg

## Setup

Mysterious packages are up for auction today. These boxes are unique in that their values are not known until they are opened, and when they are opened, their values follow a unique distribution:

probability    value
0.5               $2 0.25$4
0.125             $8 0.0625$16
1/(2^n)       $(2^n)  In total, there are 100 such packages up for auction, to be sold sequentially. At the start, each bot arrives with$20 in their wallet, and the goal is to walk away with more money than anyone else.

During each round in the auction, each bot simultaneously submits a bid. The bot with the highest bid (ties broken randomly) must pay the value of the second-highest bid, after which that winning bot receives an amount of money corresponding to the value of the opened package. This money can then be "reinvested" in future rounds of the auction.

The auction day ends once all 100 packages have been sold, or when any bot's wallet value exceeds 2^31.

## I/O format

As input, your bot receives the following info:

• an array of everyone's current wallet amounts
• the history of past sale prices (the amount paid, not highest amount bid) and winners

As output, your bot returns an integer between 0 and your current wallet amount.

## Tournament format

There will be N=large number of game run according to the above format (100 auction rounds each), and the finishing position of the bots will be averaged across games.

• Could you explain why it ends when someone reaches 2^31? – Artemis Fowl Apr 16 at 3:17
• @ArtemisFowl It's mostly to prevent players from having to deal with numbers that don't fit into a 32-bit integer. There's only a 1 in 1 billion chance that a particular package will contain enough money to trigger this condition, I just wanted to clarify how I would handle the "infinite expected value" in practice. – PhiNotPi Apr 16 at 14:45
• This seems rather win-more. It just takes one big win to be able to guarantee that you can outbid everyone else for the rest of the game. – Peter Taylor Apr 20 at 21:40

# Implement Brainfuck Algorithms

In order to make algorithms written in brainfuck more understandable, you can write them in a more abstract notation, where you give a given cell a name, and instead of lots of unreadable < and > instructions to move the pointer to a specific, you just write down the name of the cell. Let us see an example:

This algorithm doubles the value in cell x, and saves the result again in x. It needs an additional temporary cells t

t[-]          clear temporary variable
x[t+x-]       move the value from x to t
t[x++t-]      move twice as many units from t back to x


Now lets see what this would look like, if x was the cell with index 0, and t was the cell with index 2, assuming the poninter is in position 0 when the algorithm starts:

>>[-]
<<[>>+<<-]
>>[<<++>>-]


### Challenge

Given a string with a valid (see below) brainfuck algorithm, a list of strings containing the cell names and a list of integers containing the indices of each of the cell of the previous list, your program/function has to return an implementation of this algorithm in brainfuck.

### Details

• The pointer is assumed to be on a cell with index 0 when the implementation is executed.
• The two given lists can also be in a different reasonable format e.g. [cell1,index1,cell2,index2,...] or [[cell1,index1],[cell2,index2],... or as arguments of a function with a variable number of arguments etc.
• You can assume that in the given string representing the algorithm, there are only brainfuck instructions as well as cell names, but no other symbols (no line breaks, no spaces)
• The cell names consist of lower- and uppercase characters A-Z and a-z as well as digits 0-9
• The cell names in the string are always separated by at least one BF instruction symbol.
• You can assume that the pointer is the same index whenever it enters a loop as it exits the same loop.

### x=y:

String (remove line breaks):
temp0[-]
x[-]
y[x+temp0+y-]
temp0[y+temp0-]
List of variable names: [temp0,x,y]
List of indices:        [    2,0,1]
Output (remove line breaks):
>>[-]
<<[-]
>[<+>>+<-]
>>[<+>-]


### x=x*x

String (
temp0[-]
temp1[-]
temp2[-]
x[temp2+temp1+x-]
temp1[
temp2[x+temp0+temp2-]
temp0[temp2+temp0-]
temp1-
]
List of variable names: [x,temp0,temp1,temp2]
List of indices:        [0,    1,    2,    3]
Output (remove line breaks):
>[-]
>[-]
>[-]
<<<[>>>+<+<<-]
>>[
>[<<+>+>>-]
<<[>>+<<-]
>-
]


(More to be added)

• Aah, I just noticed something when writeing that line (see meta section) but I do not have time right now to think through that. That's why this part was unfinished. – flawr Jun 20 '16 at 15:14
• I think that this is undecidable. Consider a line of the form x[algorithm] where algorithm doesn't guarantee to leave the pointer where it started. For the subsequent line to move the pointer to the desired cell it needs to know whether x was zero going into that line or not. – Peter Taylor Jun 20 '16 at 16:03
• I think the problem can be solved by requiring that there are no <> in the input. Although that would make the resulting language not Turing-complete (can only access finite amount of memory) – user202729 May 2 '18 at 9:51

# Fix my stuttered words

Stuttering is a problem which many of us might have experienced or at least seen it. Although most of famous speech recognition softwares have serious issues with stuttered speaking, let's imagine a software which understands stuttering, but cannot fix them and only writes them as is.

An example written text by a such software can be like this: "please be ca ca careful". In this example "careful" is the original word and "ca ca" are the stuttered words.

## Challenge

Write a program or function that fixes stuttered words by removing them from the input while keeping the original words. For example fixed version of "please be ca ca careful" would be "please be careful".

This is , shortest answer in every language wins!

## What are stuttered words?

Stuttering has many different variations. But for simplicity of this challenge, we are going to limit it to the following rules:

• Stuttered words can be an uncompleted part or whole of the original word. By "uncompleted part" I mean that the original word should start exactly with the stuttered word. For example "ope" and "open" both can be a stuttered word for "open", but "pen" cannot be one since "open" doesn't start with "pen".
• Stuttered words must contain at least one of the "aeiou" vowels. For example "star" can be a stuttered word for "start" as it contains "a", but "st" cannot be a stuttered word as it doesn't contain any of the mentioned vowels.
• Stuttered words can only appear before the original word and should be repeated at least two times to be valid (the original word doesn't count in the repeats). For example "o o open" has stuttered words but "o open o" doesn't, because the "o" after the original word doesn't count and "o" before the original word is not repeated at least two times. "go go go go go go" has five repeats of stuttered words before the original word and is valid.
• A single set of repeated stuttered words cannot contain mixed forms and the words should be exactly like each other. For example "op o op open" doesn't count as stuttered words. On the other hand "o op op open" has stuttered words because the first "o" is seen as a whole different word here and the two "op"s are counted as stuttered words of "open".
• In case of multiple valid sets of repeated stuttered words right after each other, only the last original word stays. For example, in "o o o op op op open", the "o o o" part is seen as stuttered words of the first "op", so they should be removed and then "op op op" is seen as stuttered words of "open" and they should be removed too, so only the "open" will be left after removal of stuttered words. You can assume that multiple valid sets of repeated stuttered words only happen from left to right, so fixing "op op o o o open" would result in "op op open" (a.k.a. we do not fix again after fixing once).

## Input

• Input is a single line string containing only ASCII English letters (a-z), digits (0-9) and space characters. Letter casing is not important and you can decide to accept lowercase or uppercase or both of them, but the casing should stay the same and you cannot change it in the output.
• You can use a list of letters (like ["l","i","s","t"," ","o","f"," ","l","e","t","t","e","r","s"]) instead of the string, but you cannot use a list of words.
• The input might contain none, one or multiple stuttered words in it.
• Words and or numbers are separated by a single space and input will not contain double spaces right next to each other.

## Output

• A string or a list of letters with all stuttered words removed from the input.
• Output words should be separated by exactly one space (same as input).
• Single leading and trailing newline or space are allowed.

Standard loopholes are forbidden.

## Test cases

No stuttered words:

"hello world" => "hello world"


A single instance of repeated stuttered words:

"ope ope ope ope open the window" => "open the window"


Multiple instances of repeated stuttered words:

"there is is is is something un un under the the the table" => "there is something under the table"


No stuttered words, not repeated enough:

"give me the the book" => "give me the the book"


No stuttered words, don't have any of the mentioned vowels:

"h h help m m m me" => "h h help m m m me"


Numbers aren't stuttered words, they don't have any of the mentioned vowels:

"my nu nu number is 9 9 9 9876" => "my number is 9 9 9 9876"


But a word with both vowels and numbers can have stuttered words:

"my wi wi windows10 is slow" => "my windows10 is slow"


Different forms of stuttered words in same repeat group aren't counted:

"this is an ant antarctica does not have" => "this is an ant antarctica does not have"


For multiple continuous sets of stuttered words right after each other, only keep the last original word:

"what a be be be beauti beauti beautiful flower" => "what a beautiful flower"


This isn't a case of multiple continuous sets of stuttered words right after each other:

"drink wat wat wa wa water" => "drink wat wat water"


Empty input:

"" => ""


## Sandbox Questions

• Is the challenge clear?
• My English sucks, so apart from the technical stuff, can I make my sentences better?
• Anything else?
New contributor
Night2 is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
• "You can assume that multiple valid sets of repeated stuttered words only happen from left to right, so fixing "op op op o o o open" would result in "op op op open"." Shouldn't this result in "op open" instead? In the first rule you mention "For example "ope" and "open" both can be a stuttered word for "open"." So since the entire word is valid as stutter, I would think "op op op o o o open" becomes "([op op] op) ([o o o] open)" (([this] ... ) being the stutter, and ([...] this) being the word), thus "op open". – Kevin Cruijssen Sep 13 at 9:45
• I think you meant to give the example "... so fixing "op op o o o open" would result in "op op open"." (so one less op) instead? – Kevin Cruijssen Sep 13 at 9:46
• @KevinCruijssen: You are absolutely correct, I have updated the question. Thank you for reading with such a high precision. – Night2 Sep 13 at 12:26

# BlackJack Part II

Repost from the original sandbox

As I had a blast working on the original KOTH challenge, I wanted to come up with another. For me, the fun of these AI challenges is in refining a comparatively simple bot which plays a very simple game subtly. Due to the probabilistic nature of card games, I think that blackjack could be an interesting KOTH game just like TPD.

# Rules

• Bots play at tables of four (4) competitors and one (1) dealer
• One (1) shoe is shared by all players and the dealer until it is exhausted, at which point a new randomly shuffled deck will be added and play will continue. The bots ARE NOT (at present) NOTIFIED of the addition of this new deck. [TODO? would make card-counting a LOT harder...]
• There is a buy-in of 10 per round, and cards are free
• There is no bet maximum as bets are between the player and the house, yet the bot must have sufficient chips to immediately finance the bet.
• Perfect/ideal hand has a score of 21
• All face cards have a value of 10
• All numeric cards are worth their number
• Aces are worth 11 or 1. this will be dealt with automatically by the framework, not the bots.
• Scores in excess of 21 which use an ace as 11 force the ace to reduce in value to 1 scores in excess of 21 which cannot be coerced below the threshold of 21 "bust" the bot
• The dealer draws until he busts, or excedes a score of 17.
• The stake is subtracted from chips, so the chips value is the number of credits which are available to the bot for betting.

1. When the game starts, each player is iteratively dealt one card, and has the $10 buy-in fee/minimum bet subtracted from their chips. 2. Then (in the same order as they were dealt to) each bot is executed as described in the "Programmer's Interface" section and must make a move or stand. Betting is considered a move. NOTE THAT BETTING DOES NOT AFFECT BOTS' ABILITY TO MAKE FURTHER MOVES. It is very possible to bet and then draw a card, and it is possible to draw multiple cards and them bet before standing. # Programmer's Interface and Legal Moves As documented in the CardShark class: # DOCUMENTATION # INPUT SPECIFICATION #$ ./foo.bar <hand-score> <hand> <visible cards> <stake> <chips>
#          <hand-score>     is the present integer value of the player's hand.
#          <hand>           is a space-free string of the characters [1-9],A,J,Q,K
#          <visible cards>  every dealt card on the table. when new shoes are brought
#                           into play, cards drawn therefrom are simply added to this list
#                           !!! THE LIST IS CLEARED AT THE END OF HANDS, NOT SHOES !!!
#          <stake>          the  number of chips which the bot has bet this hand
#          <chips>          the number of chips which the bot has
#       SAMPLE INPUT
#          $./foo.bar 21 KJA KQKJA3592A 25 145 # # OUTPUT SPECIFICATION # "H"|"S"|"D"|"B" (no quotes in output) # "H" HIT - deal a card # "S" STAND - the dealer's turn # "D" DOUBLEDOWN - double the bet, take one card. FIRST MOVE ONLY # "B 15" BET - raises the bot's stakes by$15.


# Winner Selection

The winner would be the author of the bot which consistently accrued the most chips over a yet-to-be determined number of tables and rounds.

# Issues & ToDo

None! (no known problems at least)

PS. How do I tag questions/answers? thanks @dmckee [ai-player] [card-game] [koth]

# Version History

5/25 - 0020 - v1 - updated code on GitHub which fixes a bug with the dealer. DD still scores monstrously for unknown reasons. tagged this post (with any luck).

5/25 - 0800 - v2 - bugfix on github which correctly implements DoubleDown, resulting in drastically reduced scores from the double-nut bot.

5/25 - 0920 - v3 - updated the test case to match the input specification. Added the rules for the dealer.

5/25 - 1100 - v4 - added a description of the table and shoe system.

5/25 - 1620 - v5 - added an explanation of the betting and card-dealing system, major status update.

5/27 - 1700 - v6 - ready to roll the contest...

• Tags: [ai-player] and [card-game] seem naturals, though neither exists on the site as yet. What else? – dmckee May 25 '11 at 4:00
• The SAMPLE INPUT isn't consistent with the INPUT SPECIFICATION - do the args include the current score or not? How many decks of cards should we assume to be used? Does <chips> include <stake>? How does the AI dealer play? Is each bot-dealer pair using a separate shoe (so that when I stand the dealers cards are drawn fairly from all those not included in <hand> and <visible-cards>)? When does betting occur? – Peter Taylor May 25 '11 at 12:17
• should players be notified of the number of decks in play, or not? The issue is that decks are dealt from until the deck is exhausted, then the "cannot pop from empty list" error signals the creation of a new shuffled deck then continues drawing as if nothing had happened. This means that multiple decks can be in play at once, but the statistical worst-case is that each player has three or four cards, which makes between fifteen and twenty samples split between two decks of 52. It shouldn't make a difference to score-based bots, but card-counters will need to detect or be notified of the chage – arrdem May 25 '11 at 15:16
• Can we delete this because the sandbox lags so much and this hasn't been touched in 6 years? – programmer5000 Apr 13 '17 at 17:29

Given a text, determine the language it is written in. The possible languages are: English, Danish, Romanian and Hungarian. The shortest program wins.

Some examples of text in each language can be found at Project Gutenberg

You are required to include examples of runs on text files other than the ones provided here.

The input file name is given as a command line argument. Except the input text, you are not allowed read additional files (e.g. to train your program) so please encode any data in your program.

Your program must output on of the following words English, Danish, Romanian, Hungarian.

Examples

$./language pg2600.txt English$ ./langauge pg12167.txt
Danish
$./language 11756-0.txt Romanian$ ./language 30163-0.txt
Hungarian

• Another source of plain text passages might be the Gutenburg project. They do have books in languages other than English. – dmckee Jun 22 '11 at 14:53
• Thanks. I updated the text problem to include some books from Gutenberg. – Alexandru Jun 22 '11 at 15:04
• Related – Beta Decay Sep 7 '16 at 10:32
• Looks pretty trivial to me. Any sufficiently long text will have ă if Romanian, ő if Hungarian, å if Danish, and neither if English. None of the special characters occur in any other of the four languages. – Adám Jun 5 '17 at 10:45
• Hello! This looks like a good but abandoned meta post, would you be willing to offer it for adoption? (If you want to, you can still post to main.) – programmer5000 Jun 9 '17 at 15:20
• @programmer5000 The OP hasn't been seen since 2011, I think you're fine. – TheLethalCoder Jul 21 '17 at 13:21

## How long until my next birthday is on a weekend

I would like to know how much time (in days) I have to wait (from now) until my birthday occurs on a weekend...

• The required tool could accept arguments or standard input.
• The only variable passed as input (as argument or stdin) is my birth day in the strict form YYYY/MM/DD with only digits, separated by / (of course: YYYY for birth year, MM for the month and DD for the day of month.
• The output must present the number of days to wait, from now, and the target date with the day of week, in the form Wait DTW days to WWW, YYYY/MM/DD where DTW in integer is the number of days to wait, WWW as day of week abbreviation could be Sat or Sun and the target date in same form as input.
• Once done, there is no more request (tool could finish quietly, loop, bug or crash)
• About February 29th, there are 3 ways you can handle it:

• strict: Where birthday may occur once every 4 years
• right: Where birthday is March 1st while Feb 29th doesn't exist.
• relax: Where birthday could be Feb 28th or March 1st, but only while Feb 29th doesn't exist.

The tool must match in the right manner, but could accept an option as choice between one of the three ways.

• Shortest golfed code wins
• -3 explanation (while golfed version must use one letter variable, ungolfed version is welcome with useful variable names)
• -3 if properly loop on STDIN
• -5 if no requirement of external library
• -10 if an option to choose the way of considering February 29th.
• 0 for shebang (unless they contain more than runtime options: switch r in sed or p in perl are runtime options, they count for null)
• N embed code on shebang line in counted normally.
• How would you handle birthdays on February 29th? It would be an interesting special case, and it will increase the complexity of the problem. – PhiNotPi Dec 13 '13 at 23:15
• Is this going to get answers which are much different to the currently active calendar-related questions? IMO it would be best left for a couple of months. Variety is a good thing. – Peter Taylor Dec 13 '13 at 23:41
• @PeterTaylor I'm not sure about what to answer to this. I think: yes in that: there is two input: current day and birthday, a range in week, not only one day and may different thinking may build different solution... – F. Hauri Dec 14 '13 at 9:34
• @PhiNotPi Thanks, question edited! – F. Hauri Dec 14 '13 at 9:42
• @PeterTaylor I've already browsed calendar questions ;-) – F. Hauri Dec 14 '13 at 9:46
• Instead of listing this as code-golf, I recommend that you list it as code-challenge and change "Shortest golfed code" to "Lowest score" and add: 1 for each char – Justin Dec 21 '13 at 7:35
• This sandbox post has had little activity in a while. Please improve / edit it or delete it to help us clean up the sandbox. Due to community guidelines, if you don't respond to this comment in 7 days I have permission to vote to delete this. – programmer5000 Jun 9 '17 at 15:39