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

# Simple ASCII Representation of a Screw Head

Inputs are a string and a number.

If the string is "Slot", the number will be 0, 60, 90, or 120. If the number is 0, output --; if 60, output /; if 90, output |, if 120, output \.

If the string is "Phillips", the number will be 0, 45, 90, or 135. If it's 0 or 90, output +; otherwise output x.

If the string is "Torx", the number will be 0, 60, or 120. Regardless of the value, output *.

If the string is "Spanner", the number will be 0 or 90. Output .. for 0 and : for 90.

Behavior for all other inputs is undefined.

[Is this challenge too simple? If so, could more test cases help?]

• I think adding test cases that require modular division (so you could say Phillips 72270) and error handling (GenericScrewXyz 43 would throw an error). – wizzwizz4 Dec 2 '15 at 18:31

# Display a rational tangle [WIP]

In a quest to classify mathematical knots, J. H. Conway discovered that certain simpler knotlike structures called rational tangles can be uniquely represented by rational numbers.

A tangle is an arrangement of two strands of rope such that each of the four ends lies at one corner of a rectangle. The four exceptional tangles are 0, 1, -1, and a special case usually referred to as 0/0 or ∞. A rational tangle is a tangle that can be obtained from the exceptional tangles by the following operations.

An example of a rational tangle, and the tangles 0/0, 0, 1, and -1 respectively.

The rational tangle operations

Because every rational number can be obtained by addition, negation, and reciprocal, there exists some rational tangle corresponding to every rational number.

If tangle a and b have rational number values x and y respectively, then the operations in the diagram result in the following values.

Tangle |  Value
-a          -x
1/a         1/x
a + b      x + y
a b       -x + y
a , b     -x + -y


# Challenge

Using the below representations of the four exceptional rational tangles, display an ASCII art rational tangle corresponding to a given rational number.

### Exceptional rational tangles

\_/   \ /
_    | |
/ \   / \


3x3 ASCII art representing the rational tangles 1/0 and 0

\ /   \ /
\     /
/ \   / \


The rational tangles 1 and -1, illustrating how to display crossings

### Displaying more complex rational tangles

Adding and rotating the above 3x3 blocks and rotation can yield any rational tangle.

• To flip a rational tangle over the line x=y, switch all instances of 1 and -1, switch all instances of 0/0 and 0, and replace all extenders (below) as appropriate.

• To rotate a rational tangle by 90 degrees in either direction, rotate the ASCII art by 90 degrees in that direction, switch all \ and /, switch all instances of 0/0 and 0, and replace all extenders (below) as appropriate.

• To add two rational tangles, juxtapose them in the appropriate direction and orientation, adding extenders if dimensions do not match. Then surround the result with the following.

Pattern to surround the sum of two tangles in:

\ ... /

⋮      ⋮

/ ... \


Extenders:

 \        /
|      |
...    ...
|      |
\    /

\_..._
\

_..._/
/


### Examples

One possible representation of the tangle obtained through the equation [...]. This tangle is congruent to [...] because =.

 \       /
\_   _/
\ /
/
__/ \_
/      \
\      /
\ /\ /
\  \
/ \/ \
/      \
/        \


### Input

A rational number. If you instead take input as an ordered pair (numerator,denominator) of integers, you will have denominator >= 0. (Denominator 0 is necessary to represent 0/0.)

### Output

An ASCII-art representation of the rational tangle corresponding to said number, where a crossing is displayed as one of the above. Whitespace can occur anywhere. Output can contain unnecessary copies of 0, or have other variations as long as the rational tangle is obtained by operations whose corresponding arithmetic operations result in the input.

### Further sources

A further explanation of tangles and rational tangles: (https://rationaltangle.wordpress.com/what-are-tanglesrational-tangles/)

TODO: Reciprocal operation, better example, reference implementation

Should continued fraction representations be acceptable?

Since this is probably a difficult challenge and answers to such are undervoted, I'm prepared to award a bounty to the shortest answer and any improvement thereon.

This is getting more unwieldy. I'm thinking of simplifying into a challenge to simply add two rational tangles.

• The introduction seems to be written as a reminder to someone who already knows the topic and needs a refresher. To someone who's never heard of rational tangles before, it throws up a lot more questions than answers. What's 0/0 (other than NaN)? What's ramification? What (other than a+b, which is fairly straightforward) is the diagram supposed to show? The intro says that the ends of the rope must be in the corners of a square: should that say rectangle? In the ASCII art, how do extenders cross? – Peter Taylor Nov 18 '18 at 21:28
• 1. Which part of the diagram corresponds to reciprocal? Does the left-hand part somehow show both negation and reciprocal at the same time? 2. Having looked at your additional reading link, the challenge turns out to be much simpler than the question made it seem. The paragraph starting "The two simplest tangles" and the subsequent one seem to be all that's needed. Perhaps you could use a simple challenge as an introduction and then have a follow-up which asks for an equality test? – Peter Taylor Nov 18 '18 at 22:41
• @PeterTaylor 1. Reciprocal is flipping over some axis, I forget which one. 2. Will do when I have time. I probably won't end up posting this for another month. – lirtosiast Nov 18 '18 at 22:52

# Octonion multiplication code-golfmathcomplex-numbers

## Background

Octonion is a further extension to the quaternion number system. An octonion can be written as

$$x = x_0 e_0 + x_1 e_1 + x_2 e_2 + x_3 e_3 + x_4 e_4 + x_5 e_5 + x_6 e_6 + x_7 e_7$$

where $$\ x_i \$$ are real numbers and $$\ e_i \$$ are the eight unit octonions.

Octonion multiplication has the following properties:

• It is not commutative, i.e. $$\ xy \ne yx \$$.
• It is not associative, i.e. $$\ x(yz) \ne (xy)z \$$.
• But, luckily, multiplication is distributive over addition, i.e. $$\ x(y+z) = xy + xz \$$ and $$\ (x+y)z = xz + yz\$$.

The multiplication rule for unit octonions is presented below:

(will add a table from Wikipedia)

The unit octonions have several properties:

• $$\ e_0 \$$ behaves like a real number 1.
• $$\ e_i^2 = -1 \$$ and $$\ e_i e_j = -e_j e_i \$$ for $$\ 1 \le i,j \le 7, i \ne j \$$.

Multiply two octonion numbers.

## Input & output

You can accept and output an octonion as any kind of consistent structure consisting of eight real numbers (four complex numbers or two quaternions or a mixture of types is also fine).

Coming soon.

## Scoring & winning criterion

Standard rules apply. The shortest program or function in bytes for each language wins.

• $1e_0+2e_1+3e_2+4e_3+5e_4+6e_5+7e_6+8e_7$ is written in NARS2000 as 1i2j3k4l5ij6jk7kl8. ;-) – Erik the Outgolfer Nov 19 '18 at 17:11
• Somehow, I think NARS APL will win this one… – Adám Nov 19 '18 at 18:39

