# What is the Sandbox?

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

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

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

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

• How are tags added to questions? – guest271314 Jan 9 '19 at 7:51
• @guest271314 You can use this markup to create a tag in a draft: [tag:code-golf] – James Aug 29 '19 at 15:19
• @JL2210 We now have a permanent info box that links to the Sandbox, so the featured tag isn't necessary – caird coinheringaahing Sep 29 '19 at 13:43

There are 1000 phones in a city. Add some switches so that we can freely decide linking pairs (Any amount of pairs). Two phones are connected iff some closed switches directly or indirectly link them.

In graph-theoretic terms, phones and "new points" are vertices, switches/links are edges, and you need to construct a graph with least number of edges such that for all possible list of pairs of the "phone"-vertices, there exists a configuration of the switches (subgraph), such that vertices in the same pair are in the same connected component, and vice versa.

You need to answer with:

1. A list of links, where 0~999 are the 1000 phones, and 1000~ are just point.
2. A program that take some pairs of phone ids, where no two numbers are same, and output the switches that need to be closed. It should run on tio in 60s.

Fewest switches win.

A sample solution may be:

1. [(i,j) for i in range(1000) for j in range(1000,1500)]
2. def f(a):
print ([(a[i][0],1000+i)for i in range(len(a))]+[(a[i][1],1000+i)for i in range(len(a))])

Which uses 500000 switches.

SN.

1. Should I require that when a connection is added or removed, there's a series of moves so that no other connections are affected?
2. Directly using sorting network for $$\\mathcal O(n \log^2 n)\$$ seems to use more switches than $$\\mathcal O(n^2)\$$ solution. Should I have more phones?

## I'll Just Make A Snake

I noticed a post (now deleted) that pointed out that 05AB1E (legacy), when called with no arguments and non-empty input, will make a "snake" using the input:

Not sure what to do now with the input, so I'll just make a snake:

*****
*
*
*
*****
*
*
*
*

Cute, and seems simple enough. However, the snake generation has a few quirks that I thought would make an interesting challenge to replicate.

# The Challenge

When given a non-empty string as input, a snake is generated using the following algorithm:

1. If the input string is shorter than 17 characters, pad the string with duplicates of itself until its length is >= 17.
2. Generate a snake segment by replacing the non-space characters of the pattern with characters from the input string, following the direction of the snake. (Print characters right-to-left 5, up-to-down 3, left-to-right 5, up-to-down 4.)
3. If there is a previous snake segment generated, replace its last line with the first line of this segment.
4. Remove the used characters from the string.
5. Discard the first character of the remainder of the string. If there is no remainder, instead set the remainder to the original input string, minus its first character.
6. Pad the string with copied of the original input string until its length is >= 17.
7. Repeat steps 2-6 N times, where N = Length of input string.
8. Return the generated snake.

You do not have to handle empty inputs or non-string inputs.

You do not have to print the beginning message "Not sure what to do now with the input, so I'll just make a snake:".

Note: 05AB1E (legacy) actually has some different behavior when given a base-10 integer as input. We will be ignoring that and treating all inputs as strings.

# General rules:

• Input and output may be in any reasonable format.
• Trailing spaces and/or a single trailing newline are acceptable.
• This is , so shortest answer in bytes for each language wins. No answer will be marked as the answer.
• Standard rules apply.
• Default Loopholes are forbidden.
• If possible, please add a link with a test for your code (i.e. TIO).
• Adding an explanation for your answer is highly recommended.

# Test Cases

Here is an (ungolfed) Python 2 program which replicates this behavior, for clarity and generation of additional test cases.

pattern = """{0}{1}{2}{3}{4}\n    {5}\n    {6}\n    {7}\n{12}{11}{10}{9}{8}\n{13}\n{14}\n{15}\n{16}"""

def print_snake(in_str):
print "Not sure what to do now with the input, so I'll just make a snake:\n\n"
l = len(in_str)

snek = [0]

if l < 19:
d,m = divmod(19, l)
if m:
d+=1
in_str = in_str * d

print_str, lost_char, rem = in_str, "", ""

for i in range(l):
print_str = rem + in_str
print_str, lost_char, rem = print_str[:17], print_str[17], print_str[18:]
snek.pop()
snek += (pattern.format(*print_str)).split("\n")

print "\n".join(snek)

Try it online!

Input: *

Output:
*****
*
*
*
*****
*
*
*
*

Input: AB

Output:
ABABA
B
A
B
ABABA
B
A
B
ABABA
B
A
B
ABABA
B
A
B
A

Input: 123456789

Output:
12345
6
7
8
43219
5
6
7
12345
6
7
8
43219
5
6
7
12345
6
7
8
43219
5
6
7
12345
6
7
8
43219
5
6
7
12345
6
7
8
43219
5
6
7
12345
6
7
8
43219
5
6
7
12345
6
7
8
43219
5
6
7
12345
6
7
8
43219
5
6
7
12345
6
7
8
43219
5
6
7
8

Output:
s
s
*
d*dna
e
s
p
e
s
s
*dna*
d
e
s
n
e
s
dna*s
*
d
e
airsa
d
n
e
na*ss
d
*
d
pairs
a
d
n
a*sse
n
d
*
spair
s
a
d
*ssen
a
n
d
espai
r
s
a
ssend
*
a
n
despa
i
r
s
senda
s
*
a
*desp
a
i
r
endas
s
s
*
d*des
p
a
i
ndasr
e
s
s
nd*de
s
p
a
dasri
n
e
s
and*d
e
s
p
asria
d
n
e
*and*
d
e
s
sriap
a
d
n
s*and
*
d
e
riaps
s
a
d
ss*an
d
*
d
iapse
r
s
a
ess*a
n
d
*
apsed
i
r
s
ness*
a
n
d
psed*
a
i
r
dness
*
a
n
sed*d
p
a
i
s
*
a
ed*dn
s
p
a
i

# What season is it?

I don't think we have a challenge for this yet, surprisingly. The closest ones are:

Output the current season, using the astronomical definitions:

• Spring begins on the day of the spring equinox
• Summer begins on the summer solstice
• Fall begins on the fall equinox
• Winter begins on the winter solstice

You may use the northern or southern hemisphere dates.

## Input

None (use the current date).

## Output

One of these strings (case insensitive): spring, summer, fall (or autumn), winter.

Your program must finish in a reasonable (less than 1 day) amount of time.

# Problems

• Is calculating the dates of the equinoxes/solstices too difficult? (I don't want the best solution to involve a big lookup table)

• What range of years should this be required to work in?

• Should the output format be less strict? ("Any 4 distinct values" rather than the season names)

• I deide to upvote the old one and downvote this one – l4m2 Dec 30 '18 at 2:13
• They're sufficiently different so I think it's ok for both to exist. – user202729 Dec 30 '18 at 3:57
• However looking at the wikipedia "Equinox" page, it mentions "However, because the Moon [...]" (second paragraph), which interpretation should be chosen? – user202729 Dec 30 '18 at 3:58
• Is there any range of date that it's ok to be wrong outside the range? (say, 1~2 century? I don't know how the motion of the Earth/Sun will change in some million years) – user202729 Dec 30 '18 at 3:59
• To your last question: I would say yes as the core of this challenge appears to be figuring out where the current date lies in relation to the solstices/equinoxes and translating that to specific strings doesn't, in my opinion, really add anything to the challenge. – Shaggy Dec 30 '18 at 5:33
• I guess this should use the second interpretation, since it seems to be easier to calculate and more commonly used. I'll probably allow errors of a few minutes, in the event that the equinox/solstice occurs near midnight where a small rounding error might affect the result. – 12Me21 Dec 30 '18 at 5:45
• int main(){print("summer");} // guaranteed to be random – Kenneth Taylor Aug 2 '19 at 18:26

# Surreal Numbers

Surreal numbers are one way of describing numbers using sets. In this challenge you will determine the value of a surreal number.

# Intro

A surreal number consists of two sets: a left and right. The value of the surreal number must be greater than all numbers in the left set and less than all numbers in the right set. We define 0 as having nothing in each set, which we write as {|}. Each surreal number also has a birth date. 0 is born on day 0. On each successive day, new surreal numbers are formed by taking the numbers formed on previous days and placing them in the left/right sets of a new number. For example, {0|} = 1 is born on day 1, and {|0} = -1 is also born on day 1.

To determine the value of a surreal number, we find the number "between" the left and right sets that was born earliest. As a general rule of thumb, numbers with lower powers of 2 in their denominator are born earlier. For example, the number {0|1} (which is born on day 2 by our rules) is equal to 1/2, since 1/2 has the lowest power of 2 in its denominator between 0 and 1. In addition, if the left set is empty, we take the largest possible value, and vice versa if the right set is empty. For example, {3|} = 4 and {|6} = 5.

Note that 4 and 5 are just symbols that represent the surreal number, which just happen to align with our rational numbers if we define operations in a certain way.

Some more examples:

{0, 1|} = {1|} = {-1, 1|} = 2
{0|3/4} = 1/2
{0|1/2} = 1/4
{0, 1/32, 1/16, 1/2 |} = 1

To the Sandbox: is this explanation clear? Anything I should add? I want to make sure of this before proposing the challenge.

