# Sandbox for Proposed Challenges

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

Sandbox FAQ

## Posting

Write your challenge just as you would when actually posting it, though you can optionally add a title at the top. You may also add some notes about specific things you would like to clarify before posting it. Other users will help you improve your challenge by rating and discussing it.

When you think your challenge is ready for the public, go ahead and post it, and replace the post here with a link to the challenge and delete the sandbox post.

## Discussion

The purpose of the sandbox is to give and receive feedback on posts. If you want to, feel free to give feedback to any posts you see here. Important things to comment about can include:

• Parts of the challenge you found unclear
• Problems that could make the challenge uninteresting or unfit for the site

You don't need any qualifications to review sandbox posts. The target audience of most of these challenges is code golfers like you, so anything you find unclear will probably be unclear to others.

If you think one of your posts requires more feedback, but it's been ignored, you can ask for feedback in The Nineteenth Byte. It's not only allowed, but highly recommended! Be patient and try not to nag people though, you might have to ask multiple times.

It is recommended to leave your posts in the sandbox for at least several days, and until it receives upvotes and any feedback has been addressed.

## Other

Search the sandbox / Browse your pending proposals

The sandbox works best if you sort posts by active.

To add an inline tag to a proposal, use shortcut link syntax with a prefix: [tag:king-of-the-hill]. To search for posts with a certain tag, include the name in quotes: "king-of-the-hill".

Get the Sandbox Viewer to view the sandbox more easily!

# Traffic Light Simulator 2016

In this challenge, you are in charge of all of the traffic lights in a busy city. It is your goal to move the traffic as efficiently as possible.

## Definitions:

City: Everything you control. Contains a 10x10 square grid of intersections. All adjacent intersections are connected via roads, and intersections on an edge have 1 outside connection (2 on corners)

Tick: Measures time. For the first 10,000 ticks, 10 cars will span. The simulation ends after all cars have left the city.

Road: Moves cars from one intersection to another (or an outside connection). Roads have a length (in ticks).

Intersection: 12-way intersection. Connects 4 roads together, and allows cars to move from one road to one of the other 3. Only 1 car per direction can travel through at a time.

Traffic Light: Allows/Prevents cars from crossing an intersection. There are 12 lights (one for each direction) at each intersection. Lights can only be green (allows traffic) or red (prevents traffic). If a light is green, then any intersecting paths must have been red for at least 3 ticks.

Intersecting paths: Paths that cross or meet assuming right-side traffic. The following graph indicates when two paths intersect given your direction and the other lanes' directions.

Your        Left  Right Across
Direction  |L|R|A|L|R|A|L|R|A
------------------------------
Left       |X   X|X   X|  X X
Straight   |X   X|X X X|X
Right      |    X|     |X


Car: Starts at a random outside connection, and travels the shortest path to another random outside connection. After reaching its destination, adds 1.05^(TravelDuration) to your score.

Outside connection: Has a Busyness, and spawns cars. The chance of an outside connection being randomly chosen is Busyness/Sum(Busyness of every connection)

I have provided a controller that will simulate the cars and the cities. You need to provide a function that returns a list of [x,y,Direction] tuples that indicates which lights you would like to toggle. Attempting to turn a green light with intersecting green lights will turn the intersecting lights red, and turn the light green after 3 turns.

After the simulation has run, your score is the sum of all cars' scores, lowest score wins.

• Did anything ever come from this? This seems like it could be a fun challenge. Feb 25, 2018 at 17:18
• No. I'm not convinced that there are actually interesting solutions to be had, and the controller isn't trivial to write. If you want to take this challenge, feel free :) Feb 26, 2018 at 2:16

# How Many Laps?

I was at my taekwondo training last night and the first thing we do when we start is a ~5 min jog around the gym to get warmed up. The problem is as follows. We run around the edge of the gym, everyone starting from wherever they like, and everyone jogs at a slightly different speed, so there is a lot of awkward passing as no one wants to have to ruin their flow by changing speed. So i started wondering, how many times will each person be overtaken?

### The Question

Given a square of side lengths 15m, and a person starting at each corner of the square, running at speed n (m/s) how many times will each person be passed by someone else during a 5 min jog?

### Input/Output

• Input should take the form of 4 values that represent each persons average running speed( Assume their speed remains constant) accurate to 3 decimal places. The range of the input may be (0,5]. Input may be seperated by commas or spaces i.e 4.123,2.122,3.145,1.445
• Output should be printed as 4 integers representing the number of times each person was overtaken by someone else, given in the same order as the input was supplied.

### Test Cases

The input 1.3334 2.5334 1.1344 2.8531 can be visually represented as follows

1.3334 ------------ 2.5334
|                   |
|                   |
|                   |
|                   |
|                   |
2.8531 ------------ 1.1344


Each of the numbers in the corner of the square represents a jogger and their speed running in a clockwise direction(Clockwise because of the order of the input). After 5 mins of jogging, how many times will each jogger have been overtaken by everyone else?

The output for this case would be 13 1 14 0  This basically means the first person( top left corner) will be overtaken 13 times. The second person(top right) will be overtaken once. third person(bottom right, and the slowest jogger) will be overtaken 14 times. The fourth person( bottom left, and the fastest) will not be overtaken by anyone, as they are the fastest. Here are some more test cases

• Input: 5.3334 1.5334 1.5334 0.8531 Output: 0 19 19 28
• Input: 0.1334 1.5334 2.5334 3.8531 Output: 37 16 6 0

### Rules

• This is code golf, shortest working program in bytes wins
• Must be a fully working program
• You should really add an example, since this is very hard to imagine in your mind. Also don't forget testcases! Feb 25, 2016 at 7:48
• Haha yeah i thought someone would say that! I'm currently trying a few ideas as im not sure how to solve this myself yet! Once i have a way, ill ad some test cases Feb 25, 2016 at 8:16

## The broken minus parser code-golfparsing

Sam is trying to create a new programming language, but is having a lot of trouble getting the parser right. For example,

4--5


evaluates correctly to 4 - (-5) = 9, but

4-5


is giving a result of -20!

After doing some digging around, Sam realises that their parser's grammar is ambiguous. In fact, it's actually interpreting 4-5 as 4 (-5), multiplication (by juxtaposition) between two numbers!

Here's some example inputs and outputs, to get a feel for what the parser's doing woeful wrong:

Input             Calculation                 Output
7                 7                           7
-7                (-7)                        -7
8-3               8 (-3)                      -24
8--3              8 - (-3)                    11
-8-3              (-8) (-3)                   24
-8--3             (-8) - (-3)                 -5
-4-5-2            (-4) (-5) (-2)              -40
-4--5-2           ((-4) - (-5)) (-2)          -2
-4-5--2           (-4) ((-5) - (-2))          12
-4--5--2          (-4) - (-5) - (-2)          3
1-4-5-9           1 (-4) (-5) (-9)            -180
1-4--5-9          1 ((-4) - (-5)) (-9)        -9
1--4-5--9         (1 - (-4)) ((-5) - (-9))    20
1--4--5--9        1 - (-4) - (-5) - (-9)      19


To be a bit more explicit, here's the rules followed by the parser, in order:

1. Multiplication by juxtaposition: If possible, split the input into two valid parts a, b such that a is as short as possible. Return evaluate(a) * evaluate(b).

2. Subtraction: If the input is of the form a-b where a, b are two valid parts, return evaluate(a) - evaluate(b), taking the - such that b is as short as possible.

3. Unary negation: If the input is of the form -a where a is valid and does not start with a -, return -evaluate(a). In other words, unary negation can only be applied once.

4. Digit: If the input consists of a single digit, return the corresponding integer.

If an input string fails to satisfy any of the above conditions, it is invalid. For example, the following strings are invalid:

(empty)
-
7-
--7
8---3


Given a valid string consisting of 0123456789-, output the result as interpreted by Sam's broken parser. Invalid input is undefined behaviour. You may assume the usual code golf defaults for input and output, e.g. programs and functions are both okay.

## Sandbox notes:

• I'll work on the algorithm description a bit later so it doesn't sound so much like "just implement this".
• Will add more test cases later.
• Should eval-like functions be allowed? I'm not sure how much they'd help here
• With the current rules, 42 would evaluate to 4*2=8. Would it be preferable to state that input will never have two or more digits in a row?
• Doesn't rule 1 already cause 42 to be evaluated as 4*2=8 by having precedence above rule 4?
– xnor
Feb 26, 2016 at 5:25
• @xnor Ah true, yes it does (updated). I'm still tossing up whether 42 should be a valid test case - I'm wondering if it might be more interesting golfing-wise if you only ever had single digits... Feb 26, 2016 at 5:34
• I think eval-like functions should be allowed because it disallowing doesn't add much to the challenge Feb 28, 2016 at 2:17

# What can I buy in Catan?

Catan is a board game where players collect 5 commodities: brick, lumber, wool, grain and ore.

You can trade commodities in the following ways:

• you can always sell 4 of one kind to buy 1 of any other kind
• if you have 3-for-1 trading possibility you can sell 3 of one kind to buy 1 of any other kind
• if you have a given commodity trading possibility you can sell 2 of the given commodity to buy 1 of any other kind

• road costs 1 brick and 1 lumber
• settlement costs 1 brick, 1 lumber, 1 wool and 1 grain
• city costs 2 grain and 3 ore
• development card costs 1 wool, 1 grain and 1 ore

The same costs in matrix form:

 |blwgo
-+-----
r|11
s|1111
c|   23
d|  111


## Examples

This is code golf so the shortest entry wins.

# Transpose a paragraph

For some odd reason I want to transpose paragraphs. The basic idea of a transpose is that this:

a b
c d


Is changed to:

a c
b d


[more on the rules here]

## Examples

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer suscipit, arcu
ut facilisis blandit, neque tellus consequat urna, in semper mi purus vel magna.
Nam placerat mauris ac varius dictum. Nunc placerat ipsum et lectus iaculis
feugiat. Aenean eget felis ac purus fermentum dapibus ac nec leo. Vestibulum
convallis euismod metus a gravida. In eu nisl facilisis, accumsan urna a,
consectetur mauris. Integer vitae lectus et justo vestibulum lobortis. Donec
quis erat est. Curabitur pellentesque mi purus, vel posuere nunc volutpat quis.
Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia
Curae; Maecenas ultrices, elit sed finibus euismod, lacus tortor hendrerit
libero, quis auctor risus mi in tortor. Vivamus finibus consectetur est, quis
ultricies metus congue sit amet. Ut non elit libero. Fusce efficitur nec ante ut
tempor. Proin vitae commodo tortor. In aliquam massa a nulla eleifend commodo.

Lorem      ut         Nam        feugiat.   convallis  consectetu quis       Vestibulum Curae;     libero,    ultricies  tempor.
ipsum      facilisis  placerat   Aenean     euismod    mauris.    erat       ante       Maecenas   quis       metus      Proin
dolor      blandit,   mauris     eget       metus      Integer    est.       ipsum      ultrices,  auctor     congue     vitae
sit        neque      ac         felis      a          vitae      Curabitur  primis     elit       risus      sit        commodo
amet,      tellus     varius     ac         gravida.   lectus     pellentesq in         sed        mi         amet.      tortor.
consectetu consequat  dictum.    purus      In         et         mi         faucibus   finibus    in         Ut         In
adipiscing urna,      Nunc       fermentum  eu         justo      purus,     orci       euismod,   tortor.    non        aliquam
elit.      in         placerat   dapibus    nisl       vestibulum vel        luctus     lacus      Vivamus    elit       massa
Integer    semper     ipsum      ac         facilisis, lobortis.  posuere    et         tortor     finibus    libero.    a
suscipit,  mi         et         nec        accumsan   Donec      nunc       ultrices   hendrerit  consectetu Fusce      nulla
arcu       purus      lectus     leo.       urna       volutpat   posuere    est,       efficitur  eleifend
vel        iaculis    Vestibulum a,         quis.      cubilia    quis       nec        commodo.