# Tetris battle

I guess you know what Tetris is, but if you don't I'll try to explain:

So there is a 2 dimensional board, often with size 10x20. On the top of the board, in the middle, there is a random tetrominoe (also rotated randomly), a figure made of 4 squares. There are 7 shapes:

L    J   S    Z    T   O   I

#    #   ##  ##   ###  ##  #
#    #  ##    ##   #   ##  #
##  ##                     #
#


Every second, the tetrominoe (later called "block") will move 1 cell to the bottom until there is no space left. Player can control it - Move it to left, right, rotate it by 90 degrees (left or right) or speed up its fall. When it can't fall down further, a new block is created and you take the control over it, losing possibility to move the previous block.

The target is to get as much points as possible. Player can get them, by filling a line (which is then removed), for example:

        !
!
!
****####!$<- user scores a point, the line is now removed &&&&$


different character is a different block

Player can lose if there is no place for a new block to spawn.

You can play Tetris online here

## The battle

In this challenge, you will have to create a bot to play Tetris. Unlike a normal playthrough, there will be two players playing on a single board.

Let's call the bots A and B.

### Block spawning

Every block will start on the left, or right side, depending which bot's it is (left - A, right - B). There will be a 2 block margin, so the block will have some space to rotate. Block will always spawn with left/right align, not centered.

If a block can't fit, it will try to rotate, so it can be placed. If all 4 directions fail, you die.

Example for 10 width board:

--A----B--


### Random size board

Width: random even number between 8 and 16.

Height: random number between 15 and 25.

It's to make it a bit harder. Try to plan your strategy so it fits all the heights!

## Scoring

You gain 1 point per destroyed block. Some bonus rules apply:

### Enemy's block isn't my block

You can't use blocks placed by your enemy to gain score. After adding the last block to a line, you gain as much score as much sub-blocks you placed in it. Enemy sub-blocks don't count. Example:

Player A filled the line.
AAAABBBAAB
Player A gets 6 points.
Player B doesn't earn any.


### Combos

If you do a move that removes more than just 1 line, you gain x times more score. Of course, x is the amount of lines.

Player A filled the line
--ABBB
AAABBBABBB <
BBBBBBABBB <
BBBBAAABBB <
B AA ABBB
Player A removed 3 lines.
Player A removed 12 (4+5+3) blocks he owns.
Player A scores 36 points.


### Death & Game Over

When a new fails to spawn, it tries to rotate 90, 180, 270 or 360 degrees. If it still can't spawn. You lose. Note it won't try to change it's position, so be careful and try to not put any blocks in the spawn area.

When you die, you can't place any more blocks.

• In case your enemy has more points than you, you lose.
• Otherwise, the game doesn't end yet – the enemy will get double points for the next 10 blocks. The game will end when the bonus ends, when he beats your score or when he dies.

When the game is over, the bot with more points win.

The game will also end automatically after 300 actions. See API > Actions section for more information.

## Controller

Work in progress. https://github.com/Soaku/Tetris-KOTH

## API

Can't really tell you how it's gonna look like without a controller, right?

However, there is a project of how it's gonna look like:

### Actions

Every game consists of actions. Your bot function will be executed at the beginning of each action. At the end of each, active tetrominoes will move 1 cell to the bottom.

The controller will wait a configurable amount of time between actions unless the preview is disabled.

Your function should return an integer in at most 0.1 seconds, otherwise your action is terminated and ignored. If it will cross the limit repeatedly, I might remove it.

## Rules

• Default loopholes are forbidden.
• Aggressive bots are allowed but discouraged.
• You cannot use any external libraries. The controller uses jQuery, but you aren't allowed to use it.
• Don't try to access the document – Don't write nor read data.
• Don't write your bot to beat specific enemies by countering their strategies.
• Enemy spawn works like an occupied block. You cannot place anything here.

## Main scoring

Every bot will play with every other bot.

Scoring works this way:

• Victory: 2 points
• Tie: 1 point
• Lose: 0 points
• I feel like the last part (bonus round) there probably isn't such a good idea. especially since bots are mostly programmed to play against one enemy, so it means a regular bot needs to implement special cases for one round, which really doesn't add much. – Destructible Lemon Nov 5 '17 at 22:25
• If you do decide to make a massively multiplayer one, it's sort of unfair to bots that will perform better at the side that end up in the middle or vice versa, so making it a cylinder (the rows wrap around into themselves) would help – Destructible Lemon Nov 7 '17 at 8:04
• Fine, I removed it from the answer itself, but that doesn't mean I can't do it for fun ( ͡° ͜ʖ ͡°) – RedClover Nov 8 '17 at 19:44
• Just wanted to point out that your J, L, and T tetrominoes actually have 5 squares each; I'm fairly sure that wasn't intentional. – ETHproductions Nov 8 '17 at 23:48
• The question describes things that happen when "enemy is dead", but does not describe what causes that or what happens when "you are dead". – Kamil Drakari Nov 9 '17 at 16:12
• @KamilDrakari [On spawn] If a block can't fit, it will try to rotate, so it can be placed. If all 4 directions fail, you die. – RedClover Nov 9 '17 at 16:13
• That is an awfully small section for something quite important. I would add a distinct section on Death, clarifying "when dead, you can no longer place blocks" and some edge cases for the 10 bonus pieces, such as what happens if a player dies during their bonus pieces and if they are required to continue placing the full 10 blocks or they can stop once they have a higher score. – Kamil Drakari Nov 9 '17 at 16:50
• @KamilDrakari Oh, you're right. I'll try to add something about that, when I have some time. – RedClover Nov 9 '17 at 16:51
• @ETHproductions I also noticed that J and L are pentominoes. T is actually a hexomino. But... – Heimdall Nov 11 '17 at 9:59
• @ETHproductions thanks for pointing this out. Fixed – RedClover Nov 11 '17 at 10:00

# Make numbers inflate to full width! code-golfstring

Related: Full Width Text

That is a challenge that changes ALL characters into full width -- BY ADDING A SPACE AFTER EACH CHARACTER. However, in this challenge only numbers are transformed, and are transform to the REAL FULL WIDTH FORM

.

This is a short and simple challenge, so I will keep the description short.

## Challenge

Write a program / function that accepts an ASCII string as input and outputs a UTF string with each number 0123456789 converted to its corresponding full width form ０１２３４５６７８９. The range of these full width numbers is U+FF10 - U+FF19.

You may output using the following format (As an example This is 1 apple is used):

• A UTF-8 string (showing exactly This is １ apple in STDOUT)
• The same string as above but displayed in a non-UTF-8 encoding (eg. showing This is ï¼‘ apple in Windows-1252 codepage). In this case you must state the codepage of the output
• A single list of UTF-8 bytes as integers that represents the transformed string (showing ord("T"),...,ord(" "),239,188,145,ord(" "),...,ord("e") with arbitrary delimiter)

You cannot mix integer output and character output, that is, you cannot literally change This is 1 apple to This is [239,188,145] apple. You cannot output a nested list if a list is outputted either.

## Sample I/O

• Sample 1:

Input:  0123456789
Output: (Format 1) ０１２３４５６７８９
(Format 2) ∩╝É∩╝æ∩╝Æ∩╝ô∩╝ö∩╝ò∩╝û∩╝ù∩╝ÿ∩╝Ö [CP437]
(Format 3) 239,188,144,239,188,145,239,188,146,239,188,147,239,188,148,239,188,149,239,188,150,239,188,151,239,188,152,239,188,153

• Sample 2:

Input:  This is 1 apple
Output: (Format 1) This is １ apple
(Format 2) This is ï¼‘ apple [Windows-1252]
(Format 3) 0x54 0x68 0x69 0x73 0x20 0x69 0x73 0x20 0xef 0xbc 0x91 0x20 0x61 0x70 0x70 0x6c 0x65

## Footnote

This is a , so shortest answer for each language wins. Standard loopholes are forbidden by default.

P.S. I would like to see both practical and esoteric language submissions. Specifically the last two output formats are especially allowed for esoteric languages.

# Help Runbee manage the pollen! [better title needed?]

The  arsonist  friendly bee, Runbee, just finished picking up the pollen from the flower garden and now she wants to store it safely in her hive. Each pollen type is labeled with a digit (from 1 to 9). Runbee's "collection" is stored in a row of adjacent honeycomb cells, containing one grain each. For instance, this row could look like this:

1 3 2 2 4 4 4 5 3 3 3 7 8 9 9 5


But hmm, Runbee doesn't like this order... Because she's tired after flying all day, she can now only move a run of identical adjacent pollen grains to another position in the row to make it seem more organised. Her goal is to have as many identical pollen types one after another after the reordering.

Given a sequence S of digits ranging from 1 to 9, one shall:

• Split S into (the longest possible) runs of consecutive adjacent elements. Then, one of the chunks should be moved to another position in S.
• The resulting sequence S' should be chopped again into (the longest possible) runs of consecutive adjacent elements. Your goal is to search for the sequence S' which contains the most equal consecutive elements.
• You can either output all such sequences S' (deduplicated or not) or just one of them.

For the example above, the possible ways to generate optimal orderings are (where (...) represent the point of removal and [...] the point of addition):

1 (3) 2 2 4 4 4 5 [3] 3 3 3 7 8 9 9 5     | 1 2 2 4 4 4 5 3 3 3 3 7 8 9 9 5
1 (3) 2 2 4 4 4 5 3 3 3 [3] 7 8 9 9 5     | 1 2 2 4 4 4 5 3 3 3 3 7 8 9 9 5
1 3 [3 3 3] 2 2 4 4 4 5 (3 3 3) 7 8 9 9 5 | 1 3 3 3 3 2 2 4 4 4 5 7 8 9 9 5
1 [3 3 3] 3 2 2 4 4 4 5 (3 3 3) 7 8 9 9 5 | 1 3 3 3 3 2 2 4 4 4 5 7 8 9 9 5


### Rules

... To be written ..

### Test cases

• Suggested testcase: 1 3 2 2 2 2 3 3 1 – Emigna Nov 23 '18 at 7:59
• Note. Because TSP (decision version) is NP and maximum independent set is NP-hard, it's possible to have polynomial-time complexity; however given how unrelated those two problems appear to be, the actual transformation would be nontrivial and may be interesting to optimize. – user202729 Nov 30 '18 at 16:45