• The definition is not sufficient for uniquely determine the value. Why is {1|} = 2 and not 3? (they both have power of 2 in the denom = 0) – user202729 Dec 30 '18 at 3:28
• @user202729 because 2 is born before 3. – Quintec Dec 30 '18 at 4:26
• Obviously {1|} is born before {{1|}|}. But what states {1|} is 2 and {{1|}|} is 3? (that's by definition, but what is the defnition? – user202729 Dec 30 '18 at 4:47
• @Quintec I had to check wikipedia to understand what is going on. I think it is worth explaining that we are redefining the symbols 1,2,-1,3,3/4 etc in a way that has nothing to do with the integers/rationals. But as it turns out later we are "lucky" and they happen to behave just like the integers/rationals we are used to if we choose the "right" addition and multiplication. – flawr Dec 30 '18 at 9:33
• You might provide the exact form of $f(\frac a{2^b})$ which day the number is created, if that's not a part to solve – l4m2 Dec 30 '18 at 10:57
• @l4m2 Actually I have a sandbox challenge for that: codegolf.meta.stackexchange.com/a/9962/17602 – Neil Dec 30 '18 at 11:18
• @Neil I guess you also might. You mean to let users write short code to solve it, and a mathematical expression won't matter much – l4m2 Dec 30 '18 at 13:27
• @user202729 Is it more clear now? – Quintec Dec 30 '18 at 23:40
• @flawr Added a note, though I'm not sure if it gets the point across accurately – Quintec Dec 30 '18 at 23:40
• You should take the largest possible value with the smallest birthdate. (i.e., the largest possible value is a tiebreaker) – user202729 Jan 1 '19 at 14:55
• The I/O seems completely undefined. Is the input something isomorphic to two finite lists of rationals with denominators which are powers of two, and the output a rational with denominator which is a power of two? – Peter Taylor Jan 1 '19 at 23:20
• @PeterTaylor yes, I haven't defined the IO yet, just wanted to make sure people understood the concept of surreal numbers. The input will be a list of two arrays, which represent the left and right sets of the surreal number. Inside the left and right sets there may be surreal numbers or regular rationals. – Quintec Jan 1 '19 at 23:34
• I'd suggest limiting this to surreal representations of integers or else this will be a nightmare to deal with. – Beefster Jan 2 '19 at 19:40
• @Beefster Dyadic rationals aren't that hard. – Quintec Jan 2 '19 at 19:54

# Balance those Belts! code-challengeascii-art

In the game Factorio, you transport items around the map using transport belts.
Transport belts are 1x1 tiles, can go in any cardinal direction, and have 2 parallel lanes.

You can also use splitters to split a single belt into 2 belts, a splitter is 2x1 tiles and can receive input from either (or both) of its rear sides, and splits output evenly between both of its front sides. If one side is blocked, items will only be output to the other side.

Finally, you can use underground belts. These have an entrance and an exit, both 1x1 tiles, which must be directly facing each other, with no more than 8 tiles between them.

## Belts

As we will be outputting in ASCII art, we'll use >^<v to represent regular transport belts, with the arrow pointing in the direction of the belt.

As belts have 2 lanes, we'll represent each tile with a 2x2 chunk of ASCII art.
For example a simple belt would look like this:

>>
>>

Corners are simple, if a belt intersects another belt at a right angle, it creates a corner.

For example:

^^
^^
>>>>^^
>>>>^^

Would operate like this:

^^
^^
>>>>^^
>>>>>^

However may be represented as either, for simplicity.

However, there is a caveat to this corner functionality. If there is another belt that affects the direction of the corner piece, a corner is not formed.

For example:

^^
^^
>>>>^^<<<<
>>>>^^<<<<

In this case, the center belt remains straight. All items coming from the left belt will be output onto the left lane of the center belt, whilst all items coming from the right belt will be output onto the right lane of the center belt.

^^
^^
>>>>^^
>>>>^^
^^
^^

In this case, as the "corner piece" is not the start of a belt, it does not form a corner, and all items coming from the left belt will be output to the left lane of the center belt.

## Splitters

Splitters are an important part of belt systems.

A splitter is 2 tiles wide, and so will be 2x4 in ASCII art.

We will represent a splitter using the following symbols:

^^^^
----

|>
|>
|>
|>

----
vvvv

<|
<|
<|
<|

The straight line is the input side, whilst the arrows are the output side.
A splitter will attempt to evenly balance items it receives between it's 2 outputs. A splitter cannot accept any input from its sides, only its back.

Example:

>>|>^^
>>|>>^
|>>>
|>>>

In this example, the input belt is split between 2 belts, one continuing to the right, but a tile down, the other going up
As the belt going up meets the criteria to form a corner, it does so, and lanes are preserved.

A splitter can receive inputs from both of its input sides simultaneously, the input lane is preserved in the output (For example an item received on the left lane of whichever input belt will be placed on the left lane of whichever output belt)

Each individual item received by the splitter will alternate which output belt it is given to, regardless of where the input is pulled from.

For example, given this setup:

<<>>
<^^>
^^^^
----
^^^^
^^^^

If item 1 is received from the left belt, and is outputted to the right side. The next item will be output to the left side, regardless of which belt it was received from.
Again, lanes are preserved, so if Item 1 is received from the left lane of the left belt, it will be output to the left lane of the right belt.

The exception, of course, is with a setup like such:

vv
vv
<<<<>>>>
<<<^>>>>
^^^^
----
^^^^
^^^^

In this instance, the downward facing belt at the top prevents the right output from forming a corner, meaning regardless of which lane the splitter attempts to output to on the right, it will be placed on the bottom lane of the right belt.

Splitters always output their first item to their left.

## Underground belts

Underground belts are vital for intertwining your belts.

We will represent them with the following 2x2 ASCII art tiles:

nn  nn
^^  vv

>)  <)
>)  <)

vv  ^^
uu  uu