• Where did "vel" (at the bottom of column 1 in your output) come from? Feb 29, 2016 at 6:47
• I'm not exactly sure, but I don't (and won't) have time to fix it for a while. 1-2 months min. Feb 29, 2016 at 21:08

Help! My playlist is all unsorted! I need to sort it, but I can only move a video to the top or the bottom. I'd like to do this quickly so I need a solution with the minimum amount of moves. But I'm lazy and it seemed like a good fit, so I'm posting it here and now you have to do it! Now, since this is code golf, you have to do it in as few bytes as possible.

Input is a permutation of the values from 1 to n (where n is any number from 1 to ∞). Output is a list of moves that sorts the list. For example for input 1 3 2 4 a valid output would be 2D 3D (second element to bottom, third element to bottom)

Test cases:

Input         Possible Output
1 3 2 4       2D 3D
5 4 3 2 1     4D 3D 2D 1D

• I'd flag as unclear. Input and output specifications? Test cases? Just a description is not enough. Feb 29, 2016 at 16:43
• I'm having trouble understanding the test cases. No matter which side I try as "bottom", neither one of the outputs seem to sort the inputs. Mar 1, 2016 at 15:16
• For the first input, it is 1 3 2 4 1 2 4 3 1 2 3 4 For the second, 5 4 3 2 1 5 4 3 1 2 4 5 3 1 2 4 5 1 2 3 5 1 2 3 4 1 2 3 4 5 Mar 1, 2016 at 16:10
• 1. "A list of values from 1 to n" without any other mention of n says nothing about whether or not there are duplicates. I think you mean "a permutation of the integers from 1 to n", but that needs to be explicit. 2. The top appears to be index 0 (or 1 in weird languages) and the bottom index n-1, but that needs to be explicit. 3. 2D seems to mean "move the value at index 2 to the bottom": "element 2" is far too easy to interpret as the element with value 2. 4. The first paragraph says "minimum amount of moves", but the second test case doesn't meet that criterion. Mar 1, 2016 at 21:12

# Recompose a series of alternating binary sequences

This is the inverse of Decompose binary into alternating subsequences. The essence of this linked challenge is to convert a decimal integer to binary, split on adjacent 0s or 1s (like 010110001 would become 0101 10 0 01), and convert each subsequence back to decimal.

Let's take a sequence of positive integers in decimal, like

10 21 2 5 1 1 1 1 1 2 1 2 5 1 85 5 1 1 1 5 1 1


And convert each number to binary...

1010 10101 10 101 1 1 1 1 1 10 1 10 101 1 1010101 101 1 1 1 101 1 1


But wait, this is the inverse of the decomposition problem. The original binary representation was split where there were two adjacent 0s or 1s. Hence, if 10101 comes after 1010, then there must have been a leading 0. Adding these in results in this:

1010 010101 10 0101 1 1 1 1 1 10 01 10 0101 1 1010101 101 1 1 1 101 1 1


Which, after concatenation and converting back to decimal, gives 727429805944311 as the final answer.

Take a sequence of positive integers as input and output a single positive integer after recomposition.

## The Details

• Input may be in a sensible, human-readable format that is convenient for your language. All integers must be in decimal or unary, and no precomputation in the input is allowed.
• Output must be a single positive integer, in either decimal or unary.

## Test Cases

Input                Output
0                    0
1                    1
2                    2
1 1                  3
2 0                  4
5                    5
1 2                  6
1 1 1                7
2 0 0                8
2 1                  9
10                   10
1 2 2                50
1 2 2 0              100
1 1 1 1 10 0 0       1000
2 1 1 2 0 2 0 0 0    10000
1 2 2 1 1 2 2        12914
5 42 10 2 1          371017

• "Easily" is a bit (read: very) subjective. Does retina count? Sed? I'd recommend just allowing unary, the problem doesn't seem like it would be easily solved in unary, so it shouldn't make much difference. Mar 7, 2016 at 16:43
• @FryAmTheEggman: Good point. I'll edit both questions to say that. Mar 7, 2016 at 19:59
• Can you edit this so it is comprehensible without reading another question? E.g.: "The original binary representation was split where there were two adjacent 0s or 1s." -- says who? Mar 8, 2016 at 6:22
• @msh210: How is it now? Mar 8, 2016 at 9:00
• … Much better, thanks. Mar 8, 2016 at 13:23

# Count the Esolang Puns

This challenge was inspired by this conversation in chat.

## Introduction

Yesterday in chat, there was a conversation where several people extensively used esolang puns. @CᴏɴᴏʀO'Bʀɪᴇɴ kept a tally throughout to see who used the most puns. Your job will be to help him out by counting the puns.

## Challenge

Your challenge will take several strings as input and output a list of scores. Input can be in a list, separated by newlines, etc. Output can be in any convenient format, in any order. Each string of input will be in the form user : message. Both user and message will only contain printable ASCII characters. You need to count the amount of language puns used in the message and add it to that user's tally. Use this list as the list of languages that count as "pun" languages. You may not read this list from external sources (webpage, file, etc.). In the case of a overlap of languages (ex. example contains the languages example and exam), count all of them (so the example would contain 2 languages). Language names are case insensitive while counting (retina and ReTinA are the same).

### Example IO

Input (taken from the actual conversation):

AlexA. : @Mego He may be CJamming things
ConorO'Brien : I'm jelly >:I
GamrCorps : @AlexA. Argh! The Aura from the eclipse burned by Retinas. Good thing it didn't deal too much damage or I would RAGE!!!
ConorO'Brien : The hexagony, I'm losing.


Output:

[["AlexA.", 1], ["Conor'OBrien", 2], ["GamrCorps", 4]]


Meta Note: Ill add more IO when I get back in an hour or so.

• So, its basically counting the instances of a substring? Mar 9, 2016 at 18:38
• @NathanMerrill yes, counting the instances of several substrings, and outputting the total amount per person Mar 9, 2016 at 18:40
• "You may hardcode that list in your program or read that webpage." Unless you're planning on deducting the hard-coded list from the score or similar, this gives an unfair advantage to languages that can read the webpage. Mar 9, 2016 at 18:41
• Also, I'm assuming we should match the language names case-insensitively. Mar 9, 2016 at 18:46
• @AquaTart Yes it should be case insensitive, I updated the post along with removing the ability to read from the web. Mar 9, 2016 at 18:48
• Isn't most of this challenge compressing the list of languages? Mar 11, 2016 at 10:52

# ACSII Cell Game

The ASCII Cell Game is a simple game where the player has a grid (5x10) of cells (| |):

_____________________
| | | |X| | | | | | |
---------------------
| | | | | | | | | | |
---------------------
| | | | | | | |X| | |
---------------------
| | | |X| | | | | | |
---------------------
| | | | | | | |X| | |
---------------------


Any cells marked with an X have died, and any cells with an O have been blocked. The object of the game is for the spread of X's to stop. The player inputs a point i.e. 1,5 and the computer places an O there. The Xs spread to all adjacent cells every 2 seconds.

## Game Rules:

1. This is traditional code golf with the shortest in bytes winning. I will test this on my computer.
• The specification is not clear. Specify exactly what should happen to display the game board (does it need to update every iteration, or even display at all?); when the game ends (when every square is blocked?); whether players should be prevented from moving in an O or X square, etc. Mar 12, 2016 at 0:53

# Infinite Hexagony Loops

In this challenge, we will be determining whether or not a restricted-source hexagony program terminates or loops forever.

Input

A hexagony program that contains only the

• "Flow Control" characters: / | _ | > <

• the no-op character: .

• the program terminate character: @

Note that since every memory edge is zero for the duration of every program, there are no conditionals in this restricted source version of the language.

• The side length of the hexagon may be any natural number.

• You may assume that inputs are padded with no-op characters to fit the hexagon shape exactly (or you may strip all trailing no-ops as long as you do not change the hexagon size)

• You may take the input in any reasonable fashion.

• DESCRIPTIONS OF WHAT EACH OF THE FLOW CONTROL CHARACTERS DO WILL BE COMING SOON. IN THE MEANTIME, LOOK AT THE WIKI PAGE

Output

A truthy value if the program terminates. A falsy value otherwise.

A program "terminates" if the instruction pointer reaches a '@' character.

Test cases

Coming soon.

Scoring

• I approve. Especially if there is a hexagony solution Sep 8, 2016 at 0:07

# Zipdeck!

A few years ago I invented a simple card game named "Zip Deck". It's not that much fun for humans, but should be perfect for bots. This contest will be run in Python 3.

## Zip Deck rules:

There are N players, and a deck with N*4 cards, numbered 0 to N*4-1. The deck is shuffled (Python's random.shuffle function) and each player is dealt a card. Everyone looks at their card, then, on the count of three, if you believe you have the highest card, say (return) "Zip Deck!"

If you do have the highest card and you said "Zip Deck", you win! You assign floor[C/4] points, divided between the other players any way you'd like, where C is the value of your card.

If either you said "Zip Deck" but don't have the high card, or you do have the high card but didn't say "Zip Deck", you take a penalty of floor[C/4] points (min 1).

The winner is the player with the fewest total points after a set number of rounds (as of now, N2 rounds, but that's subject to change if there are many, many entrants).

## What You Do:

Write a bot! A bot is a descendant of the Player class. Your bot should have a function play that takes two parameters, card (the card you're dealt) and info (a dictionary with information about the state of the game). If your bot thinks it has the highest card, it should return an array containing the string "Zip Deck!" and a dictionary showing how it would assign points if it's correct. If you don't assign enough points, your bot will take the remainder; if you assign too many, instead all of the points will be given to your bot that round.

The info dictionary contains the following keys:

• 'round': The current round, starting with zero. Maybe your bot wants to get more reckless when the game's about to end?
• 'scores': A dictionary containing every player's current score.
• 'last': A dictionary showing what everyone was dealt last round and what the bot returned (so an array with either an empty string or "Zip Deck!" plus their point allocation). Useful if you're trying to determine the other players' strategy.

An example info from one of my test runs:

{'scores': {0: 5, 1: 6, 2: 2, 3: 1},
'last': {0: [12, ['']], 1: [10, ['Zip Deck!', {2: 2}]], 2: [15, ['Zip Deck!', {1: 3}]], 3: [3, ['Zip Deck!', {1: 0}]]},
'round': 3}


Every Player also has two attributes that you can access, my_num (that player's number) and player_count (the total number of players). I've imported random already (naturally); if you want to use any other standard library, just let me know.

class YourBotHere(Player):
def __init__(self, my_num, player_count):
super(YourBotHere, self).__init__(my_num, player_count)
def play(self, card, info):

# If you think you're highest, return an array where the first element is the
# phrase "Zip Deck!", and the second is a dictionary for how you'd assign points
# if you win.
# E.g. ["Zip Deck!", {0: 2, 1: 2, 4: 1}]

# If you don't think you're highest, return an array with one element, the empty
# string (or anything that's not "Zip Deck!")

return [""]

class Player(object):
def __init__(self, my_num, player_count):
self.my_num = my_num
self.player_count = player_count


### Example bots:

class Rando(Player):
def __init__(self, my_num, player_count):
super(Rando, self).__init__(my_num, player_count)
def play(self, card, info):
if random.random() > 0.5:
target = {i for i in range(self.player_count)} - {self.my_num}
target = random.choice(tuple(target))
points = card//4
return ["Zip Deck!", {target: points}]
else:
return [""]

class Serpentine(Player):
# Zigs and zags, trying not to do the same thing too many times in a row.
def __init__(self, my_num, player_count):
super(Serpentine, self).__init__(my_num, player_count)
self.two_back = True
self.one_back = False
self.targets = {i for i in range(self.player_count)} - {self.my_num}
def play(self, card, info):
if len(self.targets) == 0:
self.targets = {i for i in range(self.player_count)} - {self.my_num}
will_call = False
if self.two_back == self.one_back:
will_call = not self.two_back
elif card/(self.player_count*4) > 0.8:
will_call = True

self.two_back = self.one_back
self.one_back = will_call

if will_call:
target = self.targets.pop()
return ["Zip Deck!", {target: card//4}]
else:
return [""]


## Controller

The controller code can be found on my GitHub (along with most of these instructions again verbatim). [You can also see OrionBot, the one entry I got when I tried to run this competition in class; I'll remove it so that only PPCG bots are in the tournament before this goes live.] Intentionally bad or losing strategies are OK, but bots that attempt to crash the controller/cause an infinite loop will be disallowed, as are bots that collude or cooperate in any way.

## Sandbox Concerns

First and most importantly, does everything in the rules write-up make sense? Are there any loopholes I haven't considered?

This game is straightforward enough that the winning strategy might be completely boring, but I don't think it's necessarily obvious that it will be. Also, I would have said that rock-paper-scissors-lizard-spock has a very clear and well-known best strategy in game-theoretic terms, and that challenge still saw a dizzying array of answers.

• Hello, welcome to PPCG, and thanks for using the Sandbox! :) From what I can see, this looks alright, but I'd definitely leave it around a while to see what people think. I'd be concerned that the best strategy for calling "Zip Deck" might be random, in particular. Also, this game seems relatively simple, so if you feel like you could probably create a controller that passed the values as strings and allowed more than just python answers. Some other challenges have done that to great success e.g. Good Versus Evil Apr 4, 2016 at 23:18
• Thank you! I'd love to open this up to more than just Python answers, but I haven't worked with the Subprocess. I'll have to spend some time with it to see if I can make it work. Apr 4, 2016 at 23:52
• 1. As far as I can see, the rules don't actually state what values are on the cards. That's quite an important detail. 2. IMO you should restrict to no more than one entry per user and no cooperation between users. Apr 5, 2016 at 13:26
• @PeterTaylor Good catch! I've updated accordingly. (The cards are valued from 0 to N*4-1) I feel like most King of the Hill challenges I've looked at allow players to submit multiple bots, though; has there been a problem with that in the past, beyond the obvious Soviet chess player issues? Apr 5, 2016 at 17:14
• I've got a nice Communicator class in python. That said, I've actually moved away from Python for KoTHs because its slow, so its been a while since I used it, but it should be fairly unbuggy. Apr 5, 2016 at 17:53
• Also, the reason that RPSLS got so many answers is because it was simple and had a pop-culture reference. Its hard making a spec that is simple and easy to read (I'm a terrible example, IMO), and unfortunately, I don't see any pop-cultureness in this challenge. That said, best of luck to your challenge! Apr 5, 2016 at 18:02
• There has been intentional submission of entries which were intended to collude to the benefit of other entries in the past; my proposal is more extreme than any which has been implemented so far, but there have been other KotHs which explicitly prohibited collusion. I'm concerned that with this format where you can choose to whom you want to assign points if you win there is a greater than usual benefit to collusion. Apr 5, 2016 at 20:40

## king-of-the-hill A Simple Card Game

Take 2 standard decks of cards, and 4 players. Shuffle the deck, and distribute the cards evenly among the 4 players. Each player will take one card in their hand (visible to only the player himself), and place the others on a stack in front of them.

Overview:
The goal is to collect all the cards. Taking turns, each player will play a card from either their hand, or hope for the best and play the first card from their stack. After all players have taken turns, the player with the highest card* will win that round and will collect the played cards. He will then start the next round.

Replenishing / losing / winning
If you play a card from your hand, you may draw the first card from your stack and place it in your hand. If you run out of cards on your stack, you may shuffle the cards you collected, and this will be your new stack. You will be removed from the game the moment you have played the last card (which is by definition from your hand) and do not win the consequent round. Last player standing wins the game.

*Highest card
The highest card is in principle determined by the standard sequence 2<3...<King. However, when someone plays an ace, the sequence becomes 4<...<Ace<2<3, i.e., 3 becomes the highest card. The winner is determined at the end of the round - the order of play is irrelevant.

If there's a tie, the 'winning' players do another round, and the final winning player will collect all the cards 'on the table', i.e., of all the tied rounds. Edge case: if you tie with your final card, you will lose after all, since you have no cards to play with after the tie.

Examples:
We have four players: Alice, Bob, Carol and Dave. Let's denote the cards by [1-12] where 1 is an ace.

A:  5, B: 9, C: 1, D: 8.   Winner: Carol.
C: 10  D: 4  A: 1, B: 2.   Winner: Bob (2 beats ace)
B: 11, C: 1, D: 4, A: 1.   Tie between Carol and Alice... (both aces)
C:  4, A: 3                Winner: Carol (she gets six cards).
C:  3, D: 2, A: 1, B: 6.   Winner: Carol (3 beats ace)


## The challenge

Build a player that will win as many games as possible. You will receive 10 points for first place, 5 for second, 3 for third and 1 for last place. Your final score will be divided by the number of simulation runs I did, so you will score [1-10].

Your code must fit within [an amount of bytes to be determined; 1kiB?]

## Sandbox questions:

1. Would you consider participating? Why (not)? (challenge quality)
2. What would be better?
• A Java controller (each player extends the default Player class). Advantage: no I/O parsing required, just simple function calls. Disadvantage: excludes all other languages, lest a wrapper is made.
• A STDIN/STDOUT controller (each player will receive input over STDIN, and return what they do on STDOUT). Advantage: virtually any language can compete. Disadvantage: possibly cumbersome I/O format to present the players with all relevant information.
• 1. Why use standard decks of cards? The mechanic would be identical if the deck has 8 copies each of the numbers 0 to 12, and the special-cased parsing would be eliminated. 2. The weird stuff with the ace isn't adequately explained. E.g. what happens if the four players play, in order, 3, A, 3, A? Apr 7, 2016 at 13:40
• @PeterTaylor Thanks for the feedback! 1) I did that to make it less abstract. Eventually, I will use 1-12 for coding the cards. 2) Is it better explained now? (in your case, the two players playing a '3' would tie and have another round) Apr 7, 2016 at 14:48
• Still not very clear, no. King < Ace when no-one plays an ace (and therefore it doesn't matter) and Ace < 2 when someone plays an ace, so that for all practical purposes Ace < 2 always? Apr 7, 2016 at 15:17
• @PeterTaylor Oh wait, I see where the confusion comes from, my bad. Yes, you are right, and the latest edit should reflect that. Any comments on whether to use a Java controller or a STDIN/STDOUT one? Apr 7, 2016 at 15:22
• A Java controller can easily wrap a stdin/stdout one. You should be able to steal a wrapper from some existing koth. I'm still not entirely clear what's going on with the ace: is the full post-ace-play order 4<5<6<7<8<9<10<J<Q<K<A<2<3 ? Apr 8, 2016 at 7:20
• @PeterTaylor Yes, exactly. I will try to make a wrapper then, thanks once again for the feedback. Apr 8, 2016 at 7:44
• Unless I'm wrong, it seems like you will never have more than one card in your hand, but the language you use implies that you can. Can you have more than one? If so, how? Apr 8, 2016 at 12:52
• You mean the moment you have played the last card from your hand and do not win the consequent round? I meant to say "The moment you have played the last card (which will by definition be your hand card), ...", I'll fix that phrasing. Or is any other part of the spec also confusing? Apr 8, 2016 at 13:01
• Also, you refer to playing "a" card from your hand, which makes it sound like a choice. I would replace "a" with "the" in those cases. The only thing besides that that you could add is how you will determine a winner if you have, for example, N bots submitted, given that the game takes exactly 4 players. Apr 8, 2016 at 13:28

# Introduction

Binary trees are easy to manipulate using recursion. For example, here is Java code that declares a binary tree and determines its size (the number of nodes it contains) recursively:

public class BinaryTree
{
private Node root;

/**
* Constructs a search tree with the given root.
*
* @param the root node
*/
public BinaryTree(Node root)
{
this.root = root;
}

/**
* Gets the number of nodes in this tree.
*/
public int size()
{
return size(root);
}

// private helper function
private int size(Node node)
{
if (node == null)
return 0;
else
return 1 + size(node.getLeftChild()) + size(node.getRightChild());
}


The definition of Node is not shown. As you would expect, it has methods getLeftChild() and getRightChild() that either return other instances of Node or null. A Node does not have backlinks to its parent.

# Challenge

Write a non-recursive function to determine the number of nodes in a binary tree. You should not make any assumptions about the ordering of the nodes; however, you can assume that a reasonable hash function exists on nodes such that you can expect O(1) access time using a hash table.

In addition to not calling itself, your function should not simulate recursion through a stack-like data structure, and it should not call any recursive functions. You may use standard data structures, such as a set that uses hash codes to determine membership.

Solutions will be judged by their efficiency. Specifically, they will be judged by their time complexity, with space complexity used as a tie-breaker.

• Hi, welcome to PPCG and thanks for using the Sandbox! :) fastest-algorithm challenges are hard to run because they are hard to score well, just as an FYI. Also probably worth noting is that not all languages will have the same definition of binary tree. In addition, I'm not certain this is possible without "simulating recursion", arguably, any looping construct at all is also solvable through recursion, so I don't think that's really a good way to word this restriction. Apr 15, 2016 at 20:38
• I think that by the standards of this site, this question should be considered a dupe of this one and therefore closed. (This is sad, because the older question is still semi-vandalised by its OP). Apr 15, 2016 at 21:01
• Thanks for the feedback. I'll be back with a different question some time. Apr 15, 2016 at 22:03

## Decimal to Troll

Discworld Trolls have a unique number system. From Wikipedia:

Trolls have a numeral system of their own, based on powers of 4.

The base numerals are one (1), two (2), three (3), many (4) and lots (16), which can be combined to form higher numbers.

When combined, each numeral's value is added to those of the others. Higher-valued numerals take priority over lower-valued ones, so that 4 is written "many" and not "two-two" or "three-one" and 20 is written "lots many" rather than "many many many many many". If there are no ones, twos or threes, the number is written with spaces between the numerals; if any exist a hyphen replaces the space between every numeral.

## The Challenge

The challenge is to write a program that accepts a positive integer and outputs the equivalent troll counting string, including the correct separator (hyphen or space) based on the above rules.

Examples (including those from Wikipedia):

Input   Output
-----   ------
1      one
2      two
3      three
4      many
5      many-one
10      many-many-two
20      lots many
32      lots lots
126      lots-lots-lots-lots-lots-lots-lots-many-many-many-two


This is code-golf, shortest answer wins.

• Nice challenge! Apr 18, 2016 at 12:20
• I feel like this is a dupe of this challenge about money. I think the greedy algorithm still works, the only differences that I see between these is the I/O formats and the amounts to use, which I'm afraid don't sufficiently differentiate them, in my opinion. Apr 18, 2016 at 13:27
• @FryAmTheEggman I can see the similarities, and yes, the repeating units in the output and separator are the main differences. But Discworld! :) Happy to withdraw it if consensus is it's too similar. Apr 19, 2016 at 1:48

# king-of-the-hill Tron Bot Racing

It's time to begin annual Tron Racing Tournament. Create a bot that will steer your cycle to a victory!

### Glossary

Board is a 100x100 square that wraps around its edges.

### Game

Bots leave impassable trail. In the beginning of the game, all the bots participating (2 in case of a duel) are placed randomly thorough the map. Then, at the beginning of each turn, all bots must decide the direction they will chose next (Up, Down, Right, Left) based (or not) on the available data, which is the empty cells in each of the directions. If bot tries to move into an occupied cell, his turn is repeated until it makes a valid move. If after 10 tries bot still won't make a valid move, it dies. Game ends when all bots die. Score is the length of your trail.

Example:

. . . . . d . .
. . . b b b b .     Received data:
. . . b . u b .     L0 U3 R3 D3 T1
. . . b . u b .
. . . b . u b .     Length of line of sight is ceil(map_size/2) - 1
r . . b b B r r     and it wraps around map edges.
. . . . . d . .     u, r, d - lines of sight
. . . . . d . .     B - bot, b - bot's trail


If bot decides to go Left (and will collide with his own trail), he is invoked one more time with Tries increased: L0 U3 R3 D3 T2'.

### Submissions

The engine is written in Node.js, so your bot should be a function in Javascript that accepts 1 argument (state array) and returns integer between 0 - 3 which corresponds to your chosen direction.

function RandomBot(state) {
return Math.floor(Math.random() * 4);
}


0 - Left, 1 - Up, 2 - Right, 3 - Down

You can also write your bot in any other runnable language. It will be run every time a decision needs to be made, with data pushed into StdIn 3,3,0,2,1 and output (single integer) required at StdOut.

However, by using Javascript you have the advantage to use this to save data between runs.

### Winner and conditions

Bots will be dueling with each other, each duel repeated 100 times. Standard loopholes apply.

# Meta

How to create leaderboard? How to score wins and loses? Is there anything that can be improved? This is my first entry ever and I have already a working prototype. I have concerns with the data passed to bots. Maybe its too small? Anyway, let me know what do you think about it guys.

• Similar Apr 20, 2016 at 10:57
• Even more similar. Except for limited data/sight, it's a duplicate. Apr 20, 2016 at 13:56
• I think that if the match would consist of bigger board and all the bots at once, it would be different enough to not be a duplicate.
– Are
Apr 20, 2016 at 15:03
• I agree that a free-for-all should be sufficiently different, especially given the limited sight. Then again, with that many walls floating around, it could end up being very hard to avoid an impossible trap. You might want to do some test runs with some naive bots to see what happens. Apr 21, 2016 at 2:29

# Overview (basically the wiki page)

Chopsticks is a game played with two hands and two people. Both start with one finger out on each hand, the finger count. On a player's turn, they must choose one of their opponent's hands. That opponent adds the player's finger count to the one on that hand (and extends that many fingers). Once a hand's finger count has reached five or more, that hand's finger count is reduced to 0 and can't be used. Once both hands are out, the opponent wins.

To make the game more interesting, there is a mechanic called splitting: A player may use his turn to divide both his hand counts differently than he/she already has. A valid move would be to split from a 2 and a 3 to a 4 and a 1. An invalid move would be to split from a 2 and a 3 to a 3 and a 2. It is illegal to bring a hand back to life like a bunch of my friends like to do, as in split from a 4 and a 0 (a hand that is out) to a 2 and a 2 (back in). I deem it legal (since the Wikipedia article didn't say anything about it) to get one of your hands out using splitting, such as going from 3 and 4 to 2 and 5 (out).

# Challenge

Your task is to write a bot that will play chopsticks against another bot.

# Input

Every time your bot takes a turn, it will be given its opponent's finger count and its own finger count in this format:

[opponent hand 1] [opponent hand 2] [own hand 1] [own hand 2]


There will be spaces in between each value as shown above. Each value will be an integer. The bot should remember the hand numbers, as it is important to the output.

# Output

Your bot must take the data, decide what to do with it, and respond accordingly. Output is in this form:

[target hand] [attacking hand]


where [target] refers to the target opponent's hand and [hand] refers to the hand you are hitting the target with. A valid output would be 1, 2, which says that the bot wants to hit the opponent's first hand with its own second hand.

# Problems and todo (sandbox)

• I do not yet know how to make a program that handles all of this. I'll try to work on it.
• There will be a bracket.
• Should I make tweaks to the game to make it more suitable?
• I may or may not follow through, but regardless I would like feedback.

Thanks.

• If I understand correctly, this is an alternating turn game with about 6125 states. It's therefore very likely that every submission will play perfectly. Apr 27, 2016 at 8:52

## Visualize the Euclidean Algorithm by Tiling Rectangles

META: What's your opinion on moving this to a pop-con instead of a code-golf?

Suppose we have two positive integers, m and n. We can use Euclid's algorithm to calculate the greatest common divisor of these two numbers (the largest number that divides both numbers without a remainder). This is done by essentially taking successive subtractions of remainders until you reach zero. The linked Wikipedia article goes into much greater depth, and the mathematics behind it, for the curious.

Here, though, we're going to visualize the algorithm by taking a rectangle of size m x n and recursively tiling the rectangle with successively smaller and smaller squares until all space is consumed. The length of the side of the smallest square is thus the gcd(m,n).

Assuming m >= n, the first square is of size n x n, and is placed against the bottom edge. This repeats until a square does not fit, leaving a rectangle of size n x (m-kn) remaining, where k is how many n x n squares fit. That process then repeats on the newly-formed rectangle, starting on the left side, then the bottom, then the left, etc., until the original m x n rectangle is fully tiled.

Here's a beautifully done animated example, from that Wikipedia page, of 1071 and 462, showing the result to be 21.
By Proteins (Own work) CC BY-SA 3.0, via Wikimedia Commons.

### Input

• Two distinct positive integers, m and n, via any convenient input method. Without loss of generality, you can assume m > n (for example, if you take input as a tuple, your program can assume that the first element is always the larger of the two, and you don't need to test size).
• Your implementation should be able to handle input up to your language's default int size (or equivalent).

### Output

• An image of at least 300px square, but no bigger than 1200px square, showing a rectangle of proportion m x n, tiled with successively smaller squares as described above. This means that for small inputs the rectangle will need to be stretched, and for large inputs the rectangle will need to be shrunk.
• The image must be oriented so that m (the larger) is the vertical dimension and n is the horizontal.
• Squares of the same size must be distinct. This could be done by coloring the squares differently from their neighbors, by enclosing each square in a border (as in the above animation), etc.
• Output does not necessarily need to be in color, so long as the squares are distinct and understandable.
• The image can be displayed on-screen or saved to a file.

### Examples

[TODO]

You have an even number of identical balls. Half of them are "Light" balls and other half are "Heavy" balls which are heavier than the light balls for a unknown amount. You have to separate them into the "Light" box and a "Heavy" box using a scale instrument which tells you precisely for how much the left side is heavier than the right side when the balls are weighted on it.

Find a way to separate a given number of the balls with the minimal weightings as possible.

This is a challenge to programmatically reslove this question.

The solution should be an algorithm that would separate the given amount of balls with the least weightings as possible.

The Input can be any even number of balls, where the heavy balls will differ in weight from the light balls by a random amount. The balls are marked from 1 to n, and the "heavy" and "light" properties are assigned to all the balls randomly.

Now the program can take any number of balls and place it on the "right" side of a "scale" and then another amount of balls to be placed on the "left" side of the scale. It can read for how much exactly one side is heavier than the another, and then it can proceed to weight another set of balls until he can for sure tell for each numbered ball if it is "light" or "heavy". It should know how to process this in a least "weightings" or "uses of the scale" as possible.

So the goal is to write the most efficient program that can most efficiently separate the balls using the minimal amount of "weightings", and doing that for as many cases of given balls as possible.

• This seems too simple. The optimal algorithm is well-known to the point where it's a common interview question. It would just be a race to be the first to implement it in the chosen language.
– user45941
Apr 29, 2016 at 19:17
• @Mego Thank you for your review, Btw How would one write such an algorithm? Does something like that already exists? My main point of posting this was to answer that question, I would appriciate if you have any way of providing any help. Apr 29, 2016 at 19:25
• @Mego The "interview" question you're thinking of is probably a version with one different weight, as pointed out in the linked question. This seems challenging enough; one could even consider comparing different numbers of balls. Apr 29, 2016 at 20:45
• What this needs to be a good question is some kind of output specification, e.g. giving the expected number of comparisons, an interactive protocol with the user giving comparison results, or some kind of tree decision representation. Apr 29, 2016 at 20:47
• I would just set a pivot ball (e.g. the first one) and compare everything else with it. Runtime complexity O(n). Apr 30, 2016 at 14:36
• @Kennylau but that is exactly the oposite of the solution. You would have then too many unecessary weightings, since the goal is to do it in least possible weightings no matter how complex the real solution might be Apr 30, 2016 at 15:11

# How Many Colours?

Take a grid of ASCII art rectangles as input and output the minimum number of colours you would need to colour it in so that no two rectangles of the same colour are touching.

## Rules

• Input can be any type of grid format (multine string, array of strings, etc...).
• Rectangles only count as touching if the inside is adjacent to the inside of another rectangle (see the bottom-left rectangle in the example).
• You may use different characters to # and space, but if you do, please specify what you use in your answer.
• The grid itself will always be rectangular.
• Grid width and height will always be between 3 and 99.
• Shortest code in bytes wins.

## Example

The output for this input would be 3. An example arrangement of each colour 1 to 3 is labelled in the input below. Note how the bottom-left rectangle does not count as adjacent to the middle one.

#################
# 1  #      # 1 #
######      #   #
# 2  #  3   #####
#    #      #   #
######      # 2 #
# 3  ########   #
#    #  1   #   #
#################


## Test Cases

TODO...

Four Colour Theorem

# Wheels on the Bus Go...

## Scenario

There is a bus heading for an intersection. Usually that is when buses would stop and give way to traffic, but there's a bomb on the bus! The bomb blows up if the speed of the bus falls below 50 miles-per-hour. Find out what speed the bus needs to travel at to avoid crashing into the cars going through the intersection.

## Input

• Take a list of cars coming from the left and another list of cars coming from the right. The lists contain the distance of each car from the intersection as integers.
• The distances will always be from 1 to 99 units.
• There will always be 1 to 9 cars in either direction (2 to 18 total).

## Output

• The speed the bus must travel to make it through the intersection without hitting a car.
• The speed can be an integer from 5 and to 9 which is the speed in miles-per-hour / 10.

## Rules

• Each iteration, every vehicle moves speed in mph / 10 units forwards. The "path" of a vehicle for each iteration includes it's position before the iteration, it's position after the iteration and every position in between.
• The cars always travel at 40 mph.
• A crash occurs when the path of the bus intersects the path of a car in the intersection.
• The bus starts 20 units before the intersection.
• Cars cannot crash into other cars.
• The speed of each bus cannot change during the simulation. You can only give each bus one speed.
• Only solvable inputs will be given.
• Shortest code in bytes wins.

## Example

TODO: Example doesn't make sense yet. Will complete later...

Here's an example using ASCII art to illustrate what would happen with this input and a bus speed of 6. Note: despite what it may look like, the intersection should behave as if it's size is only one unit.

• B = Bus
• . = Vehcile movement during iteration
• C = Car

Input: [ ... ]

                  |     ^ |
|   | | |
------------------ ---     --------------
<-                |    C . . . C
--  --  --  --  --         --  --  --  --
. C           C . |     .  . C     ->
------------------     --- --------------
|   |   |
|     B |
|   | . |
|     . |
|   | . |
|     . |
|   | . |
|     B |


## Test Cases

TODO...

### Tags

• So a bus can never crash with another bus with a different unit digit in the distance, if they are moving from different roads? May 1, 2016 at 15:16
• @KennyLau There's only two roads, the sideways one and the up/down one. The only time buses from both roads will crash is if their paths overlap over the intersection. I'll try explaining it better when I edit it. May 1, 2016 at 15:19

# From Smiles to Molecular formula!

SMILES is an algorithm to represent chemical molecules in one-line ASCII.

In this challenge, we will only be dealing with purely organic chemicals.

• All the Hydrogens are not represented.
• All single bonds not represented, double bond is =, triple bond is #. For example, ethane is CC, ethene is C=C, ethyne is C#C.
• Branches are represented by (). For example, isobutane is CC(C)C, acetone is CC(=O)C.
• Cycles are represented by numbers. For example, cyclohexane is C1CCCCC1.
• All other things are ignored in this challenge.

Your task is to determine the molecular formula of a molecule, given its SMILES representation.

# Specs

Any reasonable input/output format.

These are all accepted, for formaldehyde:

• CH2O
• C1H2O1
• CxHxxOx (unary)
• CHHO
• OCHH
• OHCH

# Scoring

This is . Shortest solution in bytes wins.

# Testcases

input       output
C=O         CH2O
O=C=O       CO2
C1C(=O)CC1  C4H6O
C#CCC       C4H6

• I think you need to tighten up the specs. "Reasonable" is, of course, wide open to interpretation. For example, it's left unclear if the ordering in the output matters. Is it always carbon, hydrogen, oxygen, in that order (omitted if not present, naturally)? Is it "unreasonable" to say OCH2? May 2, 2016 at 13:20
• @dcsohl Thanks, edited to allow that. May 2, 2016 at 13:28
• Are you sure about your examples? My reading of the Wikipedia page is that cyclehexane's SMILES description should contain 6 Cs, but your example only has 5. May 3, 2016 at 10:08
• @PeterTaylor That was a typo, thanks. May 3, 2016 at 14:16
• Which elements do answers need to be able to handle? May 4, 2016 at 6:28
• Also, can we assume that we won't be given aromatics so complicated that the cycle indication numbers go up to 10? May 4, 2016 at 7:16

## The incremental Gijswijt's sequence

The Gijswijt's sequence G is a sequence where the next term is the maximal number of repeating blocks of terms going so far backward.

The first numbers of this series are: 1, 1, 2, 1, 1, 2, 2, 2, 3

The incremental Gijswijt's sequence I is a sequence of Gijswijt's indices where any term of this last sequence I(n) has an image in Gijswijt G(I(n)) that is greater or equal all terms that precede it in that sequence G .

In other terms, It is an increasing sequence of indexes i for which G(i) is at least as large as G(j) for any j < i. Thus it contains the index of every 1 up to the first 2, every 2 up to the first 3, etc

Example:

  G= 1, 1, 2, 1, 1, 2, 2, 2, 3, 1, 1, 2, 1, 1, 2, 2, 2, 3, 2, 1, 1, 2, 1, 1, 2, 2, 2, 3, 1, 1, 2, 1, 1, 2, 2, 2, 3,...

I= 1, 2, 3,       6, 7, 8, 9,                        18,                           28,                        37,...


Your program must output the most you can print from the starting of sequence until the delay between printing two consecutive terms exceeds 10 minutes, the actual number of outputs is your score.

For matter of reliability, the complete accurate "run-lengthed" G sequence must be linked through pastbin or any raw data repository.

the output will be so large to fit an int32 registry, so i suggest to print it modulo 1000007 or dont.

if the scores are not be divergent enough i will apply some salt, scoring is evaluated to N/T where T is executon time in seconds for the last term of sequence, the tie broken by the earlier post .

Only another 45 secs after the delay cap are given as an extra time.

• I would VTC as unclear. May 4, 2016 at 16:08
• hmmm what is unclear ? May 4, 2016 at 16:08
• Winning criterion. until nothing appears in the console for 10 minutes is a bit vague. May 4, 2016 at 16:08
• 10 minutes from last output, is this what u asked me to clarify ? May 4, 2016 at 16:10
• "nothing appears" is a bit vague. I think you want something more like "the time to calculate the next term is > 10 minutes." May 4, 2016 at 16:11
• yes when it exceeds that cap, execution must be halted May 4, 2016 at 16:12
• .. I mean the wording in unclear. Can you say something like the time to calculate rather than the console is empty? May 4, 2016 at 16:15
• if that makes you contented .... May 4, 2016 at 16:18
• I found the definition rather hard to follow, and technically it defines an uncountable number of sequences. I suggest "The incremental Gijswijt's sequence is the (increasing) sequence of indexes i for which G(i) is at least as large as G(j) for any j < i. Thus it contains the index of every 1 up to the first 2, every 2 up to the first 3, etc. If you are familiar with the Records transform on integer sequences, this is effectively a Non-strict Records transform." May 7, 2016 at 8:55
• "For matter of reliability, the complete accurate "run-lengthed" G sequence must be linked through pastbin or any raw data repository." Why? If it's generated by the same process, it would have the same bugs. If it isn't, I don't see the point of asking every single answer to include a pastebin link. "i suggest to print it modulo 1000007 or dont." Either make this a requirement or don't. It complicates comparison of answers to make it optional. "Only another 45 secs after the delay cap are given as an extra time." Extra time for what? May 7, 2016 at 8:59
• @PeterTaylor 1. That is because it a contest for scores in increment, so any new record must be followed by a string of compressed numbers from the last terminus reached, until the new record using his own technique imagine the new score is 2 numbers far from the last result ? the algorithm must print a correct G series that is ground of I series. May 7, 2016 at 10:47
• 2. The numbers could be too big and unintelligible, so either print a remainder or the difference of two edges or print it all along the console modulo something. May 7, 2016 at 10:49
• 3. extra time for me to stop execution. May 7, 2016 at 10:49
• a compressed string of numbers * in the first note May 7, 2016 at 11:31

## Functional Programming in Your Language

A lot of modern programming languages allow some form of functional programming, but I don't often see them used. I'm curious to see how different languages tackle problems that are naturally solved with some form of functional programming. The winning entry to this contest will have the shortest total code as measured in bytes for these four questions

1. Given a three-part list, return a list containing only those members for which the third element is a string.

sampleIn1={{1,2,"fred"},{3,2,1.23},{3,2,"this one too",1.23},{},{"apple","banana",{1,2,3}}}

sampleOut1={{1,2,"fred"},{3,2,"this one too",1.23}}

2. Given a list of lists, each sub-list known to have exactly two elements, both of which are numbers, return a list of the first element in each sublist multiplied by the absolute value of the second.

sampleIn2={{3,4},{-1,3},{1.0,-3}};

sampleOut2={12,-3,3.0}

In the sample output above I distinguish between integer and real output; in practice you can treat everything as a real number if you prefer.

1. Given a list known to be composed only of numbers, return a list of the cube of each member, sorted by the square of each member (or its absolute value, which will have the same result).

sampleIn3={1,-2,0.5,4};

sampleOut3={.125,1,-8,64}

2. Given a list known to be composed only of numbers, return a list with each member of the list divided by the number before it. Since this is undefined for the first number in the input list, that element should be omitted. Where division by zero would result, the list should include notification of exception ("N/A" or something similar as befits your language of choice).

sampleIn4={1,-2,0,5,4};

sampleOut4={-2,0,"N/A",0.8}

Presume that input has been assigned to a variable a in the natural list format for your language, assuming it has one.

To be clear, you don't have to use abstract functions or lambda calculus here, though I suspect that in many languages this will provide a short solution.

Standard rules apply, the examples above are only examples. Your code should work for arbitrary input.

• This challenge explicitly disallows arbitrary classes of languages, is a do X without Y challenge, and a multi-part challenge with no interaction between the parts. The latter is not allowed on PPCG, and the others are highly discouraged.
– user45941
May 9, 2016 at 19:35
• @Mego Read again, I explicitly allow any technique in any type of language. May 9, 2016 at 19:36
• I misread. This is still a multi-part challenge, which are not allowed.
– user45941
May 9, 2016 at 19:45
• @Mego I can combine the challenges. Do you have any other objections or suggestions? May 9, 2016 at 19:45
• As far as I can tell, the challenges are combined. Anyways, the challenge feels like a random list of arbitrary, unrelated tasks. I think perhaps challenge #4 could stand on its own (especially if you made the operator a parameter). May 9, 2016 at 20:07

## Shortest path to the exit:

• Given a n*n grid of 3 symbolic characters {'.','#',*} , where n is inputted, the dot is a safe spot to move from/to, # is a dragon who blows fire and spits magma, * is the outlet . Define (if it can be) the shortest path to take from the extreme upper/right to the star character that a moving point can take where:

m is an integer m < n given by user-input or a function dimention with n, that generates obstacles # at the dynamic point m modulus n from the starting point, the last # point so far is replaced by an exit *, if no such path exists print 0 or a negative amount or undifined/null anything witch doesnt throw an error.

Testcases:

input: 7,3
output:9


why? the input generates this grid

...#...
#...#..
.#...#.
..#...#
...#...
#...*..


The shortest path is marked as _

__.#...
#__.#..
.#__.#.
..#__.#
...#_..
#..._..


More TODO ...

Hints/notes

• Solution is cyclic

• No solutions when m+1 divides n or n-1 . (to verify)

• Like I said in your other challenge, please use proper English grammar and spelling.
– Nic
May 10, 2016 at 21:52
• This looks like a standard path-finding, which we've already done. Making every mth place also make an obstacle doesn't make it sufficiently different IMO May 10, 2016 at 21:52
• @NathanMerrill how is so ? obstacles are systematically generated but not arbitrarily May 10, 2016 at 22:04
• Hmmm...I guess that does allow for optimizations. Yeah, this would work for a code-golf. You should define what happens if there is no solution, or guarantee that there will always be a solution. May 10, 2016 at 23:05
• The text says that the start is the extreme upper/right, but the example seems to start from the upper left. Do you mean upper left? Also the slash makes it look like upper or right, rather than referring to a corner, which doesn't seem consistent with the example. May 11, 2016 at 0:49
• @trichoplax this is not really a big issue, up/right to down/left or up/left do down/right. May 11, 2016 at 6:47
• @Agawa001 It's no issue either way - I'm just helping get it clear which one you want before the challenge goes live May 11, 2016 at 14:30
• @trichoplax the challenge will never get a soul to the other end anyways i m not really ready for another blizzard of downvotes May 11, 2016 at 14:40
• I never know which challenges will make it to main. I just try to help clarify them until we can tell one way or the other May 11, 2016 at 14:48
• I dont know why serial dvter did miss to star the 4th comment, is it because is not castigating ! May 12, 2016 at 7:58
• I think you have a gross misunderstanding of what constitutes serial downvoting. Serial downvoting is when somebody goes through and downvotes a lot of posts, typically out of spite. I downvoted both this and your other sandboxed post because they are very poorly specified, and you seem to have a tenuous grasp on the English language that makes understanding these challenges impossible.
– user45941
May 13, 2016 at 5:23
• that's penguins being penguins May 13, 2016 at 7:46

# Simulate a DNA Computer code-golf

DNA computers are very powerful computational models, theoretically able to solve NP-complete problems such as SAT deterministically in polynomial time. Your task in this challenge is to write a program/function that simulates the behaviour of a very simple DNA computer that accepts only four different kinds of commands.

# DNA and Tubes

To make things a bit easier, we model DNA strands as non-empty words over {0,1}. So for our purpose, the following are all valid strands of DNA: 1, 010010, 01, 1100101.

Our DNA computer has access to an infinite number of (test) tubes T1,T2,T3,..., each of which contains a finite number of DNA strands. That is, Ti ⊂ {0,1}* for all i ∈ ℕ+. For example, T1 = {1,0100101,000} would be a valid tube. At the beginning of a simulation, all tubes are assumed to be empty (Ti = ∅ for all i ∈ ℕ+).

# Commands

Our computer supports four different commands: Initialize (I), Merge (M), Filter (F), and Amplify (A). In the following, let the pairwise different numbers i, j, k ∈ ℕ+ denote indices of tubes Ti, Tj and Tk. Furthermore, let n ∈ ℕ+ and b ∈ {0,1}.

## Initialize

• Description: We take all possible DNA strands of length n and put them into tube i.
• Syntax: i = I n
• Semantics: Ti ← {0,1}n
• Example: After the execution of 2 = I 3, we have T2 = {000, 001, 010, 011, 100, 101, 110, 111}.

## Merge

• Description: We mix the contents of tubes j and k and put them into tube i.
• Syntax: i = M j k
• Semantics: Ti ← Tj ∪ Tk ; Tj ← ∅ ; Tk ← ∅
• Example: If T2 = {00, 111} and T3 = {1, 010, 00}, then after the execution of 1 = M 2 3, we have T1 = {00, 111, 1, 010} and T2 = T3 = ∅.

## Filter

• Description: We remove all DNA strands from tube j whose n-th bit is not equal to b. We put the remaining strands into tube i.
• Syntax: i = F j n b
• Semantics: Ti ← Tj ∩ {0,1}n-1∘{b}∘{0,1}* ; Tj ← ∅
• Example: If T2 = {1010000, 111, 1, 0101}, then after the execution of 1 = F 2 3 1, we have T1 = {1010000, 111} and T2 = ∅

## Amplify

• Description: We put an exact copy of the contents of tube j into tube i.
• Syntax: i = A j
• Semantics: Ti ← Tj
• Example: If T2 = {1010000, 111, 1, 0101}, then after the execution of 1 = A 2, we have both T1 = {1010000, 111, 1, 0101} and T2 = {1010000, 111, 1, 0101}.

# Input

Input will be a DNA program, i.e. a sequence of these four commands, that can be read from STDIN, taken as a function argument or even be stored in a file. It's up to you whether you take them as a list or a string with some kind of separator. Also, you can choose a different separator for the parameters of the commands or encode each command as a list as long as you do so consistently. For example, instead of the command 1 = F 5 10 0, you may use [1,"F",5,10,0], 1;F/5/10/0, 1=F(5,10,0) or the like. You may assume that the input is always syntactically correct. For example input/output pairs, see below.

# Output

You have to output a truthy value iff tube 1 is not empty (i.e. T1 ≠ ∅) after the execution of the DNA program specified in the input. Otherwise output a falsey value. Note that you are not actually required to simulate the DNA program step by step - if you find a more clever way to calculate the output of a given program, feel free to use it.

# Examples

In the below examples, all commands are ;-separated and encoded as described in the "Commands" section.

Truthy

• 1 = I 20
• 2 = I 4; 1 = A 2
• 3 = I 1; 1 = M 3 9
• 1 = I 4; 2 = A 1; 3 = F 1 1 0; 4 = F 3 2 0; 5 = F 2 1 1; 5 = M 3 4; 1 = M 2 5
• 1 = I 3; 2 = A 1; 3 = A 1; 4 = A 1; 5 = F 2 1 1; 6 = F 3 2 0; 7 = F 4 3 1; 2 = M 6 7; 1 = M 2 5; 2 = A 1; 3 = A 1; 4 = F 2 1 0; 5 = F 3 2 1; 1 = M 4 5 (1)

Falsey

•  (the empty program)
• 2 = I 5
• 1 = I 2; 2 = A 1; 3 = F 1 2 0; 2 = A 3; 1 = F 2 2 1
• 1 = I 1; 2 = I 1; 3 = M 1 2
• 1 = M 2 3

# Scoring

This is , so the shortest answer (in bytes) wins.

1 In case you are interested: this example evaluates the formula (x1 ∨ ¬x2 ∨ x3) ∧ (¬x1 ∨ x2), that is, the contents of T1 after execution of the program are exactly the assignments to (x1,x2,x3) that make this formula true. One can create similar such programs for any 3SAT formula. The number of commands needed is linear in the size of the given formula.

• I think this question would benefit from being written in a more layman-friendly and less symbolic way. While I might know that Ti ⊂ {0,1}* means that each test tube is a subset of the kleene star of the set {0, 1} I don't think every user of this site will. You also use things like ℕ+ instead of saying, say, "positive integers" and so on. This is just my personal opinion, but I think if you can explain something with words instead of symbols without compromising much in terms of length, you are more likely to be understood when using words. May 11, 2016 at 18:47

Inspired by this, but also different. I need help phrasing things, putting them together coherently, etc.

Also, I can't decide on what the magic numbers (size, toggles per turn, etc.) should be.

Lastly, is this even winnable?

(oh, and if anyone wants to write a nice "backstory", that'd be much appreciated)

(also I have a couple of notes to myself in there so I remember what I was doing when I come back to this later)

## Murderous Life

### Overview

The game is played on a 100-cell-wide, 300-cell-long board. It's cylinder-shaped -- patterns will wrap around the long sides, but not the short ones. Attempts to toggle cells behind the short edges will fail, and all cells along the short edge are considered dead. The center 200x100 area (the "no man's land") is the focus of the game. The farthest left 50x100 area (next to the origin) is the Police Headquarters, and is where the police can send units from. The far right is the Robber Hideout, and is where they operate from.

Your program will communicate with the controller via standard input and output. Each message is terminated with a newline (\n, ASCII code 10). The code your program must exit when it receives Control+C (ASCII code 3). It doesn't have to stop immediately -- for example, if you have to close IO handles -- but it should take less than a second. It also doesn't have to end cleanly -- throwing an error is fine. As long as you've tidied up after yourself.

Immediately, both programs print to STDOUT their name and their author's name, with a hyphen in between, followed by a newline. This signals that they are ready to begin receiving input. After that, the turns will start immediately. The turns work like this:

1. Both players are sent a string containing the current map through their STDIN. The format is detailed below.
2. The desired moves are collected from each program in no particular order.
• Note: If the moves are invalid for any reason -- they attempt to change a blocked square, too long, fail to precisely match the format, anything like that -- then the program is immediately ejected from the game, and I'll drop a comment on your post letting you know what happened.

3. All of the moves are applied at once to the board
4. One iteration of Conway's Game of Life (standard rules) is run on the map.
5. The number of living cells in the No Man's Land is tallied.

The game runs for 5000 turns, after which the average number of living squares in the No Man's Land is calculated. This is the score of both the cop and the robber. Once three answers of each type have been submitted -- aside from the example ones -- I'll begin playing the answers against each other. The scoreboard will be updated daily until at least a week after the first answers have been submitted, or if it's later, three days after the last one has. The full score of any given program is the average of all of its scores.

Each program will be played against every other exactly once. Any attempts to communicate or disrupt the other AI -- except through the board -- are banned. If your bot doesn't respond to CTRL+D or CTRL+C, it will be banned.

Note that, if you have to do some cleanup before exiting, that's fine -- the "kill switches" don't have to work instantly. They do, however, have to work quickly. They can throw an error or something like that if you like.

You can always assume you'll get valid input.

### In Cops version:

The point of the game, for the cops, is to keep the board as dead as possible. You can toggle up to 30 cells in the Police Headquarters per turn, creating or removing whatever patterns you like. At the end of the game, the Cop program with the lowest score wins.

### In Robbers version:

The point of the game, for the robbers, is to make as many cells in the No Man's Land alive as possible. You can toggle up to 20 cells in the Robber Hideout per turn, in whatever arrangement you want. At the end of the game, the Robber program with the highest score wins.

[link to the opposite side's version]

### Message format

Aside from the initial name string, all messages passed between programs will be like this:

1,4 12,0 9,125 299,6


Each pair is a coordinate pair, with the X values first and Y values second. The origin is at the top left of the board -- on the Police side of the board. The indexes are zero-based.

To be explicitly clear, the format is a space-delimited string of pairs. Each pair consists of two base-ten numbers, between 1 and 3 digits long, separated by a comma. The first number must not have a value greater than 299 or less than 0, and the second number must not have a value greater than 99 or less than 0. In addition, the first number must be between 0 and 49 (inclusive) if the player is a Cop, or between 250 and 299 (inclusive) if the player is a Robber.

I've written a basic example bot. To change what side it's on, simple change the comments on the lines indicated.

# Uncomment the part marked with the team this one should be on
#Cops
place_at = (0..47).to_a.product (0..97).to_a
glider = [[1, 0], [2, 1], [0, 2], [1, 2], [2, 2]]
toggles = 30
#Robbers
place_at = (0..47).to_a.product (0..97).to_a
glider = [[1, 0], [0, 1], [2, 2], [1, 2], [0, 2]]
toggles = 20

puts 'GliderLover-QPaysTaxes'

while gets
# We don't care what the board is like in this dumb AI.
puts toggles.times.map {
loc = place_at.sample
glider.map { |offset| loc.zip(offset).map { |(a, b)| a+b }.join ',' }.join ' '
}.join ' '
end


Is there anything else I need to specify?

• .. I think this is the first C&R with a controller we've had? May 10, 2016 at 22:07
• @EᴀsᴛᴇʀʟʏIʀᴋ Maybe! It fits CaR better than KOTH, though.
– Nic
May 10, 2016 at 22:08
• @QPaysUnicornTaxes yeah. May 10, 2016 at 22:09
• I think tagging this as KOTH is logical. The closest thing done before was: codegolf.stackexchange.com/q/51029/31203. Maybe putting both tags would be ideal. May 11, 2016 at 19:17
• @MegaTom Hm, probably. It's certainly got elements of both. I still haven't finished the controller though, so until then I can't post anything :)
– Nic
May 11, 2016 at 19:38

An idea for a king-of-the-hill challenge:

You have a "memory arena" with a fixed size. You have several programs which "reside" in the memory arena (I mean you take the assembly and put it in the arena). The goal of the game is to get another program to access memory outside of this "arena" which then causes it to die because access outside of the memory arena is not defined. The last program standing wins.

You enter in assembly code (I have not determined which architecture yet). At the beginning of a round all of the entries get randomly placed in the memory arena. Each program will execute one instruction per turn.

It would be very similar to red code but in actual assembler.

# Three Indistinguishable Dice

Given three dice rolls (integer values from 1-6) in sorted order (so as to be indistinguishable), write a program that converts them to the sum of two dice with an identical distribution.

Inspired by standupmath's The Three Indistinguishable Dice Puzzle. A follow-up "solution" video was also posted, but arguing about "elegance" of one way or another is a bit subjective. Counting characters isn't. :D

## Details

• Score is the length of the program in characters
• The program can be a function that's called somehow, or executable script that reads from stdin, or whatever's convienent.
• No "rerolling" by getting entropy from another source

## Example Test Code

Rather than doing any sort of probabilistic testing, it's easy enough to rip through the 216 (63) cases of all the three dice and assert that your function returns each value as many times as it should. It will be called with identical parameters (e.g. the cases 1, 2, 3 and 3, 2, 1, ... are presumed indistinguishable and are (arbitrarily) converted to 1, 2, 3).

The below is in Python, written hopefully generically enough to be clear to port. If your language of choice uses stdin/stdout, it would be a bit different. The testing code is just for testing and not scored (though if you want to provide it for other users of your language or I/O method, that might be useful).

from thing import f

# this is the fair distribution of the sum of two dice,
# multiplied by 6 (because each should be hit 6x more)
dist = {
2: 6,   12: 6,
3: 12,  11: 12,
4: 18,  10: 18,
5: 24,   9: 24,
6: 30,   8: 30,
7: 36,
}

d = [1, 2, 3, 4, 5, 6]
for i in d:
for j in d:
for k in d:
ijk = sorted([i, j, k])
result = f(ijk)
dist[result] -= 1

for key in dist:
assert dist[key] == 0


# Collatz or Hailstone sequence efficiently

Sorry for everywhere I posted in the wrong place and thank you to all of the mods for helping me find the sandbox.

Winner is the shortest run time to check whether all numbers up to N will end in x=1 or goes 70 iterations without returning to the original number or without decreasing under a step over Log(N) steps in a row under iterating f(x)=x/2 if x is even and f(x)=(3x+1)/2 if x is odd.

Hint: all one needs to show is that for all x under iteration it hits another y in the sequence that has already been shown to hit 1.

# Sandbox questions

• How can I phrase the above challenge. I set it with parameters that halt for all natural numbers n. I care more about the speed of the program then the shortness of the program.
• Glad to see you've found the Sandbox now. I know it's somewhat counterintuitive that these are posted as answers instead of questions, but it keeps them all in once place with more chance the people who are looking to give feedback will find them. May 18, 2016 at 6:36
• For code that is judged by its speed, rather than its length, we have the fastest-code tag. I've added this and a few other tags. You can click on the tags to see other questions of the same type, and a description of the tag. Feel free to use different tags - I've just added some as suggestions. May 18, 2016 at 6:48
• I've removed the $s since currently this site does not support MathJax or LaTeX. Your challenge seems to work without it, but if you ever need mathematical notation I've found mathurl.com can be used as a workaround (it's fiddly so I'd only recommend it where the mathematical notation is essential). May 18, 2016 at 6:52 • I've looked at the challenges containing the word Collatz and it seems they are mostly code-golf (shortest code) challenges and there have been no fastest-code challenges so far, so I expect this challenge will not be a duplicate. May 18, 2016 at 7:02 • What form should the output take? Just true or false? Or the number of cases that don't get to 1 in 70 steps? I guess the latter will prevent all cases above a certain N having identical output. May 18, 2016 at 7:30 • The biggest problem I see with this challenge being fastest-code is that I don't see any real optimisation potential beyond the "hinted" memoization. Do you believe anything other than actually including memoization will affect runtime significantly? If not then this feels very much like a chameleon challenge for "write an efficient memoization function" and most of the answers will probably have unappreciably different time taken. May 18, 2016 at 13:23 • there are a lot of shortcuts to the clever person for instance if x is of the form 2^k then we're done, similarly if x of form 2^k-1 it will ascend k times in. row, so there are number theoretical optimization other then the hint stated May 18, 2016 at 14:16 • the output should be the numbers under n the fail conditions. i.e. n that doesn't hit one,doesn't cycle in 70 terms, doesn't run for more the Log (n)/Log (2). that is Log base 2 of N. May 18, 2016 at 14:19 • Just so you know, you are getting notifications because this is your post. Other people won't be notified unless you put an @ symbol before their name in your post, like @FryAmTheEggman. May 18, 2016 at 14:49 • oh thank you, @trichoplax I responded what inputs should be May 18, 2016 at 14:56 • Also note, neither of the optimisations you propose would actually improve the speed of a program that computes this. The Collatz operations are so trivial that calling them k times is faster than checking if a number is a natural power of 2. In addition, if you have memoisation you will only ever have to do each power of two once, rather than check each number for a non-trivial property. May 18, 2016 at 14:57 • @FryAmTheEggman Yes for those examples but this does not convince me that there are no shortcuts for the smart programmer hence the challanhe May 18, 2016 at 15:00 • This site isn't quite like other SE sites, I don't believe you should post a challenge if you yourself are not certain that there actually is challenge. That said, I'd guess the actual best approach is to grow a collatz tree upwards and just report the number of nodes that satisfy your properties, but that has the same problems of it being pretty much optimal already: I feel like the differences between responses would be largely negligible. Someone may prove me wrong, but until you know the competition will be worthwhile, I'd recommend against posting on the main site. May 18, 2016 at 15:14 • @FryAmTheEggman Are there other SE you would recommend I ask? May 18, 2016 at 15:22 • No this is the correct site for this question, I just don't think it would be particularly good. You have enough rep to chat by the way, it may be worth finding some other people's opinions; I am not the sole authority on the goodness of questions ;) May 18, 2016 at 15:27 ## Kill the mosketeers Taken a NxN square field, where you are supposed to be on the extreme upper right corner, n mosketeers are waiting an execution instruction that begins with the first lefttmost shooter alternatively until the last righttmost one, in a continuous unceasable order, meanwhile, between any shot and another you are allowed to move one step either to 4 allowed perpendicular directions. T a period permitted to reload the riffle from a shot to another, dependently of steps taken from a move to another, a step is expressed in other words, as the time taken from two consecutive shots that of a mosketeer and his neighbor, so once T steps are elapsed, the mosketeer takes turn to shot again where two shots can occur in real-time. Your task, is more than saving your head on your shoulders, but it is rather the ability of killing all the mosketeers while they are reloading their riffles by a knife, noted that : a mosketeer can shot in an horizontal dimention if his turn comes out, and no moketeer is between him and you, morover, a mosketeer do never move. Given two inputs, N T, say in term of integer output how many mosketeers you are able to kill, return -1 or nil the case you end up killed no matter what you tried. ## Example: input:  4,3  steps: ...* |... .|.. ..|. |..| .|.. ..|. |..| .|.. ..|. ...| .... .... .... |..* .|.. ..|. |..| .|.. ..|. |..| .|.. ..|. ...| .... .... .... |... .|.* ..|* |.*| .|*. .*|. |*.| *|.. ..|. ...| .... ....  |$$|$$ $$| |$$|$||$|$$| |$$ *$$.*| ..* ...*  Output:  4  example 2 input:  4,2  steps: ...* |... .|.. |.|. .|.| |... .|.| |... .|.| .... .|.| .... |..* .|.. |.|. .|.| |... .|.| |... .|.| .... .|.| .... |... .|.* |.|* .|*| |... .|*| |*.. *|.| .... *|.|$$$$|$$$ $|$$|| || |*$$.$ $$.$$.$*$.$.$.$ Output:  2  • 1) Do you mean musketeers? 2) I think the diagrams could do with a bit of explaining - it took me a while to decipher that | meant shooting, $ is a musketeer, * is you and the spaces separated different states. 3) It's not obvious to me why it's not possible to get all four musketeers in the second case, and also more test cases would be good (especially some that result in -1`) May 22, 2016 at 5:08
• @Sp3000 i m sorry to puzzle u this way beucause the challenge isnt about deceiphering patterns, but honestly i think that goes without saying, the second part where yu have been stuck deceiphering it, the two remaing shooters cannot be killed because either of both can shoot you horizontally when you are busy stabbing the other. May 22, 2016 at 9:22
• any ways, you dont have to boggle yur mind more this will gonna be dead on meta, May 22, 2016 at 9:23