# Is the array sorted?

Inspired in part by Creative ways to determine of an array is sorted.

Given an array of integers, find out if the array is sorted. This challenge is as simple as it sounds. I'm surprised that I couldn't find a question like this on PPCG. I'm aware that a lot of golfing languages will have short solutions, but perhaps this question could allow you to showcase a language that's more esoteric than it is practical?

## Input

An array of integers, or a sequence of integers if your language doesn't support arrays.

## Output

Truthy if the array is sorted, falsey otherwise

## Examples

[1, 2, 3] => true
[3, 2, 1] => false
[1, 1, 1] => true
[] => true
[1] => true
[-3, -2, -1] => true
[-1, -2, -3] => false
[1, 2, 1] => false
[1, 1, 0] => false


Since this is , get ready to trim off some bytes! Happy golfing!

## For the sandbox

I have searched thoroughly for a question like this, but I haven't been able to find this question posted previously. If it exists, or if it is too similar to another question, please link the question or comment why this question should/shouldn't be posted.

• People don't post trivial challenges because it's not interesting to do in most languages. However having trivial challenges is not a too bad thing for esoteric languages like Brain-Flak. Dodos will still have great difficulty handling negative numbers. – user202729 Dec 6 '18 at 16:27
• Good point. Since this challenge will mainly be interesting in esoteric languages, I suggest restricting the input to positive integers. It won't make the challenge any different for languages with signed integer types, while allowing other languages to participate without implementing a new number type. – Dennis Dec 7 '18 at 13:46

You are filling a survey. You don't like filling such thing, so you decide to automatically fill some random thing.

However, there may be some duplicated question, and some may be inverted. To simplify the question, we define:

1. Adding or removing word "not" or "no" inverts the sentence;
2. Adding or removing "un" at the beginning of a word inverts the sentence;
3. Adding or removing "n't" at the end of a word inverts the sentence;
4. Adding or removing word "any", "a" or "an" keeps (doesn't invert) the sentence;

Invertion can go through sentences even if they are not asked. E.g. "Do you own a car?" is twice inverted to "Don't you own no car?", so they should have same answer, no matter what sentences left are mentioned.

Input: A list of string, each of which is a sentence.

Output: A list of 2-possible-value, where inverted sentences are answered different and same sentences are answered same.

Sample Input:

Are you rich?
Are you unrich?
Are you poor?
Are you rich?
Are you not rich?


Possible sample outputs (assuming 0 and 1 as possible outputs)

1,0,0,1,0
1,0,1,1,0
0,1,0,0,1
0,1,1,0,1


. Decided to not have to try to have more creative solution

• I would rather have this challenge something closer to just "identify duplicate questions" rather than "create a possible set of answers such that you answer duplicate questions with appropriate inversion". Something like "Given two sentences, output one of 3 distinct values to indicate whether they are "duplicate", "inverted", or "unrelated"". If you insist on keeping the output as possible answers, then your "output" line needs to say so rather than just "a list" – Kamil Drakari Dec 5 '18 at 17:26
• @KamilDrakari If no random requirement, false relation or something else may exist. Considered – l4m2 Dec 6 '18 at 3:01
• @KamilDrakari That is a good option, because it is a large part of the challenge, and the other part is likely to be implemented using brute force ⇒ very slow, not testable. – user202729 Dec 6 '18 at 16:19

# Separate the syllables - in Finnish

Given a Finnish word as a string, separate each syllable.

## Wait, what?

In Finnish, syllables are very important for many different things in the grammar - often, the first place a foreigner starts with the language is with the syllable structure. Your job, as a prospective learner, is to decompose the given word into its syllables. To do this, your program or function must return a string in which the syllables have been separated by a single | or -.

## But how?

Given any word, you can split the syllables apart by following five simple rules. In the below mapping, V indicates a vowel (aeiouyäö), a diphthong or a long vowel (see below) and C indicates a consonant (bcdfghjklmnpqrstvwxz). '-' indicates where the word should be split. Patterns are "greedy", so the longest matching pattern is the one that should be applied.

VV -> V-V

VC -> VC

VCV -> V-CV

VCCV -> VC-CV

VCCCV -> VCC-CV

## What the &@?! are diphtongs?

Because Finnish is a complex language, we can't just let foreigners get off that easy with learning the basics! So, we came up with diphtongs - pairs of vowels that are considered a single vowel when determining syllables. The list of the ones important to this challenge is as follows (in an arbitrary order):

ai, ei, oi, ui, yi, äi, öi, ey, iy, äy, öy, au, eu, ou, iu, ie, uo, yö

Furthermore, we have long vowels - these also count as a single vowel, and are simply the vowel repeated twice:

aa, ee, ii, oo, uu, yy, ää, öö

## What else?

You should note that:

• Default loopholes are forbidden.
• Default I/O is allowed.
• You may take input and produce output in any string encoding that contains at least the following characters: abcdefghijklmnopqrstuvwxyzåäö-| and/or their upper-case equivalents.
• The encoding must be the same for input and for output.
• This is . Shortest answer wins.

## Give me the solutions!

Examples are given as input -> output with syllable boundaries indicated by a -.

perkele -> per-ke-le
sauna -> sau-na
koskenkorva -> kos-ken-kor-va
nopea -> no-pe-a
maa -> maa
suomenkieli -> suo-men-kie-li
esimerkki -> e-si-merk-ki
itsenäisyyspäivä -> it-se-näi-syys-päi-vä
koodigolffi -> koo-di-golf-fi
toritapaaminen -> to-ri-ta-paa-mi-nen


## Finally...

Happy golfing!

• I don't understand how to use the patterns. What is the point of the VC pattern if it does not have any split? – feersum Dec 10 '18 at 14:00
• @feersum It's just there to indicate that any trailing consonants are considered part of the same syllable as the preceding vowel (i.e. the last example). – user77406 Dec 10 '18 at 14:06

# Validate a simple bell-ringing method

A simple bell-ringing method on n bells has the following characteristics.

1. Each row exchanges at least one pair of adjacent bells. Any given bell can only take part in one exchange per row.
2. The notation for a row lists those bells that are not exchanged. Each row is separated with a .. However, rows that exchange all bells are notated with an X and do not use . separators, so that .16..16. would actually be notated X16X16X.
3. The first n-1 rows always exchange bell 1 with the next bell so that it becomes last.
4. The nth row, also known has the half lead, does not exchange bell 1.
5. The next n-1 rows are the same as the first n-1 rows but in reverse order. This brings bell 1 back to its original position.
6. The 2nth row, also known as the lead end, also does not exchange bell 1.
7. Up to three different lead ends may be used, being named "Plain", "Bob" and "Single".
8. After the lead end, the 2n-1 rows are rung again, possibly with a different lead end, and this repeats according to a predetermined pattern known as a touch.
9. The method starts and finishes with the bells in ascending order.

The following parts are intended to be submitted as separate questions.

## Part 1

Given any number of rows in bell-ringing notation, return a truthy or falsy value depending on whether they represent a valid permutation.

## Part 2

Given any number of rows in bell-ringing notation, convert them to permutations and output them in the most convenient format for input into subsequent parts.

## Part 3

Given a list of permutations corresponding to the first n rows of a method, append the first n-1 rows in reverse order, and then output the result of combining the permutations.

## Part 4

Given the permutation from part 3, and up to three different lead end permutations as output by part 2, and a string representing which the order in which the lead ends are to be used, calculate the permutations before and after each lead end, ensuring that they are all different, and that the last permutation is that the identity permutation.

Example:

Main rows: 5.1.5.1.5
Bob: 145
Touch: PBPPBPBPPB


5.1.5.1.5 means that the permutations are (12)(34) and (23)(45) repeated, so the permutation before the first lead end in this case turns out to be just (23)(45) again. The plain lead is (34) and the bob is (23). The relevant permutations for the touch are as follows:

(23)(45)
(2453)
(25)
(235)
(245)
(2345)
(35)
(345)
(243)
(34)
(2354)
(2453)
(25)(34)
(2435)
(2534)
(253)
(354)
(45)
(23)


then finishing with the identity permutation as desired.

• I have to say, I am entirely confused by this and haven't the slightest idea what any of it means to the point that I can barely even identify what things confuse me. However, I can at least ask one thing: Rule 3 states "exchange bell 1 with the next bell so that it becomes last". How does "exchange bell 1 with the next bell" result in "it becomes last"? If I have 3 bells I would expect the result to be 213. Are you using a different definition of "exchange" than me? – Kamil Drakari Dec 11 '18 at 21:09
• @KamilDrakari There are n-1 rows, which is exactly the minimum number needed to get bell 1 into last place, as long as each row moves bell 1 a further step each time. – Neil Dec 11 '18 at 22:22
• In point 2 should .16..16. say .16.16.? – Peter Taylor Dec 14 '18 at 12:08
• @PeterTaylor No, .16..16. is a list of five strings, three of which are empty. – Neil Dec 14 '18 at 13:23

# Prime Steganography

Alice and Bob have devised a steganography encryption method where they encode the letters of their message (the "secret message") into the letters in the prime positions of the larger message (the "carrier message"). Your job is to create a program which takes a secret message as input and outputs a carrier message that hides the secret message in the letters in the prime positions.

## Requirements

• Only letter characters in the carrier message count toward positions.
• The secret message is not case sensitive and non-letters do not need to be encoded in any way.
• The carrier message must contain only words that can be found in this list of English words. The carrier message does not need to make sense.
• The carrier message can contain punctuation (any of .,?!"':;-), whitespace, and letter characters only.
• The carrier message cannot hide a message that is longer than the secret message. If it ends on a prime after the last one needed, it is invalid. For instance, if the carrier message is 38 letters long and the secret message is only 11 letters long, the carrier would encode an extra letter and therefore is invalid. (Sandbox: help me phrase this better)

## Examples

Input: 'Hello world'

Possible Output:

Ah! Eels live! Oh wall! Oars will board.

Lining up all the letters, you get these positions

 A  h  E  e  l  s  l  i  v  e  O  h  w  a  l  l  O  a  r  s  w  i  l  l  b  o  a  r  d
1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29


All the letters in the prime positions would be extracted. h at 2, E at 3, l at 5, l at 7, O at 11, w at 13, O at 17, r at 19, l at 23, and d at 29. Thus the full message is hEllOwOrld, but case doesn't matter.

## Rules

• Standard rules and loopholes apply.
• You can read in the word list using any method you would like, or not at all. Other word lists may be used and will not count toward byte count, but every word in your output must appear somewhere in the previously mentioned word list.
• You may assume that the secret message only includes letters, whitespace, and punctuation.
• Your program does not need to be deterministic, but does need to always output a valid carrier message which correctly encodes the secret message.
• You may assume that the secret message is possible to encode with English words from the list. (Even though it may not be for one reason or another)

### Sandbox note

I'm thinking this might make for an interesting popularity contest. The objective criteria is validity of the carrier message. The subjective criteria is how interesting/entertaining/convincing the messages that it outputs are.

• Considering that only the letters of the secret message are encoded anyway, I think it would make more sense to only provide the letters of a secret message without punctuation. – Kamil Drakari Dec 13 '18 at 3:33
• I'd reccomend giving the list of words as input rather than a defined word list. This makes it much easier to test – Jo King Dec 13 '18 at 13:32
• @JoKing That would be covered by "You can read in the word list using any method you would like, or not at all. Other word lists may be used and will not count toward byte count, but every word in your output must appear somewhere in the previously mentioned word list." It's a pretty massive list of words, so any subset of it will do for testing. – Beefster Dec 13 '18 at 22:25

# Stego-nography: Hide A Stegosaurus with Steganography!

This doesn't work as a cops and robbers challenge. Leaving for possible inspiration.

Making something that converts an image with a live dinosaur into one with a dead dinosaur would be a clone of Hiding information in Cats.

# Cops

Devise a method for hiding this ASCII stegosaurus in an image.

                         .       .
/ .   .' "
.---.  <    > <    >  .---.
|    \  \ - ~ ~ - /  /    |
_____          ..-~             ~-..-~
|     |   \~~~\.'                    ./~~~/
---------   \__/                        \__/
.'  O    \     /               /       \  "
(_____,    ._.'               |         }  \/~~~/
----.          /       }     |        /    \__/
-.      |       /      |       /      . ,~~|
~-.__|      /_ - ~ ^|      /- _      ..-'
|     /        |     /     ~-.     -. _  _  _
|_____|        |_____|         ~ - . _ _ _ _ _>


Source: custom 'cow' for cowsay

Create an encoder and a decoder. Post the decoder and two versions of three different images, each pair with and without the encoded stegosaurus. Include hashes for each of the six images.

## Rules and Scoring

• The decoder must be able to decode any arbitrary ASCII text of at least the same size as the stegosaurus (either 677 characters or 14x63 characters if you assume the text is right-padded. Be consistent).
• Only the part of the encoded message that actually includes the stegosaurus matters; extra bytes in the message can be ignored by the user or decoder, but must be either before/after the 677 characters or outside the 14x63 bounding rectangle, depending on how you encode it. (Sandbox: this phrasing is awkward)
• In short, it must be possible for the robbers to kill your dinosaur (link to robber thread goes here) by replacing your stegosaurus with a dead one.
• You may not use asymmetric encryption in your solution. (For example, encrypting the stegosaurus with your private key before hiding it and then putting the public key in the decoder)
• You can use any lossless image format of your choice.
• You do not need to post the source code of your decoder. Precompiled Windows or Linux binaries are allowed, but must be packaged with all of their dependencies and be able to be run without any installation. Obfuscation and minification are allowed for interpreted languages and likewise should prepackage all third-party dependencies.
• You may not host your decoder on a webservice. The reason why is that it enables you to use symmetric encryption with no way to derive the key.
• As an objective criteria for the encoded images to be not easily distinguishable, the maximum absolute pixel difference between the images should be less than 4/255 for each color component in the entire image.

If at least one of your dinosaurs survives after one week, your dinosaurs are safe and you earn 10 points (after which point you can explain your algorithm). If your dinosaurs are all killed within a week, you score 1 point for each 24 hour period they survived.

The cop with the most points wins.

# Robbers

You're a dinosaur hunter. The cops have hidden stegosauruses in three images. It's your job to find the stegos and kill them. You are to change the message hidden in each image from the original stegosaurus to this dead one:

                         .       .
/ .   .' "
.---.  <    > <    >  .---.
|    \  \ - ~ ~ - /  /    |
..-~             ~-..-~
\~~~\.'                    ./~~~/
\__/                        \__/
/               /       \  "
_____     .'               |         }  \/~~~/
|     |  .'   /       }     |        /    \__/
--------''    |       /      |       /      . ,~~|
.'  X        __|      /_ - ~ ^|      /- _      ..-'
(_____     _-~  |     /        |     /     ~-.     -. _  _  _
__U___--~     |_____|        |_____|         ~ - . _ _ _ _ _>


Cracking a cop submission requires that you kill all of its hidden dinosaurs. You earn a point for each submission you crack. Note that the cop can encode garbage or null data around the dinosaur (either by bounding box or before/after the 677 characters), but you do not need to leave this data untouched.

The robber with the most cracked submissions wins.

# Sandbox

Does this work as a cops-and-robbers challenge? Any problematic loopholes or ways to abuse this?

• It's possible you simply considered this implied, but I would recommend indicating a timeframe after which a cop's answer is "safe", and requiring that safe answers post their encoder to prove that it can indeed hide arbitrary images. Requiring the decoder from the start seems best so that robbers can validate potential cracks. Also, each portion of the challenge needs some kind of scoring method. – Kamil Drakari Dec 13 '18 at 3:18
• @KamilDrakari: It will probably be a week. I just wanted to test the waters on the idea first since cops and robbers challenges are hard to make. – Beefster Dec 13 '18 at 18:01
• I'm really not sure if the stenography really adds much to the challenge. Stenography is all about hiding the fact that secrets are being transferred in the first place. Here, though, there's no reason to make the image look "normal", and so it becomes a "implement your own asymmetric crypto algorithm" – Nathan Merrill Dec 13 '18 at 21:11
• If "implement your own asymmetric crypto algorithm" is what you want, then I don't think this should be posted. Banning crypto is fine if it is closing a loop hole, but here it's literally "Do crypto without using crypto". The line will be too hard to define IMO. – Nathan Merrill Dec 13 '18 at 21:14
• @NathanMerrill: I'm definitely banning crypto to close a loophole because the challenge becomes trivial to make uncrackable with public key encryption. Symmetric crypto would be fine because you'd be able to reverse-engineer the decoder to derive a key. I suppose a possibility for better patching the loophole would be to require lossless images and require that changing a bit in the uncompressed pixel data changes at most one character in the output. That also effectively bans most hard-to-crack crypto. – Beefster Dec 13 '18 at 21:38
• Hmm... Looking over the typical cops-and-robbers challenges, none of them are related to crypto... and I can see why. I like the general concept though. I think it's fun and whimsical and I think I can convert it into one or two code challenges (code-golf, code-challenge, and popularity-contest might all work) – Beefster Dec 13 '18 at 22:18

# Buddhabrot (speed edition)

Your goal is to generate an image like this one:

(Sandbox: this image will be replaced by a valid solution image for the challenge)

This is a render of a 2D histogram called Buddhabrot. The algorithm for generating it is very simple. If you have heard of (or written a program to generate) the Mandelbrot Set, this will feel familiar. The algorithm goes as follows:

1. Generate a random complex number $$\z_0\$$
2. Iteratively perform the calculation $$\z_{i+1}=z_i^2+z_0\$$. Do this $$\N\$$ times
3. Check if the absolute value of the number $$\z_N\$$ is larger than 3
4. If it is, calculate all the numbers $$\z_i, 0 \leq i\leq N\$$ again and map them to pixels.
5. For each pixel that is mapped to, add $$\1\$$ to the counter for that pixel
6. Repeat the 4 steps above a few million (or billion/trillion) times.

Since this algorithm depends on random sampling rather than just a single calculation for each pixel, it is not as easy to parallelize on a GPU. However, a GPU will still perform better than a CPU for this task. Since it is random, it is also dependent on having a large number of iterations to generate a smooth image. With a low number of iterations, the output image will be grainy.

To participate in this challenge, write a full program which creates a render of the Buddhabrot. For this challenge, the maximum iteration number is set to 100. That means that for every random complex $$\z_0\$$, you must write to the counter array if $$\|z_{100}| > 3\$$. Note that if $$\|z_i| > 3\$$ for some $$\i < 100\$$, then you can quit the calculation, since you know that $$\|z_{100}| > 3\$$.

If you want some help to get you started, I recently made an attempt to optimize this problem. You can read about my journey if you want.

## Generating the image

A basic algorithm for rendering a Buddhabrot image is described above. To make it efficient, I would suggest that you use an unsigned int* to hold all the counters for the pixels. When running the program, you calculate which pixel should have its counter increased, then you add 1 to that index in the counter array. When you are done with the random number generation, you take your array of counters, divide every element by the array's maximum value. Then all values in the array will be in the range $$\[0,1]\$$. You can then use that value as the grayscale color of the corresponding pixel.

## Specification

1. The output image must be exactly 1024x1024 pixels
2. The maximum iteration number is 100
3. The complex numbers must be sampled from the rectangle in the complex plane given by $$\-2.5 < Re(z_0) < 1.5, -2 < Im(z_0) < 2\$$ (Sandbox: these limits are subject to change). The sampling does not have to be uniform (you might discard points which you know are not important). However, it does need to result in a picture which is visually similar to the one in the post.
4. The output image must be a visualization of the area in the complex plane given by $$\-2 < Re(z) < 2, -2 < Im(z) < 2\$$ (Sandbox: these limits might change slightly)
5. You have 20 minutes to perform the sampling and generate the image. I will assist with tweaking to maximize your score.
6. You are free to use CUDA or OpenCL to generate the image. For any other methods of implementation, please include instructions on how yo get the environment ready.

## Scoring

To ensure that we have an objective criteria for scoring, your score will be the total sum of all pixel counters. Since the Buddhabrot is a 2D histogram in its essence, this can be seen as the total number of samples. To be specific, you calculate your score before dividing by the maximum value and generating the image. The highest score wins. Note that if your approach is similar to mine, the theoretical maximum score is limited by the memory bandwidth. The bandwidth of my GPU is 484GB/s, and since each counter is 4 bytes, you can get 121 billion iterations per second. However, there might be more effective ways to save the samples using the CUDA caches, which could lead to higher performance than that. (Sandbox: I'm not 100% sure if my maximum speed calculation is valid)

Since I already have a working example for this problem, I have decided to add a further incentive. If your solution is 2x faster than my implementation, I'll reward 50 reputation once one month has passed from posting the question. If it is 5x faster, the reward goes up to 100 rep. If it is more than 10x faster, I'll award 150 rep. If you somehow manage to make your solution 30x faster, I'll throw in 200 rep. If multiple answers are eligible for the bonus, only the fastest one will be rewarded. If no answer is eligible for the bounty once one month has passed, the bounty will be rewarded to the first one who claims it. However, you can only claim one bounty, so if you have made your solution 5x faster but want to claim the 10x bounty, I will give you time to optimize your solution to reach the next bounty.

## Testing machine

• Intel 5820K 6-core 12-thread CPU running at 4.4GHz
• 16GB DDR4 RAM
• NVIDIA GTX 1080Ti (11 GB GDDR5X, 3584 CUDA cores)
• CUDA 9.0 (I'll add information about C++ version and other relevant info)
• Windows 8.1 (sorry)

## For the sandbox

• Right now there are a few things that need to be clarified in the description.
• I will also update the post with an image that is 1024x1024 pixels. Is the question clear?
• Do I need to clarify anything besides the information that's left out right now?
• Is it okay to add reputation rewards from the start to attract answers?
• Are GPU challenges welcome? A short discussion about hardware was had in the chat, and I'm aware that not everyone has a NVIDIA GPU. That's why I made sure that there are OpenCL implementations of this problem.
• I say that the sampling should be uniform, but there have been some optimized solutions using importance sampling for this specific problem, should I allow that?
• Step 6 is "repeat the 4 steps above". Does that mean "repeat steps 2-5", or is it a mistake and should be "5 steps"? – Kamil Drakari Dec 11 '18 at 20:37
• Two parts of the challenge leave me scratching my head when combined. When describing the formula you say that "if |zi|>3 for some i<100, then you can quit the calculation, since you know that |z100|>3." which seems to imply that |zi+1|>|zi| However, in the specification you assert that the range of possible values for z0 should be identical to the range of values displayed. Either this means some samples map to pixels off-screen or... I guess I could be misunderstanding something? – Kamil Drakari Dec 11 '18 at 20:58
• @KamilDrakari I'll address all of these points more thoroughly later today. Yes, it should say repeat the 5 steps. As for the scoring, it is random, but since a good program will perform >10^10 iterations per second, the standard deviation will be very low. To maximize your score, you want to perform steps 1-5 as many times as possible within the time limit. And yes, samples could map to pixels off-screen. Those samples do not count towards your score. It is not always true that |z_i+1|>|z_i|, but if the absolute value goes above 2, it will start growing towards infinity. – maxb Dec 12 '18 at 5:37
• Ah, I think to resolve my confusion about the scoring method you should add somewhere "Highest score wins" or "higher scores are better". – Kamil Drakari Dec 12 '18 at 14:24
• "The sampling must not be uniform". In that case, you need to specify what it must be. – Peter Taylor Dec 14 '18 at 11:40
• @PeterTaylor I'm sorry, I meant "the sampling does not have to be uniform". I have seen some work with importance sampling, but I have not implemented that myself. – maxb Dec 14 '18 at 12:47

# A Golden March

Draw a circle whose circumference is the golden mean. Choose a point and label it 1, then move clockwise around the circle in steps of arc length 1, labeling the points 2, 3, and so on. At each step, the difference between each pair of adjacent numbers on the circle is a Fibonacci number.

from Futility Closet.

### Challenge

Given some natural number $$\ n \geq 1 \$$, determine the first $$\n\$$ points as described above. Then determine all differences between pairs of adjecent numbers and return them as a list.

### Details

• The list should contain all the differences in the order in which they appear.
• It should start with the difference between $$\1\$$ and one of its adjecent neighbours. Then you need to continue recording the differences in the direction you started with.

### Examples

to be determined.

# Prime number construction game

Tags: code-golf

Inspired by this post, here is A "single player" version of the prime number construction game.

### The game:

2. Add a digit to the end, such that the resulting number is a prime number.
3. Repeat from step 2 until there are no more possible prime numbers.

### The challenge:

Write a function (or required functions) that returns the sum of the lengths of the largest prime numbers you can get starting with each digit, following the game rules above.

### The score:

Scoring will have two components:

1. The length of the code, in bytes (it's code-golf, after all), and
2. The sum of the length of the largest primes obtained, starting with each digit.

The total score will be the length of the code (1) minus the sum of the length of the largest primes obtained (2).

The lowest score wins.

### Example:

Here's a code sample using R (verbose and non golfed):

isprime <- function(x) {
for(i in 2:sqrt(x))
if(x %% i == 0)
return(FALSE)
return(TRUE)
}

next_prime <- function(x) {
for(i in sample(c(1,3,7,9))) {
y <- strtoi(paste(c(x,i), collapse=''))
if(isprime(y))
return(y)
}
return(NULL)
}

longest_primes <- function(x) {
primes <- 1:9
for(d in 1:9) {
y <- d
while(!is.null(y)) {
primes[d] <- y
y <- next_prime(y)
}
}
return(sum(nchar(primes)))
}


Here's a sample run of the code above:

 Digit | Largest prime obtained | Length
------+------------------------+-------
1   | 19139                  | 5
2   | 29399999               | 8
3   | 3797                   | 4
4   | 4799                   | 4
5   | 53                     | 2
6   | 6173                   | 4
7   | 719333                 | 6
8   | 89                     | 2
9   | 977                    | 3
------+------------------------+-------
Total |                        | 38


Assuming the byte count of my code is 469, my final score is 469-38=431.

# [Language]: [Byte count] - [Sum of lengths] = [Total score].

Miscelaneous:

I think this is a simple, yet fun, challenge. I've searched the site, and I haven't found a related challenge. If there's one, please point me.

I tried sometime ago to post a challenge, and I wasn't careful enough before posting (hence, I deleted it). I'd like to post a good first challenge. Any feedback will be appreciated.

• Unfortunately, the possible results are very small, so this challenge may not be that interesting. (They are: 1979339333, 1979339339, 23399339, 29399999, 37337999, 4391339, 59393339, 6133373, 6733919, 6733997, 73939133, 839, 9719, for a total of -63.) Be aware that most golf languages will get a score near -63 just by brute forcing. – japh Dec 22 '18 at 14:29
• @japh That may be. I just thought it would be fun. Maybe a "King of the Hill" dinámica would work? Bots competing to eliminate opponents generating primes? (Like the game mentioned in the linked post) – Barranka Dec 22 '18 at 19:31

# Is it a D?

Given an image, check if it's a letter D.

Here D is defined as:

Let pixels labeled $$\(x,y)\$$ where larger $$\x\$$ mean at right and larger $$\y\$$ mean more up. If there exist $$\x_0, x_1, f_0, f_1, f_2, f_3\$$ such that:

• $$\ (f \rightarrow (x\rightarrow f(x+1)-f(x)))^n (f_i) (x) >0\$$ for $$\n>0, 0\leq i<4\$$
• $$\ x_0
• Pixel $$\(x,y)\$$ is true iff $$\y>f_0(x) \text{ and } y<-f_1(x) \text{ and } (y>-f_2(x) \text{ or } y
• There should be a hole, i.e. a false pixel that can't reach border without acrossing a true pixel

Shortest code win. Don't mind if D doesn't follow the rule or a symbol which follows the rule doesn't look like a D at all

• A couple of examples would help here. Also, if I've understood the conditions correctly, I think you mean $y>-f_2(x)$. – japh Dec 22 '18 at 14:54
• Also, those are some fast-growing $f_i$. Your font must have really, really tall D's. – japh Dec 22 '18 at 14:55

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.

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.

# 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 – Kenzie 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
"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)

alert('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