(<  (>
(<  (>

The arrows represent the input or output side (depending on the direction of the arrow), while the curve represents where the belt goes underground.

If an Underground entrance (tile with an input, rather than an output, ie arrows pointing towards the curve) does not have a corresponding exit, any items input to it will simply stop at the entrance.

However if an Underground exit does not have a corresponding entrance, items can still be side-loaded onto the exit (see below).

### Connections

An entrance is connected to an exit by having the curves facing eachother within 8 tiles, in a straight line.

For example: (dots used to more easily highlight empty tiles)

>)..  ..  ..  ..  (>
>)  ..  ..  ..  ..(>

These 2 are connected. There may also be any other tiles in the gap between an entrance and exit, like such:

>)^^  >>|>^^nn^^vv(>
>)^^..^>|>>^^^uuvv(>

As there are still 8 tiles between these, they are connected.

However it's important to note that Underground belts use naive connection, meaning this setup causes problems:

>)..  >)  ..  (>
>)  ..>)..  ..(>
A     B       C

In this case I've labelled the entrances and exit. The issue here is that B is the closer entrance that is a valid connection to C, and so A is left without an exit (Each entrance can only have 1 exit, and each exit can only have 1 entrance)

The same of course applies with exits:

>)..  (>  ..  (>
>)  ..(>..  ..(>
A     B       C

In this example, A and B connect, and as there is no free Entrance for C, it remains disconnected.

Unlike splitters, Underground belts support input from the side. This is useful, as they will only pull from 1 lane

For example:

>)..  (>>> D
>)  ..(>>> C
^^
^^
AB

As underground belts cannot form corners, this creates a 1-lane sideload. The left lane from the belt in the bottom left is loaded onto the right lane of the underground belt, meaning the output belt to the right will have only items from the left lane (Labelled A) of the input, on only its right lane (Labelled C).
The right lane of the input belt (Labelled B) becomes blocked, as the curved section of an underground belt cannot accept any input, and the left lane of the output belt (Labelled D) remains empty, provided there isn't another belt also loading items elsewhere.

This mechanic allows you to split individual lanes from your belts and perform more precise balancing.

## Backlogs and Blocking

If a belt becomes blocked, its items will stop moving. This can cause problems if not done properly.

If a Splitter's output is blocked, the splitter will output all of its items to its other output. This is lane specific, so if the right lane of a splitter's right output is blocked, any input it receives on the right lane will be output to the right lane of the left belt.

If items reach the end of a belt, they will stop, creating a backlog.
If a belt hits the side of a splitter, it will stop, creating a backlog.
If a lane hits the curved half of an underground belt (entrance or exit) it will stop, creating a backlog. If a belt hits the curved side of an underground belt, it will stop, creating a backlog.

### Throughput

The game includes 3 different belt tiers, however for our purposes, we will only use the highest tier.

Each lane of a belt can transport 20 items per second. This means a belt using both lanes can transport 40 items per second.

Due to this, it is possible to create a backlog by overloading a belt.
For example:

^^
^^
>>^^<<
>>^^<<

Assuming both side input belts are full and transporting their maximum of 40 items per second, the center belt will be receiving 80 items per second, which is too much.

In practice what this means is that the bottom lane of both input belts will continue moving at max throughput, while the top lanes will stop completely, only moving when the bottom lane dips below 20 items per second, creating a gap for an item from the top lane to squeeze in.

## The challenge

Now that you (hopefully) understand the basics of belts, let's get to the challenge!

Your code should, given 2 positive integers; an input i and an output o, create a layout for a belt balancer that will evenly distribute i input belts among o output belts. In this case, evenly means all i*2 lanes must be split evenly among all o*2 lanes

You can assume both inputs will always be lower than 17 and greater than 0 The orientation of your layout does not matter, provided it has the correct number of inputs, the correct number of outputs, correctly evenly balances all lanes, and all inputs are outputs are at the edges of the layout

All inputs must begin with a 2x2 tile of is, like so:

^^
ii

With arrows pointing in the direction the tile is outputting items to

All outputs must terminate with a 2x2 tile of os, like so:

oo
^^

With arrows pointing in the direction the tile is receiving items from

These special I/O tiles can be thought of unique straight belts.
An input tile cannot receive any input, and will output maximum belt throughput (20 items per second per lane) in the direction of the arrows
An output tile cannot give any output, and will consume maximum belt throughput (20 items per second per lane) from input given directly to the arrows (side-loading not supported)

## Scoring

Your program's score is in 2 parts:
n is your primary score, and is the number of input permutations your program outputs a valid, balanced layout for.
The maximum possible n score is 256, as both i and o can be any integer between 1 and 16, making 16^2 possible inputs, which is 256

s is used as a tiebreaker, and is the sum of the total area (in "game" tiles) of each of your program's valid outputs, where the area is calculated as: (charwidth / 2) * (charheight / 2)

In the event that 2 solutions reach a tie on both the n and s scores, most likely by reaching the same solutions for all possible input pairs, tie breaker is time of posting, with the earlier posted answer winning.

## Examples:

Note these examples may not be the optimal layout for the given inputs in terms of area, but are all correctly balanced

i: 1
o: 1

layout:
oo
^^
^^<<
^^<^
^^^^
----
^^^^<<
uuuu<^
nn<<^^
^^<^^^
^^^^
----
^^
ii

charwidth: 6
charheight: 14
area: (6 / 2) * (14 / 2) = 3 * 7 = 21

i: 2
o: 2

layout:

oooo
^^^^
^^^^
----
^^^^
uu^^
|>>>^^<<
|>>>uu<^
>>|>nn<<^^
^>|>^^<^^^
^^<<<<^^^^
^<<<<^----
^^^^
----
^^^^
iiii

charwidth: 10
charheight: 16
area: (10 / 2) * (16 / 2) = 5 * 8 = 40

## Sandbox Questions

• This challenge is too complex, isn't it?
• Is the scoring okay?
• Are belts explained well enough?
• Did I miss any edge cases?
• This is essentially a Kolmogorov complexity challenge - answers will most likely hardcode existing balancers, and it will just come down to who can compress the data most efficiently. – Mego Dec 31 '18 at 18:11
• @Mego there are not currently existing designs for every i/o ratio though so some would have to be made from scratch – Skidsdev Dec 31 '18 at 18:19
• @Mego perhaps changing the 2nd tie breaker from shortest code to first post. That would require that people beat an existing answer's layouts in size in order to beat their score – Skidsdev Dec 31 '18 at 18:22
• There are existing optimized designs for all sizes up to 8x8, which is half of the problem space. As for the others - once one person makes a design for a balancer of a certain size, there's no reason for the other answers to not use it. And yes, first answer to reach a score is a better tiebreaker than code size - code size as tiebreaker is something to avoid. It would also be beneficial to test the designs using something like this simulator. – Mego Dec 31 '18 at 18:29

# Hearts king-of-the-hill

Goal: build the bot to play the classic card game Hearts.

## The Rules

• Four players per game
• Played with a standard deck of 52 cards (in the protocol, 11 = J, 12 = Q, 13 = K, 14 = A)
• Object: finish the game with the least points
• Each game consists of many rounds, each of which consist of 13 tricks
• At the beginning of a round, each player is dealt 13 cards
• Then, each player passes three cards to an opponent:
• Round 1: Pass to opponent 1 (to your left)
• Round 2: Pass to opponent 2 (across the table)
• Round 3: Pass to opponent 3 (to your right)
• Round 4: No passing occurs
• Round 5 is the same as round 1, and so on
• The player with the two of clubs plays it, beginning the first trick. The suit of the first card played in a trick is the "leading suit."
• Each other player adds a card to the trick (clockwise). If they have any cards of the leading suit, they must play them; otherwise, they can play any card. (Exception: hearts and the queen of spades cannot be played in the first trick.)
• The player who played the highest card in the leading suit takes the trick, adding its cards to their collection of taken cards (distinct from their hand)
• The player who took the trick then begins the next trick with any card from their hand. (Exception: A player may not begin a trick with hearts until a heart or the queen of spades has already been played.)
• After 13 tricks, the round ends. Each player gains points for their taken cards:
• 1 point per heart
• 13 points for the queen of spades
• 0 points for all other cards
• Exception: If a player would gain 26 points (i.e. they took every heart and the queen of spades), every other player gains 26 points instead.
• Another round begins. This continues until a player has ≥100 points at the end of a round. At this point, the player with the lowest score wins (if there is a tie, extra rounds are played until there is no longer a tie).

## The Protocol

Your program can be in any language (that I can run on macOS without too much fuss). It communicates using newline-separated JSON messages on stdin/stdout.

• {"request": "pass", "direction": "left", "state": {...}} (other directions: right, across)
• {"request": "play", "state": {...}}

Expected responses:

• {"action": "pass", "cards": [{"suit": "hearts", "number": 14}, {"suit": "hearts", "number": 13}, {"suit": "hearts", "number": 12}]}
• {"action": "play", "card": {"suit": "hearts", "number": 14}}

The state object:

{
"hand": [cards...],
"taken": {playerId: [cards...]},
"scores": {playerId: number}, // Does not include the current round
"currentScores": {playerId: number}, // Points earned so far this round
"tricks": [tricks...] // The current trick is the last object in this array.
}

The trick object:

{
"leader": playerId, // The player who started the trick
"leadSuit": "hearts", // or spades, clubs, diamonds
"played": {playerId: card},
"winner": playerId // Missing for the current trick
}

You always see the same player numbers: you are player 0, player 1 is to your left, player 2 is across from you, and player 3 is to your right.

• Good idea for a king-of-the-hill. Do you have the controller written yet? If not, I think JSON is a bit overkill. – Peter Taylor Jan 1 '19 at 23:04
• Controller not written yet. Disagree about the JSON—IMO, JSON is a lot easier to deal with than a custom format (especially since I’m passing the full state each time—I could probably set up a passable format for just the events without JSON, but then players would need to track the game state themselves) – Gaelan Jan 2 '19 at 3:39
• When building the controller, you should be sure to allow a player to play a heart in any case if their only cards are hearts and the Queen of Spades (That's not in your rules, but it's kind of an obvious exception). – Spitemaster Jan 3 '19 at 13:43
• @Spitemaster good catch – Gaelan Jan 3 '19 at 17:01

Smallest Working Result - Referenced Reduction

RULES

1. Function must accept a keyed data structure
2. Function must return a modified version of that keyed data structure.
3. Function cannot use any libraries
4. Function will be tested against linked file.
5. Function must work against other similarly formatted files (no having a function that pops out a static answer!)

SCORING

1. To score, must be able to be run against multiple inputted keyed arrays.
2. To score, returned array must be able to be reverse-engineered into original array (conversion must be lossless).
3. Score will be determined by a keyed array built off of attached CSV (based off the oxford dictionary).
4. Score is to return an array with the fewest unique referenced keys.

DESCRIPTION

Build a function that does the following: It pulls in a keyed data structure (dictionary, keyed array, object, etc. depending on your languages' primary keyed reference structure) of the following structure...

ID   |  REF 1   |   REF 2   |   REF 3   | ...
1    |
2    |   1      |   35      |   1
3    |   1      |   2       |   5       |
4    |   FOO    |   7       |   21      |
5    |   FOO    |   9       |           |
6    |          |           |           |
7    |          |           |
BAR  |   6      |   6       |   6
8    |   BAR    |   BAR
...

Each object is made of and unrestricted number of references to other objects (that may or may not be in the table), or are 'prime' objects that reference nothing. Prime objects cannot be reduced. Objects that reference objects not in the table obviously cannot be fully reduced. Further, an object may not directly reference itself.

The goal is to have the fewest things referenced possible.

For example, a table like:

ID   |  REF 1   |   REF 2   |   REF 3   | ...
1    |
2    |   1      |   1       |   7
3    |   1      |   2       |   1       |
4    |   3      |   1       |   3       |
5    |   1      |   3       |   3       |
6    |   1      |   4       |   FOO     |
7    |

Could be reduced to:

ID   |  REF 1      |   REF 2                   |   REF 3     | ...
1    |
2    |   1         |   1                       |   7
3    |   1         |   (1,1, 7)                |   1         |
4    | (1(1,1, 7)1)|   1                       |  (1(1,1,7)1)|
5    |   1         |  (1(1,1,7)1)              |  (1(1,1,7)1)|
6    |   1         |((1(1,1,7)1),1(1(1,1,7)1)) |   FOO       |
7    |

(Notice, although the returned array is bigger and multidimensional, it actually has fewer references in it. While the first has 1, 2, 3, 4, 7, and FOO in the ref columns, the reduced table only has the unique values 1, 7, and FOO.)

The result is scored by the result that has the fewest unique items referenced while still being able to re-create the original table.

And to test, it's going to have a csv of the complete Oxford Dictionary thrown at it that's been converted to a keyed array. (I've uploaded a csv of it here: http://joshup.com/experiments/Oxford_English_Dictionary.csv, each word being the ID, and the following words being the references. Note, file is still being cleaned up, plan to clean before challenge gets moved from sandbox to main area.)

Although the examples are fairly straightforward, the code puzzler is reminded that this will be tested against an array built form the Oxford Dictionary using the word as the key, and the full description of the word as the array (each word being an array item, and, potentially a key somewhere else in the array). This means there is a very real chance that unlike the examples, arrays will reference eachother quite frequently, creating large loops of refrences between them, and the puzzle solver is reminded that choosing which key to reduce other keys into to will likely have a large impact on the final set of unique references.

• Will self references be removed from the test data? – trichoplax Jan 3 '19 at 19:10
• @trichoplax No, they won't. – liljoshu Jan 4 '19 at 5:52

# IPv6 Aggregator

The goal is to aggregate a list of ipv6 subnets into a smaller list.

### Rules:

• The input is a list of ipv6 subnets in the extended format (such as 2001:0db8:0000:0000:0000:0000:0000:0000/48)
• The output must be the optimal
• The output list can be either in extended format, or using any valid compression
• The output list can be unsorted
• The value of irrelevant bits is not important (both ::1/127 and ::0/127 are considered valid)

### Examples:

[2001:0db8:0001:0000:0000:0000:0000:0000/48,
2001:0db8:0000:0000:0000:0000:0000:0000/48,
2001:0db8:0000:000f:0000:0000:0000:0000/48,
2001:0db8:0000:000e:0000:0000:0000:0000/48]
will become
[2001:0db8:0000:0001:0000:0000:0000:0000/47,
2001:0db8:000e:0001:0000:0000:0000:0000/47]

# Index and Get/Set Nested Arrays/Lists

This question is intended as extension of Home on the Range of Lists.

This challenge is to write one or two functions or a program which are getter and setter for a nested array/list mapped to 0-based or 1-based indexing.

# Input

An array/list containing at least one nested array/list (length of 2) where each first element of successive nested arrays is set to either 0-based or 1-based indexes corresponding to each array. Each array is initialized with the first element set to the respective index of the full array.

Example

2 => [0, [1]]
(0) (1) // 0-based indexing
6 => [0, [1, [2, [3, [4, [5]]]]]]
(1) (2) (3) (4) (5) (6) // 1-based indexing

# Rules

• If one function is used the second parameter must be the getter for the element value. If only two arguments are passed the function (input, index to get) acts as the getter. If three arguments are passed, the second argument acts as a getter and the third argument acts as a setter.

• If two functions are used one function acts as a getter exclusively and the second function acts as a setter exclusively. The first argument to the function is the index to get, the second argument is the value to set at the index passed at the first argument.

• If the array/list prototype is modified to chain the method to the rules above still apply.

• The functions are not expected to push to or splice from values in the input array/list.

# Output

• Where a getter is used the value of that index of the array/list.

• Where a setter is used the complete array/list after setting the index to the passed value.

# Test cases

(Single function acting as both getter and setter, where f is the single function)

Setter (0-based indexing)

f([0, [1]], 1, 7) => [0, [7]]

Setter (1-based indexing)

f([0, [1, [2, [3, [4, [5]]]]]], 6, 'map') => [0, [1, [2, [3, [4, ['map']]]]]]

Getter (1-based indexing)

f([0, [1, [2, [3, [4, ['map']]]]]], 6) => 'map'

(Two functions, get and set, 1-based indexing)

get([0, [1, [2, [3, [4, [5]]]]]], 4) => 3

set([0, [1, [2, [3, [4, [5]]]]]], 4, 'set') => [0, [1, [2, ['set', [4, [5]]]]]]

(Modifying Array (or equivalent in the language used prototype) 0-based indexing)

[0, [1, [2, [3, [4, [5]]]]]].get(4) => 4

[0, [1, [2, [3, [4, [5]]]]]].set(4, 'set') => [0, [1, [2, [3, ['set', [5]]]]]]

# Winning criteria

Least amount of bytes in the language used.

Tags: 'code-golf' 'array-manipulation'

• 1. Requiring inputs to be in a particular order is too restricting, you should remove that. 2. Are we guaranteed that the value to be set is either an positive integer (>0) or a non-empty string? You should specify the possible values we'd be expected to handle. – Shaggy Jan 9 '19 at 14:58
• @Shaggy 1) What do you mean by a particular order? That is the input data structure, for consistency. Had this user not been consistent as to input then users would have stated the input is not clear. The input is stable and clear. Can you provide examples of the input that you are contemplating that is not at the question? 2) No, the value set can be any value the language used has available to set. Do you suggest making that restrictive? The data structure must remain the same. A single value at index "0" of each nested array with a nested array at index "1" of that array, except the last. – guest271314 Jan 9 '19 at 17:22
• @Shaggy What edits to the question do you suggest? – guest271314 Jan 10 '19 at 23:07
• If a language has no support for nested lists but there's a way to implement them be scored? Will they need to include the datastructure's implementation in their bytecount? – ბიმო Jan 14 '19 at 16:08
• @BMO Not sure what you mean by "the datastructure's implementation"? Importing a library to achieve the output? If a user is able to implement the requirement using strings, that suffices. A valid JSON string can be converted to an array/list. Implementing the getter and setter might be interesting, though should be possible. – guest271314 Jan 15 '19 at 6:06
• I had Haskell in mind, meant something like this since this is not allowed. But good call with strings. – ბიმო Jan 15 '19 at 10:23
• @BMO The expected output for the first example would be [Element 1 [Element 2 [Element 3 [Element 4]]]]. The second example is valid. There is an additional requirement to create getter and setter to get and set each element either using 0-based or 1-based indexes. If that is achievable using strings, yes, the answer is allowed. – guest271314 Jan 15 '19 at 15:05
• @BMO For example, using JavaScript with String methods and without Array methods this is possible Try it online!. The example does not include a getter or setter, though should be possible using only string methods. – guest271314 Jan 16 '19 at 3:50

# This is not the Timing Attack you are looking for!

## Introduction

I recently was writing a piece of code to verify a HMAC signature (to verify an API request). While doing that I found the given method in the documentation to be "incredibly verbose" and as a somewhat as a somewhat active PPCG member, that's obviously something that needs to be "fixed"! However being also an active member of Crypto.SE I know that HMAC tag verification needs to expose secret independent timing (a.k.a. "needs to be constant time") because otherwise an attacker may just brute-force a valid tag with a couple of dozen / hundred queries checking each time up to which byte was correct.

## The input

The input is two strings a and b which are guaranteed to be of the same length and encoding.

## The output

The output is a truthy or falsey value.

## What to do?

You return a truthy output if a and b have the same content and a falsey value otherwise.

## That sounds too easy, where's the catch!?

Your code must exhibit secret independent timing, that is the runtime of your code may not depend on the actual values of the two strings. To be valid your answer must provide a convincing argument that the execution time is independent of the secret values. To help you, I've listed a helpful guidelines:

• For secret-independent timing it is sufficient to use a non secret independent comparison on the HMAC of both strings under a fresh random key.
• For secret-independent timing there must not be early (loop-) returns or operations that are not evaluated due to short circuiting semantics (assuming you operate on the actual strings).
• For secret-independent timing the values must not be used as array indices or for similar lookups as timing variation can happen due to caching.
• For secret-independent timing the value must not contribute to control-flow decisions, e.g. as a condition for a while or if or as an operand to a short-circuiting &&.
• For secret-independent timing the value must not contribute to operands to multplication or division instructions.

## Who wins?

This is so the shortest code in bytes per language that satisfies the I/O and the runtime behavior wins!

• At least points (2) to (4) - probably also (5) - are non-observable requirements for some languages. For example, what counts as control-flow decision contributing value in brainfuck? – ბიმო Jan 13 '19 at 1:41
• might want to dumb it down a little (i.e. explain jargon) for slow folks like me – don bright Jan 31 '19 at 3:00

# Restoration by patching code-golfstatistics

Given a list of signed floating-point numbers and missing values denoted with a consistent value that doesn't represent a signed floating-point number of your language's natural signed float type (e.g. NaN, +∞, -∞, null/undefined/None, char, string, int/long, unsigned float, double, etc. as long as you can separate it from a real signed float), patch the list so that it only contains floats. Here's how you patch the list:

1. For each run of missing values:
1. Take the mean of the value that precedes the run to the value that follows it.
2. Patch the run:
• If the run has an odd length, replace its middle element with that mean.
• If the run has an even length, replace its two middle elements with that mean.
2. If there still are missing values, go to step 1.

The input denotes data points, and some of them are missing, so you want to patch them. Please note that this method of restoring lost stats isn't recommended for everything.

Your solution must not make use of some stuff.

### Example: [1.0, _, _, _, 5.0, 6.0, 7.0, _, _, _, _, 12.0]

"Patch X.Y" represents the Yth patch of the Xth iteration of the method above.

Patch 1.1: [1.0, _, 3.0, _, 5.0, 6.0, 7.0, _, _, _, _, 12.0].
Patch 1.2: [1.0, _, 3.0, _, 5.0, 6.0, 7.0, _, 9.5, 9.5, _, 12.0].

Patch 2.1: [1.0, 2.0, 3.0, _, 5.0, 6.0, 7.0, _, 9.5, 9.5, _, 12.0].
Patch 2.2: [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, _, 9.5, 9.5, _, 12.0].
Patch 2.3: [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.25, 9.5, 9.5, _, 12.0].
Patch 2.4: [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.25, 9.5, 9.5, 10.75, 12.0].

# Shenzhen I/O command encoder/decoder

The basic elements in Shenzhen I/O are:

P = p0 | p1
X = x0 | x1 | x2 | x3
R = acc | dat | P | X | null
L = 1 | 2 | 3 | ... | 15
V = R | -999 | -998 | -997 | ... | 998 | 999

acc | dat | X are registers containing number between -999 and 999, and P between 0 and 100, but you can't know them in advance. null is register that writing anything into it has no effect, and reading from it provides 0.

The command set is:

nop     nothing
mov V R R:=V
jmp L   unreplacable
slp V   sleep for max{V,0} seconds
slx X   unreplacable
sub V   acc:=acc-V
mul V   acc:=acc*V
not     unreplacable
dgt V   acc:=Tth decimal digit and sign if V in {0,1,2} else 0
dst V V set V1th decimal digit and sign to lowest digit and sign
(negative/non-negative) of V2 if V1 in {0,1,2} else nothing
teq V V s:=1 if V1=V2 else s:=2
tgt V V s:=1 if V1>V2 else s:=2
tlt V V s:=1 if V1<V2 else s:=2
tcp V V s:=1 if V1>V2; s:=2 if V1<V2; s:=0 otherwise
gen P V V
P:=100, sleep for max{V1,0} seconds,
P:=0, sleep for max{V2,0} seconds

Only mov can take two same elements in P or X.

Now you're to encode each command into two bytes. If two commands do exactly same thing they are replacable, but:

1. If element(s) in P and X appear, the existance matters. E.g. mov acc null = nop, but dst 8 x1 = mov x1 null != nop

2. If multiple elements are in P and X, the order matters. E.g. teq acc p1 = teq p1 acc, but teq p1 p0 != teq p0 p1

3. Reading from P also writes 0 to P; Writing any negative to P equals to writing 0 to P, and writing number larger than 100 equals to writing one equal to 100. E.g. mov p1 null = mov 0 p1 = mov -43 p1

4. For sleep function we don't need to consider what happen after 1800 seconds. i.e. gen p0 900 901 = gen p0 900 900 != gen p0 900 899

You need to write an encoder(turning a command into 21 bits, or to say an integer between 0 and 2^21-1) and a decoder(vise versa). Smallest sum of length of encoder and decoder win.

A command checker and equivment finder(two equal commands are mapped to same one) is below: (Spoiler) (WIP)

<input id="vin" maxlength="20" onchange="foo()" onkeyup="foo()"><br><span id="vout">

P.s. I changed the definition of L to allow single line command

• What is Shenzhen I/O? Why would I care about I it doesn't appear anywhere? What is the input of a decoder, what is the input of an encoder? It's hard to tell what this challenge is about.. Is it about encoding/compression, decoding/parsing? Sum of length of what (encoded program or encoder and decoder)? – ბიმო Jan 13 '19 at 1:21
• @BMO Who care what SZIO is. I appear in V. Input a command and output two bytes. Vise versa. It should be a encoding/decoding for you can decide your own encoding rule – l4m2 Jan 13 '19 at 4:36
• Ah I didn't see that, my bad. I would add an motivation or at the very least a link, st. people know what Shenzhen I/O is. Rules should be ok, I think. – ბიმო Jan 13 '19 at 13:20
• But this is not possible to encode in 2 bytes, not even dst V V only: V can be $2000$ values, for that I will need $\lceil \log_2 2000 \rceil = 11$ bits, to encode the tuple (V1,V2) I will need $22$ bits plus two bits for +-@ . Total is: $24$ bits which is more than two bytes. And this doesn't even account for the encoding of dst itself. – ბიმო Jan 13 '19 at 13:24
• @BMO If two commands do exactly same thing they are replacable, and dst only have 297 possible behaviors – l4m2 Jan 13 '19 at 13:32
• You should assume that people have no knowledge about this assembly language. What are the semantics of +-@ ? Would mov null acc = nop (the current rules seem to suggest so, but my intuition tells me otherwise)? etc. Also, I'm not convinced that it's possible to encode each instruction (or an equivalent thereof) in 2 bytes, are you certain that it's possible? – ბიმო Jan 13 '19 at 14:58
• @BMO Th +-@ are just there for purposes unrelated to this challenge. Since "null is register that reading from it provides 0" it equals to mov 0 acc – l4m2 Jan 13 '19 at 16:00
• @BMO Should I remove the +-@ part and allow only 14 bits? – l4m2 Jan 13 '19 at 16:02
• – ბიმო Jan 13 '19 at 16:04

## Write a negadecimal number in words.

Negadecimal is a numeral system with digits $$\0\$$ to $$\9\$$ but is base $$\-10\$$ instead of $$\10\$$. Here are some examples (the left side is decimal numeral, and the right side is a negadecimal numeral):

$$\begin{array}{rcrl} 0 & \to & 0 & \\ 1 & \to & 1 & \\ 9 & \to & 9 & \\ 10 & \to & 190 & \bigl(1 \cdot 100 + 9 \cdot (-10) + 0 \cdot 1 \bigr) \\ 11 & \to & 191 & \\ 20 & \to & 180 & \\ 99 & \to & 119 & \\ 100 & \to & 100 & \\ -1 & \to & 19 & \\ -9 & \to & 11 & \\ -10 & \to & 10 & \\ -11 & \to & 29 & \bigl(2 \cdot (-10) + 9 \cdot 1 \bigr) \end{array}$$

Basically, the carry rule (for both addition and subtraction) is that if you add one to nine, it wraps around to zero and you subtract one from the digit to the left, and if you subtract one from zero, it wraps around to nine, and you add one to the digit to the left. Also note that you can add or remove leading zeros from a number without changing its value. (In particular, the empty string represents the empty sum, i.e. zero.)

## Challenge

Anyways, for the actual challenge, you will take an integer as input and convert it to negadecimal. Then you will convert that to words. What do I mean by that?

The digits $$\0\$$ to $$\9\$$ have their regulars names (i.e. zero, one, ..., nine). The negadecimal numbers $$\10\$$ through $$\90\$$ (i.e. negative ten through negative ninety) have the following names:

onetao, twotao, threetao, fourtao, fivetao, sixtao, seventao, eighttao, ninetao

The negadecimal numbers $$\100\$$ to $$\900\$$ have their regular names (i.e. one hundred, two hundred, ..., nine hundred).

Numbers that are a digit followed by three or more zeros are created by combining the above names. For example, negadecimal $$\2000\$$ is twotao hundred, $$\40000\$$ is four hundred hundred, $$\300000\$$ is threetao hundred hundred, etc.

All other numbers are named by writing it in expanded notation, naming each summand (which will be one of the above), and conjuncting them. For example, negadecimal $$\5402=5000 + 400 + 0 + 2\$$ is fivetao hundred, four hundred, and two.

Zero summands are a special case. If the whole number is zero, you just write zero. Otherwise, you omit all zero summands.

## Examples

Here are some examples (the left side is a decimal numeral, and the right side is a negadecimal numeral noun):

0 → "zero"
10 → "one hundred and ninetao"
11 → "one hundred, ninetao, and one"
-11 → "twotao and nine"
-10 → "onetao"
-9 → "onetao and one"
101 → "one hundred and one"
999999997 → "ninetao hundred hundred hundred hundred, nine hundred hundred hundred hundred, ninetao hundred hundred hundred, nine hundred hundred hundred, ninetao hundred hundred, nine hundred hundred, ninetao hundred, nine hundred, ninetao, and seven."

This is , so the shortest code wins!

• Rather subjective: Interesting challenge, until I read "Then you will convert that to words" :( – ბიმო Jan 21 '19 at 16:21
• The challenge is well explained, but it could be improved a lot with some minor formatting. Eg. use MathJax, make some paragraphs (intro,actual description, i/o rules, examples or the like). As it stands it's not very easy to read. Also by conjuncting do you mean join with , except for the last two with and? What about spaces, are they important? – ბიმო Jan 21 '19 at 16:21
• @BMO What do you mean subjective? I specify exactly what I mean by convert to words later in the post. – PyRulez Jan 21 '19 at 18:26
• @BMO Conjuncting means to join with commas, and then to insert and between the last and second to last item. If there are only two items, you omit the comma. If there is only one item, you omit the and. – PyRulez Jan 21 '19 at 18:26
• My opinion is subjective: That I liked the first part of the challenge, but the second part not so much. Okay, got it maybe you could add that to the challenge and describe how the spacing works there. One question which should be answered (in the challenge) for example: Is the space after the , obligatory or can a solution omit it? – ბიმო Jan 21 '19 at 18:58
• I reformatted the post (didn't change the wording), feel free to roll-back if you don't like it. Another question popped up when doing so: Some examples seem to have a . at the end, is this on purpose? If so you should explain when it is required. Also is lower-case important? – ბიმო Jan 21 '19 at 19:31

# KoTH: Iterated Nash bargaining!

In this king of the hill challenge, you must play an iterated Nash bargaining game. You and your opponent must return a number between 1 and 100 which says how much money out of £100 you want.

If the total amount requested by the players is less than £100, both players get their request. If their total request is greater than that available, neither player gets their request. However, to spice things up, it is iterated — you will play 200 rounds against each opponent.

Your bot should be a Python 3.7 function that takes 4 inputs in the following order: your current points, your opponent's current points, all moves you have played (in a list) and all moves your opponent has played so far (also a list).

Here are two examples, one plays the opponents last move (and 50 on the first move):

def copycat(themp, myp, theml, myl):
if len(theml) < 1:
return 50
else:
return theml[-1]

The other plays 50 if they have less than 50 points, and 70 otherwise:

def fiftyseventybot(thempoints, mepoints, themlist, mylist):
if thempoints <= 50:
return 50
else:
return 70

Your bot will play 200 rounds against each opponent, in the 'round robin' fashion .Whoever ends up with the most points wins. Standard loopholes are banned.

Have fun!

## Sandbox

This is my first question, make sure to tell me if anything could be worded better or if anything is spelled wrong etc.

Also tell me whether you think this is a good idea and if you have any ideas to add to it.

Is there not enough of an incentive to change if both players are going 50? if so, what incentives could be created?

There seems to be disagreement between @PeterTaylor and @Spitemaster. I would like to reach some kind of consensus on this. Could anyone possibly comment on what they think?

• It seems to me that this won't work - neither player has any incentive to play anything other than 50. – Spitemaster Jan 11 '19 at 18:46
• Agreed; furthermore, upon gaining an advantage on an opponent, it only makes sense to play greater than 50 every turn so that either you gain more points or neither of you gain any points so that you end with more points than them. – Sebastian Jan 11 '19 at 21:14
• @Sebastian I can see why you would say that, but as you are trying to gain the most points over all rounds (playing every bot) you would want to maximise your score, meaning that tactic would lose you potential points as it relies on both of you not getting any points not being a bad outcome.(sorry that was quite a bad way of putting it but I hope you get my point) – Arkine Jan 12 '19 at 8:48
• @spitemaster I originally thought that if you went for a higher number, you could try to force the opponent down, and you could use small numbers by finding when bots are constant and you’ve got no chance etc. Maybe there needs to be some kind of short term incentive for going high, like, for example, in the prisoners dilemma? – Arkine Jan 12 '19 at 10:08
• The very idea of a Nash equilibrium is that neither player has an incentive to change. I don't think this is a good thing upon which to base a challenge. – Spitemaster Jan 12 '19 at 23:50
• I think it might end up with interesting answers if there are any bots which do not actually aim for equilibrium. It depends on whether the bot cares more for maximizing its own score or minimizing the amount the other bot gets as an advantage – fəˈnɛtɪk Jan 13 '19 at 1:39
• @Spitemaster, I can tell you from personal experience in earlier king-of-the-hill games that playing a Nash equilibrium may get you a fairly high position in these iterated games but it never wins. The winner usually plays a strategy which has a worse mean but high variance until they get an advantage, and then switches to the equilibrium. – Peter Taylor Jan 14 '19 at 16:29
• @PeterTaylor In games like the Prisoner's Dilemma, the Nash equilibrium is defect. As there are ways of getting more points for both players, it is advantageous to not play that and instead try something semi-cooperative. In this game, there is no strategy that would be advantageous over the Nash equilibrium if both bots cooperated. For a bot to beat the 50 bot, you'd have to have a majority of bots willingly lose to either the bot that would win or the 50 bot. – Spitemaster Jan 14 '19 at 18:35
• @Spitemaster, in practice that's not a problem. – Peter Taylor Jan 14 '19 at 21:26
• Maybe changing the amount of money from 100 to 99 or any other odd number would solve it? – Embodiment of Ignorance Feb 4 '19 at 5:45
• @EmbodimentofIgnorance Thats a good idea. It certainly would improve things but you might just get bots switching between rounded down and up halves only – Arkine Feb 6 '19 at 17:58
• Or maybe a restriction that you can't play the same number more than 3 times in a row? – Embodiment of Ignorance Feb 6 '19 at 19:38
• @EmbodimentofIgnorance I'm definitely going to implement your idea about an odd number, I think I might just change it to 99. However banning playing the same number all of the time wouldn't make a difference to too many bots just, in this example ,playing 50 and 49. – Arkine Feb 7 '19 at 19:05

# Check List for Duplicates

Given a non-empty list of integers, return a truthy value if all entries are unique, and a falsey value of there are duplicate entries (or vice versa).

### Examples

[1,2,3] -> false
[1,1,3] -> true
[1] -> false
[1,3,1,5] -> true

META: I couldn't find this as a challenge, but I cannot believe we didn't allready have this. Let me know if you can find anything related.

• Related – Mr. Xcoder Dec 31 '18 at 11:07
• I expect this to be one byte in Jelly. – Adám Dec 31 '18 at 11:08
• @Adám It's 2 bytes long, actually. – Mr. Xcoder Dec 31 '18 at 11:08
• Hm, no Iit is so trivial, that everybody assumed it already exists… We have lots of related (and more interesting) challenges. – Adám Dec 31 '18 at 11:10
• Can the input contain 0s or negative integers? Can we take input as an array/list of strings? Should the 2 outputs be consistent? – Shaggy Dec 31 '18 at 14:44
• Possible duplicate – Shaggy Dec 31 '18 at 19:52
• (Both my Japt solution and my second JS solution there would work for this, without any modifications) – Shaggy Dec 31 '18 at 20:53
• let x=|v| v.iter().unique().count()>0 even short in Rust! but i would kind of like to see if one of the esolangs could get it down to 1 byte, though. would be fun. – don bright Jan 31 '19 at 2:56

# Super Permutations

Find the super permutation for a set of size n. A super permutation of a set is one string that contains all permutations of that set. Here is a helpful video by Matt Parker

# Example

For a set of size 2 all the permutations are AB, BA but the super permutation is ABA because it contains the string AB and BA.
For a set of 3 all permutations are ABC,ACB,BAC,BCA,CBA,CAB and the super permutation is ABCABACBA.

# Challenge

Given a certain size n (n>=1) find a super permutation of that set. To do this you have to use a pattern explained in the video.

# Input

An integer greater than 0. This can be a function input superperm(n) or be taken from user input.

# Output

super permutation of that sized set. This can either be printed out or the return value of a function

# Sample Inputs

all of these are the shortest for that length but this is not a requirement.

1: A
2: ABA
3: ABCABACBA
• Are you sure you don't want the shortest length to be the requirement? As you stated yourself, just concatenating all permutations is trivial, but if this is a [codegolf] challenge, everyone will use that trivial approach to save (loads of) bytes. I know a few programming language which could get all permutations and join them in 2 bytes.. Finding the shortest permutation would prove more difficult however, and seems like a more interesting challenge tbh. – Kevin Cruijssen Jan 30 '19 at 7:42
• @KevinCruijssen the problem with the shortest permutation is that it's not known about 7 or 8. There is a pattern that gives one of the shortest solutions so maybe you should be required to follow that. – Jackson Jan 30 '19 at 23:53
• This feels very dupey to me but I can't come up with the right search term(s) at the moment to find a possible target. I also agree with @KevinCruijssen on the scoring - some combination of byte count and length of output for a specific n would work better. – Shaggy Feb 1 '19 at 1:25
• I don't know of a duplicate from before this sandbox answer was posted, but there is now a superpermutation challenge on main that uses a different scoring mechanism to encourage shorter superpermutations – trichoplax Feb 8 '19 at 20:53

Recently i made a post, but jumped the gun a little... I posted it before getting feedback and ended up getting it put on hold for being too arbitrary, but I have finally come here to get it properly fixed. Also I just got my Meta User fixed, so now I can post here!

Link to original post

Link to chat where all of this is being discussed

Basically I want to make the challenge where you create a quine that when given an input of 0 it outputs itself, and if given some other number it outputs a different quine. For example, abc outputting abc if given 0, abc outputting gef if given 1, abc outputting qwerty when given 255 etc... The scoring will be based on how little bytes can be used and how many extra different quines that it can output.

The problem comes with defining what defines different quine and how to balance the scoring so that coders will be encouraged to write short code, but still try to create different quines that aren't just altered copies of the original or each other

Examples of what not to do

abc      //original
abcd     //output
abcabcabc//output
aabc     //output
aaabc    //output
aaabbbccc//output

stuff like this wouldn't be allowed, I just don't know how to turn that into a rule that can't be abused.

What I want examples

abc      //original
gefh     //output
qwetryiop//output
uiop     //output
kerdp    //output
tttuiiree//output

Basically all of the output quines are different from each other, nor are they similar

And of course no examining source code.

• I would say output a quine without using the same characters from the previous quine but there is already a challenge like that – Luis felipe De jesus Munoz Feb 6 '19 at 20:13
• @LuisfelipeDejesusMunoz Yes, that would work, but I want to see if there is another way to do this without branching away from the original challenge – KrystosTheOverlord Feb 6 '19 at 20:21
• Perhaps you can go back to the polyglot specs, and say that the outputted quines all have to be in different languages? – Jo King Feb 7 '19 at 13:10
• @JoKing That might just work, if I do that I'll have to change the scoring system so that it doesn't push too hard on golfing, but hard enough that people are encouraged to make small programs, and also to try and make it output as many quines as possible. – KrystosTheOverlord Feb 7 '19 at 14:04

# Break Hello World (Cops)/Fix Hello World (Robbers)

## Cops

Your job is to write a broken hello world program. What do I mean by that? Well, you write a valid hello world program, and make changes to it.

Your probably thinking "easy peasy", right? Well, there's one other condition: it must be hard to fix.

Anyways, for the actual rules. First you write a valid hello world program. That means:

• The characters sent to stdout form the string "Hello World!" exactly. Then the program halts gracefully (if given enough time and resources).
• Nothing is read from stdin or sent to stderr.
• No interacting with the operating system (i.e. no modifying files, randomness (unless it is pseudorandom and the seed is the same each run), internet, other commands, etc...)
• No using built-in or imported hashes or cryptographic primitives. If the program implements cryptographic primitives, that's fine though.
• Should work no matter how or on what platform it is run, assuming default options. The language it is written in should be reasonably cross platform and not cost money as well.

Now, make any changes you want to it. However, your score will be based on the edit distance between the valid and broken program (the lesser the better). The exact scoring will be described below.

The broken program can be any string you like (so calling it a "program" is technically a misnomer). Your submission will consist of:

• The broken program
• The edit distance between the valid and broken program, or any greater distance. (The reason you might want a greater distance is if the exact distance would reveal too much information. However, your score will suffer, and the robbers will have more flexibility, so be careful exercising this option). This number will be called your "brokenness" number.
• The language and language version of the valid program. This language should not be one written for this challenge.
• The sequence of literals appearing in the valid program, in the order they appear. (This is to encourage cops to scramble the program structure, not just hard coded values.)
• What the score will be if it is not cracked and after you reveal the solution.
• The date and time at which the program will be safe (as described below). (This way your program will be safe as soon as this time is reached, even if you have not had an opportunity to reveal the solution yet.) You may edit this in immediately after posting the solution, if you prefer, so that you will now the submission time.

After that, the robbers will have 168 hours (one week) to crack your submission from the date posted. If your submission is not cracked by then, your entry is safe. However, you can not claim your score until after you reveal the solution. To do this, edit your answer to include the valid program and an explanation as to why it works (if it takes a while to run). Also include what edits where made (since calculating the edit distance can be hard) and the word "safe" in the title.

How can your program be cracked? A robber just needs to write a valid hello world program (not necessarily the same as you wrote) whose edit distance from your broken program is less than or equal to your submission's brokenness number. The only other stipulation is that it has the same language and language version. In particular, it is not required to use the same literals as your program (this is to discourage cops from making their submission harder to crack this way).

And now for score. If the length of the broken program is L, the brokeness number is b, and the number of characters that can be used in your programming language is k, your score is (k^b)*(L+b)!/(L!b!), which you are trying to minimize. If your wondering were the heck that formula came from, it is very roughly the number of strings whose edit distance from your broken program is less than or equal to your submission's brokenness number (the exact value is hard to compute) (NOTE TO SANDBOX READERS: If you know a more accurate metric that isn't too complicated, let me know.). The idea is that the smaller the search space the robbers have to search, the more impressive it is if it does not get cracked. Also, please post the score in scientific notation for easy comparison.

This is , so the submission which claims the lowest score wins!

Python 2.7, score 7.5×10^53 (Safe)
Broken Program: salida "Hola Mundo!"
Brokenness Number: 18
Literals: "Hello World"
Safe Date: Feburary 12th, 3:42 PM UTC.

Valid program: print "Hello World!"
Edits: Make 7 replacements to get to saida "Holao dorld!". Make 4 deletions to get to saida "Hola do!". Make 4 insertions to get to salida "Hola Mundo!".
Explanation: Uses python's builtin print command to send "Hello World!" to standard output.

## Robbers

Welp, the cops did it again. They broke some hello world programs. Its your job to fix them.

Your probably thinking "easy peasy, I'll just rewrite it from scratch", right? Well, there's one other condition: you have a limited number of edits.

Anyways, for the actual rules. Pick a submission from the cop's thread that has not already been cracked, and is not safe. A submission is safe if it is over 168 hours (one week) old. The submission will have a broken hello world program, a brokenness number, and a programming language and language version, as well as some other useful information (including what literals in the cop's valid hello world program). Your submission must contain a valid hello world program in that language and language version whose edit distance to the broken program is less than or equal to the brokenness number. See the cop thread for what constitutes a valid hello world program. Also note that you are not required to use the same literals the cop used. They are only meant to give you a hint.

Your robber submission should consist of:

• A link to the cop entry you are trying to break.
• Your valid hello world program.
• An explanation as to why it works (if it takes a while to run).
• The edits you made to create the program (since calculating edit distance can be hard).

and then place a comment in the cops submission with a link to your submission. You get a point for each submission cracked. Note that only the first robber to crack a given cop submission gets a point. If you post a submission cracking a cop's submission, but it turns out another robber posted one before you, edit your submission to say that it is non-competing (or you can delete it if you want to). It is also non-competing if you crack a submission that is already safe.

This is , so whichever robber gets the most points wins!

• I don't think the requirement for solutions to include "The sequence of literals appearing in the valid program" is a great idea; in particular I suspect it would run into similar arguments over the definition of "literals" as we've previously had when challenges tried to regulate builtins, comments, strings, etc. Perhaps this won't end up that way, but I don't think it's worth the risk. – Kamil Drakari Feb 12 '19 at 15:19
• I basically understand what you were trying to do with the scoring formula, but I don't think using "number of characters that can be used in your programming language" is a good idea. For one thing, I'm pretty sure there are at least some languages where all unicode could validly appear somewhere in the source code. I think a formula that only uses b and L would be better. Since L is calculated in bytes, I think the most neutral change would be to just replace k with 256. – Kamil Drakari Feb 12 '19 at 15:27
• I also think it would be a good idea to put "also known as 'Levenshtein Distance'" next to your "edit distance" link, or even just use the term Levenshtein Distance instead. It's not a huge deal, but Levenshtein Distance seems to be the more common term in existing challenges (though "Levenshtein edit distance" seems to be a compromise with some precedent). – Kamil Drakari Feb 12 '19 at 15:33
• Your scoring system is weird and confusing. Why not have the cop score be the Levenshtein Distance and say the lowest scoring safe program wins? – Beefster Feb 13 '19 at 0:35
• @KamilDrakari Well, regarding literals, I'm not sure of a good way to encourage cops to scramble the program structure other than this and a popularity contest. Without that restriction, the challenge basically becomes "for what input does this program make it to the "print 'Hello World'". Also, yes, I think I'll make L and b be specified in bytes and k=256. And I'll edit Levenshtein Distance into the question. – PyRulez Feb 13 '19 at 0:39
• @Beefster Then they came make the program as long as they want. They could either have a small "changeable" section, and make the rest of the program either raise an error or print hello world based on some NP-complete problem, or have a massive hello world program with only four or five errors. – PyRulez Feb 13 '19 at 0:41

# Is This Randomizer Seed Beatable?

Randomizers of Pokemon, Zelda, Metroid games (among other games) have gained a lot of popularity in the last few years within the speedrunning community. Basically these are programs that shuffle around items, Pokemon, and even cosmetic things in a ROM of the game. It gives speedrunners a new and exciting challenge for a game they have played perhaps hundreds of times since items affect progression and can lead them to play the game very differently.

Randomizers also have logic that prevents them from making unbeatable configurations. We'll be looking at a simple, but generalized, form of this logic in this challenge.

## Challenge Explanation

You will be given a list of rules as input describing some game world and its item requirements and a list of item locations. Your task is to determine if the item locations represent a beatable seed within the rules.

### World Rules

The rules are a list of required items for accessing a location. A required item may have an associated quantity. For example, a simplified sampling of Super Metroid:

[] => Morph
[Morph] => BlueBrinstarBottomMissiles
[Missiles, Morph] => Bombs
[HighJump] => BlueBrinstarETank
[Morph, Bombs] => CrateriaDescentETank
...
[Supers, HighJump, Morph, Bombs] => Kraid
[Kraid] => Varia
[Varia] => Speed
[Varia, Speed] => IceBeam
...
[Kraid, Phantoon, Draygon, Ridley, Morph, IceBeam, Charge, 3 Missiles, 3 Supers, 3 ETank, Varia, Gravity] => END

It's possible for a location to be reachable by different sets of requirements. Conceptually, this means that any one set of requirements. Here's an example from Zelda: Ocarina of Time (referencing some glitches):

[DekuTreeBeaten] => ForestExit
[Stick] => ForestExit
[Nut] => ForestExit
[KokiriSword, DekuShield] => ForestExit

Keep in mind that the right hand side of the rules list in my example is actually a location id, not an item id. The special location id END indicates the ability to beat the game with those items.

### Item Locations

You will receive a mapping of location IDs and which item they contain. For example:

KokiriSwordChest: HeartPiece
MidoHouse1: Hookshot
MidoHouse2: 5Rupees
...
DampeDig: ForestTempleBossKey
DampeRace1: NayrusLove
DampeRace2: HeartPiece
...
GoldGauntletsChest: DoubleMagic
...

## What does it mean to be beatable?

A player begins a game with no items. If it is possible for the player to, through the continued acquisition of available items, reach the END location, then the seed is beatable. It doesn't matter if all items are obtainable as long as the END location is reachable.

This maps to a variant of graph reachability problems which can be solved relatively easily with a breadth-first search. (Other approaches may work as well)

### Simple example (beatable)

World Rules:

[] => SwordChest
[] => ShieldChest
[Sword, Shield] => FireballScroll
[Fireball] => IceBeamScroll
[Fireball, Sword] => LightningScroll
[Fireball, IceBeam, Lightning] => END

Item Locations:

SwordChest: Fireball
ShieldChest: Sword
FireballScroll: Shield
IceBeamScroll: Lightning
LightningScroll: IceBeam

This seed is beatable with this item order: Fireball, Sword, Lightning, IceBeam. It's impossible to get the Shield because it's locked behind the FireballScroll which requires the Shield. But that doesn't matter because the END only requires the three elemental spells.

### Simple example (unbeatable)

World Rules:

[] => SwordChest
[] => ShieldChest
[Sword, Shield] => FireballScroll
[Fireball, Shield] => IceBeamScroll
[Fireball, Sword] => LightningScroll
[Fireball, IceBeam, Lightning] => END

Item Locations:

SwordChest: Fireball
ShieldChest: Shield
FireballScroll: Sword
IceBeamScroll: Lightning
LightningScroll: IceBeam

This seed is unbeatable because Lightning is required, but is locked behind the Ice Beam Scroll, which requires the sword, which in turn is locked behind the Fireball Scroll, which itself requires the sword to access.

### More test cases

More test cases can be found here.

## Other Notes and Rules

• You can accept the world rules and the item locations in any convenient format or representation, given these restrictions:
• When multiples of one item are in a requirements list, you can represent it by repeating that item multiple times or by having a quantity and item id.
• Both item and location ids must be taken in as alphanumeric strings. (i.e. no converting it to numbers or other more convenient values before passing it into your program/function)
• The sentinel value for the "beating the game" location id must be END, all caps, three letters.
• Item and location ids are case sensitive and must match exactly between the two inputs to be considered the same item or location
• Each location can be reached only once, even if it is reachable from multiple sets of requirements
• You may assume that every location id on the locations list appears at least once on the rules list and that there is at least one END in the rules list
• You may assume that each location id on the locations list appears exactly once and contains exactly one item.
• There is no concept of one-way doors that block off access to previously accessible locations. The requirements list is unordered.
• Location ids and item ids are separate and distinct. For instance, Morph as a location is different from Morph as an item.
• Output a truthy value for a beatable seed and a falsy value for an unbeatable seed.

Happy golfing!

Sandbox: there's a lot here. Any suggestions for explaining things better? Should I add more test cases?

• You might be interested in Rado, a language that's attempting to quickly(ish) solve this problem more generally. I'm not related to the project in any way, I just think it's interesting. – Spitemaster Feb 13 '19 at 21:40

### MisterGeeky's query-to-list challenges:

It is up to you whether you interpret these challenges as following a pattern.

Challenge 1:- Given an array of random numbers and a target number, sample pairs in the array whose sum is closest to the target.

Minimize the error function. To explain this challenge, I need elucidate on the random list.

L = [8.76, 7.89, 6.98, 9.99]

That's just a handmade random list. Yours can be auto-generated of any length.

Say target = 42.

Find a tuple made from cartesian LxL whose sum of elements is closest to target.

These are obviously not the best words to pose the challenge with, they will be refined. How close is this to golf?

Challenge 1.5:- Extend the above problem with all known operations, and even increase the number of numbers that can be taken at a time to reach the target.

op = ['*', '**', '^', '/', '+', '-']

Assume usual meaning for each, ** is sometimes for exponentiation but you can use it for tetration, similar to knuth's up arrow notation. '^' is either XOR or exponentiation. You have the liberty to choose operators. I meant operators known to you in general. Just normal arithmetic should even do.

op = ['+', '-', '*', '/']

I also allow any binary function that doesn't trivially output the target value.

Challenge 2:- Find list of Adjacent Elements to a given element or element position in any 4-dimensional matrix. (ie, m rows* n columns * p sheets * 4th dim whatever)

Even I'm not sure how this is golf. But I typically like to think there's only one approach that's the correct answer. Feel free to argue with me on that :D The idea is that this knowledge gives you a starting point to find n-neighbours of a cell location.

So, you typically have 8 directions of search (4 pure and 4 combined). You start with listing the immediate neighbours

Challenge 2.5:- Find specified number of adjacent elements of a point in n-space. You are free to either sample at random, use rank of the point or use minimum euclidean distances.

Here, you find n-neighbors of a given item. Points for creativity.

Challenge 3:- build a simple recommender, takes a query and outputs a list (recommender as a suggestions lister is not easily defineable)

Challenge 3.5:- improve recommendation efficiency (too advanced for golf)

Third challenge is anything that combines knowledge from first and second challenge.

...

The above are to be refined as golfing challenges, shortest code is the best code.

• all known operations, adjacent, recommender, efficiency? I'm missing some definitions here. – Adám Feb 25 '19 at 8:08
• Hi, and thanks for using the sandbox! While this seems pretty clearly to be a work in progress, I don't think there is particularly much for readers to comment on at the moment. You might consider expanding the first idea into a more complete challenge first so you can receive more useful feedback. From the way the first challenge is worded, I think you may have some trouble with ensuring the error is sufficiently minimised if golf is the goal. – FryAmTheEggman Feb 25 '19 at 20:54
• @FryAmTheEggman Yes, I aso think there are more eleqouent ways to pose the problem. I'm actually not sure what golf is. Is it heuristic shorthand? I'm slowly completing the challenge definitions. My aim is to also make them feel good to read, not just sound jibberish one can't relate with. So, your inputs would be most useful. – MisterGeeky Feb 26 '19 at 9:39
• @Adám Um, I'll remember to do that, but I meant english words. Operation is assumed as binary input function yielding one result value. Adjacent is the direct nearest neighbours, left and right elements incase of a 1D list or array. There will be 8 adjacent elements for an element is a matrix and 26 adjacent elements for an element in a datacube. A recommender is a function that you assume can give you a list of suggestions based on an input-query or item selection. Efficiency is same as the time to get solution. I'll be more than happy to clarify further doubts. – MisterGeeky Feb 26 '19 at 9:50
• I think I see what you mean by the first challenge now. Sorry about my language, I mean "golf" in the sense that the ultimate goal is code golf, that is, writing as short a program as possible. The first challenge appears fine in this regard now, but 1.5 will suffer from this the way you have it worded now. Since each competitor will want to minimise their code, they will implement as few operators as possible. You should certainly specify precisely which operators need to be supported. – FryAmTheEggman Feb 26 '19 at 15:31
• @FryAmTheEggman I am yet to generalize to the maximum extent possible. Writing the question seems so much harder than actually answering it. Um, in 1.5, I mean to say replace the summation of tuples with any other operation to get near to target. I'd have liked to added more challenges along the lines of, you can sample more than two elements to get output, you can reuse but according to some limitation et cetera. These are not simple to pose, especially when this 1d/2d concept is supposed to analogize a higher dimensional thing. – MisterGeeky Feb 27 '19 at 15:56

# Reducing switches in a binary matrix

A row's switch count is the amount of times the array switches from 1 -> 0 or 0 -> 1 when reading the array sequentially. As a Python function this looks like:

def row_switch_count(row):
switch_total = 0

last_r = row[0]

for rr in row[1:]:
if last_r != rr:
switch_total += 1

last_r = rr

return switch_total

A matrix's switch count is the maximum switch count of all it's rows:

def mat_switch_count(bin_mat):
max_switch = 0

for row in bin_mat:
count = row_switch_count(row)

if max_switch < count:
max_switch = count

return max_switch

Write a function to reduce a matrix's switch count for each row to be less than a desired toggle count by permuting the elements in the nth column. You should permute as few columns as possible.

## Permissible permutations

The only permutation allowed is moving the column. You can move a column's index, but you cannot mutate the column itself. For example, you cannot change a column [1, 0, 0] -> [0, 0, 1]. However, you can move a column within a matrix:

([1, 0, 0], ->  ([0, 0, 1],
[0, 0, 0])      [0, 0, 0])

## Input

A binary array with rows > 1 and cols > 5. The sum of all rows in any given column less than 1.

A desired_toggle_count >= rows.

## Examples

Note the solutions are not unique and not all solutions need to be provided. However, there is guaranteed to be a solution, since the trivial solution where you sort all the columns, is valid.

desired_toggle_count=3
([1,0,1,0,1,0,0],
[0,0,0,1,0,1,1])
=>
([1,0,1,1,0,0,0],
[0,0,0,0,1,1,1])

-----

desired_toggle_count=4
([1,0,1,0,1,0,0],
[0,0,0,1,0,1,1])
=>
([1,0,1,0,0,0,1],
[0,0,0,1,1,1,0])

or

([1,0,1,1,0,0,0],
[0,0,0,0,1,1,1]))

----

desired_toggle_count=4
([1,1,1,0,1,0,1,0,0],
[0,0,0,1,0,1,0,0,1])
=>
([1,1,1,0,1,0,0,0,1],
[0,0,0,1,0,0,1,1,0])

or

([1,1,1,0,1,1,0,0,0],
[0,0,0,1,0,0,1,1,0])

----

desired_toggle_count=5
([1,1,1,0,1,0,1,0,0],
[0,0,0,1,0,1,0,0,1])
=>
([1,1,1,0,1,0,1,0,0],
[0,0,0,1,0,1,0,0,1])

----

desired_toggle_count=4
([1,0,1,0,1,0,1],
[0,1,0,1,0,0,0],
[0,0,0,0,0,1,0])
=>
([1,0,1,0,0,1,1],
[0,1,0,0,1,0,0],
[0,0,0,1,0,0,0])

I think this question might have too many requirements to be interesting? Brevity is the soul of wit and this question is not very brief.

• 1. I think the definitions are not standard enough to assume in the first paragraph, and the task would be much more readable if the definitions came before the task specification. 2. NumPy is rather cryptic: it's optimised for speed rather than legibility (especially to non-Python programmers), so it's not very effective as a communication format. 3. The output section should be about formatting, not processing. 4. What happened to "n-dimensional" from the first line? – Peter Taylor Feb 28 '19 at 9:14
• 5. I've clearly not understood the definition of toggle count, because I think ([1,0,1,0,0,0,1], [0,0,0,1,1,1,0]) from the second example has a toggle count of at least six. 6. Since each column has zero or one 1s, the Hamming distance constraint can be given without mentioning Hamming distance: the permitted operations are permuting the elements in the $n$th column, and you should permute as few columns as possible. – Peter Taylor Feb 28 '19 at 9:18
• @PeterTaylor thank you for your feedback. I tried to address all of your suggestions. Please let me know if I can improve this puzzle further! – Seanny123 Feb 28 '19 at 16:09
• OK, I get it now. I'm still not convinced by the test cases: why isn't ([1,0,1,1,1,0,0], [0,0,0,0,0,1,1]) a strictly better solution for the first one? Also, it might be worth adding a guarantee that there will be a solution. – Peter Taylor Feb 28 '19 at 18:16
• @PeterTaylor in your example, you've modified one of the columns, which isn't permitted. I've added example mutations. Sorry, I got confused, when you said "permutation". – Seanny123 Feb 28 '19 at 18:36
• I feel like the python code at the beginning is not particularly illuminating. I think the rest of your description is adequate, and I think you risk hiding more important details like the moving as few columns as possible. Speaking of, it is probably a good idea to state the number of columns moved in each solution. In fact, it may be a better idea to simply make that the output, as it will make other answers easier to verify and it capture what seems to be important. – FryAmTheEggman Mar 1 '19 at 20:01

# (bit)Wise Images

Given a truth table and two images, use the truth table as a bitwise operation to the two images.

For example with the truth table:

1 0
1 0 0
0 1 0

(Note that the top is the first image and the left is the second)

and the two images (0, 2, 4) (a 1x1 image, with the numbers being RGB values) and (30, 20, 10):

You would apply the above truth table to the numbers 0 and 30, of which's binary representations are 00000 and 11110. Using the truth table as a bitwise operation would get us 00000, or in decimal form 0.

This means that the red value of the first pixel would be 0.

Continuing this with the other RGB values would get us 2 and 4 for green and blue respectively.

So the output for this would be a 1x1 image with the only pixel having an RGB value of 0, 2, 4.

NOTES:

You can use any default input or output method.

You can assume that the two input images are the same dimensions.

You can support any image format you want as long as the image format supports RGB values from #000000 (0, 0, 0) to #ffffff (255, 255, 255).

The truth table can be in any format you want

• Are the images guaranteed to be the same dimension? What image formats should be supported (or is it up to us?)? Are we generating a 3rd photo or overwriting the two existing ones (due to asymmetric truth tables, 1+2 can be different from 2+1)? – Veskah Mar 2 '19 at 4:27
• I think you should more clearly specify your value ranges. One would assume, your image channels contain eight bits of entropy. – Jonathan Frech Mar 2 '19 at 4:30
• @Veskah I think both format and overwriting are covered by default I/O. – Jonathan Frech Mar 2 '19 at 4:31
• @JonathanFrech I'll yield format. And a second reread shows it as the inputs being Source image + Modifier image, whereas I thought it was "do this to both" at first – Veskah Mar 2 '19 at 4:40
• @Veskah I am sorry, but I neither understand what you mean by "I'll yield format." nor "Modifier image". – Jonathan Frech Mar 2 '19 at 4:42
• @JonathanFrech The former is "Yeah, fair enough on format, you are correct", the latter is "Image order matters due to the possibly asymmetric truth tables. So you can say the 1st image is the source and the 2nd image is the modifier which will result in the 3rd output image." – Veskah Mar 2 '19 at 4:50
• @Veskah Edited. – MilkyWay90 Mar 2 '19 at 16:13
• @JonathanFrech Sorry, but what do you mean by "image channels" – MilkyWay90 Mar 2 '19 at 16:15
• @MilkyWay90 with the numbers being RGB values -- I mean the image's three color channels. In what value range do they live? – Jonathan Frech Mar 2 '19 at 22:43
• @JonathanFrech From 0 (0x00) to 255 (0xff) – MilkyWay90 Mar 3 '19 at 2:32

# Venn of $$\n\$$ number of sets

Given positive integer $$\n\$$, output $$\n\$$ 2D bool images with same width and height such that:

1. each image should be 4-connected, i.e. for each two pixels that are true, you can start from one and go up, down, left and right for some times to the other pixel, only passing through true pixels.

2. each image should have no hole, i.e. the component should be 4-connected

3. If we choose itself, its component or neither for each image, their intersection should be non-empty and 4-connected

## Examples (only a finite amount of solution shown, but there are infinitely many more)

Input: 1

Output:

.....
.***.
.**..
..*..

Input: 1

Output:

.....
...*.
.....
.....

Input: 2

Output:

..... .....
.***. ..**.
..... ..**.
..... .....

Input: 2

Output:

..... .....
.**.. ..**.
..**. ..**.
..... .....

Input: 3

Output:

..... ..... .....
.**.. ..**. .....
.**.. ..**. .***.
..... ..... .***.

Input: 4

Output:

...**.. .***... ....... .......
...**.. .***... ..***.. .......
...**.. .***... ..***.. ..****.
....... .***... ....... ..****.
....... ....... ....... ..****.
....... ....... ....... .......

Shortest code in each language win

Reference

• im a little slow... what would be an example of an non-valid output? – don bright Mar 23 '19 at 3:31
• So each image represents one Venn circle? This is a cool challenge. I would (1) say explicitly that each image represents one Venn circle, to make the question easier to understand, and (2) use a different term than "4-connected", which already has a different mathematical meaning. – Lopsy Apr 2 '19 at 20:25
• @Lopsy I mean the 4-c here – l4m2 Apr 4 '19 at 4:04

# Perfectly stable code

You are a.... Let's say prepared, programmer. You are working on the code to end all code, and it must be perfectly stable. No crashes, memory corruptions, mispellings, or anything else must get in your way. Everything else was set, but to your horrer you discovered that you had not accounted for the possiblity that the sun could actually flip a bit in your code! Naturally, you must now account for this.

### The objective: A hello world program that still works if a single char is changed.

Questions:

• Has this been asked?
• What kinds of limits should I impose to make it possible? Allow 10% of chars to be safe, limit the charset to just ASCII, ect.
• Is it possible?
• This challenge is similar. – Esolanging Fruit Mar 7 '19 at 6:15
• Of course it's possible – ASCII-only Mar 7 '19 at 6:16
• In fact, it's solvable rather trivially in certain languages. – Esolanging Fruit Mar 7 '19 at 6:18
• Would it be sufficiently different if I didn't have the requirement that the modification is syntactically valid? – J Atkin Mar 7 '19 at 6:18
• Of course. But that would probably heavily restrict the possible language set, as seen in the other linked challenge – ASCII-only Mar 7 '19 at 6:43
• The tag you're looking for is radiation-hardened, though most challenges deal with deletion rather than modification. I would strongly recommend using bytes rather than characters. In fact, if you want to make it more interesting and closer to the original premise (as well as a little easier), how about using changing bits instead? You should also add a winning criteria (I assume code-golf) and specify the exact output of (Hello, World!) – Jo King Mar 7 '19 at 10:56

# Centurion Counter

The drinking game Centurion is extremely simple - 1 shot of alcohol (usually beer or cider) once a minute for 100 minutes.

Whilst playing the other day a friend commented that we didn't need the tracking app, and that we could have just written the program ourselves. So now it is your turn.

Write a program that once every 60 seconds produces a beep or sound to alert players a minute has passed, and then add one to the counter of how many shots have been had.

The counter starts at 1 (the first shot) and then ends at 100 when the last counter is taken.

• What's the winning criterion here? code-golf? – Ven Mar 14 '19 at 15:37
• Aside from choosing a winning criterion, I think you need to be more explicit about what counts as a sound, or on what hardware this should work on. However, this is extremely similar to this challenge as it is, so you might consider changing up what you want. – FryAmTheEggman Mar 14 '19 at 18:30

There doesn't seem to be a "l337 5P34K" challenge, or I have not yet found one. How about it? Simple string manipulation so it should fall under "C0D3 60LF", right? I.E, Leet speak encoder (challenge one), and leet speak decoder (challenge two).

• You'll need to define the question a lot better than this. i.e. What substitutions define leet speak? If the challenge winning criteria is shortest program size, than code-golf is correct. The string part would be probably be tagged substitution . The closest I could find was the code-challenge Leet to English – Jo King Mar 15 '19 at 10:50
• As you've found a translator, I'll think about an encoder challenge. – Shaun Bebbers Mar 15 '19 at 14:04

# Plot an NACA Airfoil

NACA airfoils are described using a series of digits that represent the miscellaneous properties of the airfoil profile.

The purpose of this challenge is to receive an airfoil number as input, and plot the profile of the airfoil.

## Background information:

4-digit NACA airfoils are generally described by their string NACA ABCC, where A,B are single digit integers, and CC is a 2-digit integer.

• A is the maximum camber as a percentage of the chord length. Eg. A=2 means that the camber is 2% of the chord length.
• B is the location (divided by 10) of maximum camber as a percentage of the chord length. Eg. B=4 means that point of maximum camber is 40% down the length of the chord.
• CC is the profile thickness as a percentage of the chord width. Eg. CC=12 means that the width of the airfoil is 12% of the maximum chord length.

Using the example given above, NACA2412, a suitable profile plot would look something like this:

Note that in the image above, the Red line is the camber line and the purple is representative of the symmetrical airfoil NACA 0012.

Any airfoils with a representative number of NACA 00XX are symmetrical in nature because they possess zero camber.

Possible scoring criteria are and

Any feedback is welcome. I also plan on having more challenges for the 5-digit and 6-digit profiles. Eventually, I will add equations to this post too.

Another way this challenge could be run would be to have the programmer return a series of points around the profile. This could be judged both for accuracy and quantity of points returned. If this approach is used, this would probably be a challenge.

• What are you trying to achieve with popularity-contest? I highly recommend against using it unless you really know what you're doing, most of such challenges are closed as too broad (popularity-contest isn't a broadness waiver). On the other hand, code-golf is the most common winning criterion around here, so I highly recommend it. There are other issues, however, which make the challenge unclear. For example, what constitutes a valid plot image (including how axes, lines, areas and points can be represented)? How would the answer be judged on its accuracy? If the winning... – Erik the Outgolfer Mar 17 '19 at 22:31
• ... criterion isn't just code golf, then I recommend using the code-challenge tag, since code-golf implies a pure golfing competition. – Erik the Outgolfer Mar 17 '19 at 22:32
• There are well-defined equations relating the x and y coordinates, so perhaps submissions could return a set of (x,y) points, and they could be judged by how closely the entire set of points follows the profile lines? – JPeroutek Mar 17 '19 at 22:33
• The spec is completely opaque to me. It should be written without assuming any aerofoil-specific knowledge, not as a refresher for someone who already knew it but may have forgotten. – Peter Taylor Mar 19 '19 at 8:52
• I think your idea is good, but the details are pretty vague. – dfeuer Mar 19 '19 at 22:23

# Optimize the JSON (WIP)

Consider function f which takes two objects data and default, and merge anything from default into data if data contains no such element. Take the two objects(if the one in your language can handle the required elements) or JSON as input, output a shortest JSON that, when given as data, output the same object as the original data do, as long as default doesn't change.

• If posted as it is now, I would flag it: closed as unclear what you're asking – Beefster Mar 19 '19 at 17:15
• @Beefster That's what WIP means – l4m2 Mar 20 '19 at 9:34
• I really have no idea what this challenge is. The title suggests making a representation smaller while the text seems to indicate some sort of merging process that really needs to be fleshed out. – Beefster Mar 20 '19 at 16:23
• add some examples! – vityavv Mar 20 '19 at 16:53
• @zevee Actually I don't know what I want on some situations, so this will be here for long time – l4m2 Mar 20 '19 at 22:17

# Draw these shapes

Given: a width, a height, and a set of sets of points. Output: An image where each set of points is connected and colored in (like a shape). Each shape must be a different color from all of the other shapes, but the difference doesn't matter. The shapes must be in order; whether you start at the end or the beginning of the set doesn't matter, though.

## Examples

//the code here has nothing to do with the actual challenge and just shows examples

document.getElementById("one").getContext("2d").fillRect(0, 0, 300, 300)
const ctx = document.getElementById("two").getContext("2d")
ctx.fillStyle = "black"
ctx.beginPath();ctx.moveTo(0,0);ctx.lineTo(0,300);ctx.lineTo(300,0);ctx.closePath();ctx.fill()
ctx.fillStyle = "lime"
ctx.beginPath();ctx.moveTo(200,0);ctx.lineTo(600,0);ctx.lineTo(300,300);ctx.closePath();ctx.fill()
canvas {border: 1px dotted black}
<pre>Width: 500, Height: 500, Set: [[[0, 0], [0, 300], [300, 300], [300, 0]]]</pre>
<canvas id="one" width="500" height="500"></canvas>

<pre>Width: 600, Height: 300, Set:
[
[[0,0], [0,300], [300,0]],
[[200,0], [600,0], [300,300]]
]</pre>
<canvas id="two" width="600" height="300"></canvas>

Scoring is .

• is there any rules about how long I have to wait before posting to the main site? – vityavv Mar 20 '19 at 23:52
• It's usually best to wait at least 72 hours before going from the Sandbox to main. As for the actual challenge: do the colors need to be visually difference, or is changing a color from #FFFFFF to #FFFFFE enough difference (I assume the second, but if not, please explain how much different the colors have to be)? Also, is the input order of the points for the shapes important, where the last is always in front of the first? Or are we also allowed to have the green triangle behind the black one in your second example? – Kevin Cruijssen Mar 21 '19 at 12:01
• @KevinCruijssen any difference is enough. Order can be either descending or ascending, but must go sequentially. I'll add those to the question – vityavv Mar 21 '19 at 15:12
• You may want to add something about jpegs and other lossy image formats, and whether they are allowed. Also I think you should explain "in order" a bit more: do you mean later shapes will be drawn over earlier shapes (or vice versa)? – FryAmTheEggman Mar 22 '19 at 17:25
• @FryAmTheEggman. In order means later shapes will be drawn over earlier shapes or vice versa, that's why I said "whether you start at the beginning or the end of the set doesn't matter though." Also, codegolf.meta.stackexchange.com/questions/9093/… says stuff about lossy formats (Programs may output via a common raster graphics image format) – vityavv Mar 23 '19 at 21:53
• What are the width and height? – Artemis still doesn't trust SE Mar 26 '19 at 23:18
• the width and height of the outputted image. BTW, I've posted this: codegolf.stackexchange.com/questions/182104/draw-these-shapes (only need one more re-open vote) – vityavv Mar 26 '19 at 23:34

# Patch one line

First question I've written, feedback is highly appreciated. If you can think of a clever title, I'll take that too.

## Challenge

In an effort to prove to your employer that Git commit count is a worthless metric, you've decided to break up all your changes from now on line by line.

Golf a program which can edit a patch file to remove all changed lines except for one.

## Patch file format

The patch file will be given by Git in the unified diff format, although git will append multiple file changes together:

diff --git a/afile b/afile
index bf70e9e..d2df230 100644
--- a/afile
+++ b/afile
@@ -1,8 +1,9 @@
-Lorem ipsum dolor sit amet,
+Lorem IPSUM dolor sit amet,
+++ (good luck parsing this line)
Duis est elit, imperdiet ac dolor quis,
volutpat commodo nunc.
diff --git a/bfile b/bfile
index c484b2b..db4afe5 100644
--- a/bfile
+++ b/bfile
@@ -1,11 +1,7 @@
-#
-# /etc/bash.bashrc
-#
-
# If not running interactively, don't do anything
[[ $- != *i* ]] && return [[$DISPLAY ]] && shopt -s checkwinsize

Here are two accepted outputs for the above patch file:

diff --git a/afile b/afile
index bf70e9e..d2df230 100644
--- a/afile
+++ b/afile
@@ -1,8 +1,9 @@
Lorem ipsum dolor sit amet,
+++ (good luck parsing this line)
Duis est elit, imperdiet ac dolor quis,
volutpat commodo nunc.
diff --git a/afile b/afile
index bf70e9e..d2df230 100644
--- a/afile
+++ b/afile
@@ -1,8 +1,9 @@
-Lorem ipsum dolor sit amet,
Duis est elit, imperdiet ac dolor quis,
volutpat commodo nunc.
diff --git a/bfile b/bfile
index c484b2b..db4afe5 100644
--- a/bfile
+++ b/bfile
@@ -1,11 +1,7 @@
#
# /etc/bash.bashrc
#

# If not running interactively, don't do anything
[[ $- != *i* ]] && return [[$DISPLAY ]] && shopt -s checkwinsize

### Assumptions

Any other corner cases I'm missing?

You do not need to handle the following cases:

• A file is deleted, renamed, or added
• A file has changed its mode

You do need to handle the following cases:

• An added line starts with ++
• A removed line starts with --
• There are changes in multiple files (although you can remove one of the diffs and git will still patch okay)

## Input/Output

Is this much explanation necessary?

I added the stdin/stdout method since I imagine it's more conducive to golfing in some langs... Should I do any kind of bonus/penalty?

Your program may either take the name of the patch file as its first parameter and do an in-place edit (this will let GIT_EDITOR=/path/to/your/program git add -e apply the patch), or read from stdin and write to stdout such that the following will correctly apply the patch:

$cat > oneline.sh << EOF #!/bin/sh mv "$1" "$1.old" /path/to/your/program < "$1.old" > "$1" EOF$ chmod +x oneline.sh; GIT_EDITOR=./oneline.sh git add -e

Refer to the EDITING PATCHES section of man git-add for some helpful info on editing the patch file.