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

Phases of the Clock Moon Numbers

We can imagine all the factors of a number. For example 7 has factors 1 and 7. 12 has factors 1, 2, 3, 4, 6, and 12. 9 has factors 1, 3, and 9.

We can also imagine that a number has a position on the edge of a wheel or circular face. Let us divide our circle into 12 pieces around the edge evenly. In fact, we can call this a clock face. Human culture has settled on most clock faces having 12 numbers.

Therefore, we can imagine creating hands on a clock face for an integer that we have been given, like 7. Each hand can be imagined as a nice, easily visible line drawn from the center of the circle to the position of the number on the edge of the circle. We can also imagine creating hands on the face for all of that integer's factors, like 1 and 7. Now, we can imagine the clock face with hands at each factor. 1 and 7 for 7. This clock face now has 2 hands.

The number 9 will have 3 hands, at 1, 3, and 9.

The number 10 will have 4 hands, at 1, 2, 5, and 10.

The number 12 will have 5 hands, at 1,2,3,6, and 12.

The number 13... er... well, in that case, we use modular arithmetic. The number 12 becomes 1. In mathematical language, we might say the number 13 modulo 12 is 1. Another way to say this is that the remainder of 13 divided by 12 is 1. We could also say that 13 is congruent to 1, modulo 12.

At any rate, our imaginary clock face for the number 13 will have hands at 1 and.... 1. Now, we will say that the two hands are redundant, so it actually only has one hand, pointing to the position 1.

The number 14 will have 4 hands, at 1, 2, 7, and... 2. So actually just three hands.

Now, you may notice a pattern here. Some numbers generate a clock face with hands clustered together around the right hand side of the face, like 6 with 1, 2, 3. Other numbers seem to have hands all over the face, spread more evenly, like 20 with 1, 2, 4, 5, 10, 8. And we can go further - some numbers like 77 will only have their hands on the left-ish side of the face, at 7 and 11.

To make it even easier, let's rotate the clock anti-clockwise by one hour, so the number 1 is straight up and the number 7 is straight down.

Let us give these patterns names.

Numbers like 1, and 13, with only one clock hand: Full

Numbers with clock hands only on the left, like 77: First South Quarter

Numbers with clock hands only on the right, like 6: Last South Quarter

Numbers with clock hands on all sides, like 20 (10,5,2,1,8): New

Write a program that given some number n, returns it's phase, and how many other numbers have that same phase, but are smaller than n.

For example 13 has the phase Full, and there is 1 other number below it, so the result should be "Full 1"

2, 3, 4, 5, and 6 are all phase Last South Quarter, so they would be "LSQ 0" "LSQ 1", "LSQ 2", "LSQ 3", "LSQ 4"

7 has phase First South Quarter, and in fact is the first such number, so it will be "FSQ 0".

8 has factors 4, 2, and 1, which are on both the left and right side, so it's phase is New. It's the first full number, so "New 0"

• Hm, as it is right now, it looks like the "how many other numbers have that same phase, but are smaller than n" is an overcomplication. Also, is the 1 hand to the left, right or neither? Similarly for the 7 hand. I also suggest allowing any 4 unique identifiers for the phases. – Erik the Outgolfer Jun 30 '19 at 16:50

# Switch the colour of the largest non-unique connected shape

Given a rectangular grid of square cells, find the non-unique connected shapes with the largest area, and switch their colour

# Input

• A rectangular grid of cells, each of which has 1 of 2 distinct values ("colours")
• You can choose to accept any of
• an image with only 2 distinct pixel colours
• text with only 2 distinct characters (also allowing newlines for forming a rectangle)
• a 2d array, with each element having 1 of 2 distinct values
• a 1d array, plus a width and/or height

The 2 distinct values will be referred to as "colours", but the rules apply similarly for all of the permitted formats

# Output

• A rectangular grid of cells in the same format as the input, using the same 2 colours
• For each shape required to be changed, all of its cells have been switched to the other colour

# Rules

• Each cell is part of a connected shape, which contains all cells of the same colour that can be reached by a path made up only of vertical or horizontal steps to adjacent cells of the same colour (no diagonal steps)
• The grid does not wrap: a shape cannot be connected across the outer boundary
• A shape is identical to another if it can be made to coincide exactly with it by any combination of
• translation
• rotation by an integer multiple of 90 degrees
• reflection in any vertical or horizontal line
• switching its colour
• A shape is unique if no other shape is identical to it
• The area of a shape is the number of cells it contains
• The shapes to be changed are those with the largest area, of those that are non-unique
• If 2 or more distinct shapes are non-unique and have the largest area, all instances of each distinct shape must be changed
• If there are no non-unique shapes, the output is the same as the input
• A grid (input or output) may sometimes contain only 1 of the 2 colours

# Test cases

Each test case is an input followed by its unique correct output

.  .

..  ..

.#  #.

.#  .#
..  ..

.#  #.
#.  .#

..#  ...
...  ...
.#.  ...

.......  .......
##.....  .......
#.....#  .......
.....##  .......

....##.  ....##.
##..##.  ....##.
#.....#  .......
.....##  .......

#.....###.  ..........
#.......#.  ..........
##...##...  ..........
.....##...  ..........
##........  ..........
##..####..  ....####..

.......###  .......###
..##..####  ......####
..#..###.#  .....#####
....###..#  ....######
...#######  ...#######

.......###  #######...
.##...####  ######....
.#...###.#  #####.....
....###..#  ####......
...#######  ###.......

........####  ########....
.###...#...#  ########....
.#..#.#.##.#  ##..##..##..
.###.###...#  ####........
....########  ####........

........####  ########....
.###...#...#  ########....
.#..#.#....#  ##..##......
.###.###...#  ####........
....########  ####........

The same test cases with colour coding for human reading (click image for larger version):

# Scoring

This is . Your score is the number of bytes in your source code. For each language, the code with the lowest score wins

# Sandbox thoughts

• Any important/useful test cases welcome
• Is there a more useful format for 2d test cases?
• Are there 2 distinct characters that would make human reading easier?
• Is this a duplicate?
• Can anything be made clearer or more succinct?
• I'm also trying to think of a better name
• I think using "remove" and "change" to mean the same thing is confusing. If I understand correctly, "removing" means to change the colour of, right? That wasn't very intuitive to me on my first reading. – FryAmTheEggman Jun 29 '19 at 16:52
• Ah good point. Thank you. I will try and make that consistent throughout – trichoplax Jun 29 '19 at 19:16

# Some enchanted avening

(you may see a stranger across a crowded room).

This is one part of a multi-part series inspired by various built-ins in R. Credit goes to digEmAll for suggesting this one.

ave calculates particular grouped values of a list.

For example, we would group x in the following way based on the criteria given in f:

x = [2, 1, 3, 5, 4, 1, 5, 5]
f = [[1, 2, 2, 2, 1, 2, 1, 1], [1, 1, 2, 2, 2, 1, 1, 2]]

x f1 f2
[1,] 2  1  1    -> group [1,1]
[2,] 1  2  1    -> group [2,1]
[3,] 3  2  2    -> group [2,2]
[4,] 5  2  2    -> group [2,2]
[5,] 4  1  2    -> group [1,2]
[6,] 1  2  1    -> group [2,1]
[7,] 5  1  1    -> group [1,1]
[8,] 5  1  2    -> group [1,2]

Then for each group, we apply a given function (in R, the default is mean), let's say sum:

group [1,1]: 2, 5 -> sum = 7
group [2,1]: 1, 1 -> sum = 2
group [2,2]: 3, 5 -> sum = 8
group [1,2]: 4, 5 -> sum = 9

Then we replace each value in the group by the group sum, resulting in an output of:

[7, 2, 8, 8, 9, 2, 7, 9]

## Inputs:

• a list x of integers
• a list of lists f or an arbitrary number of lists, each of length equal to x; these are the factors to group on
• a black-box function FUN that takes a list of integers and returns a single integer value

## Output

• a list o of length equal to x where each element o[i] is equal to FUN(group(x[i])), or as the documentation says:

A numeric vector, say y of length length(x). If f is g1, g2, e.g., y[i] is equal to FUN(x[j], for all j with g1[j] == g1[i] and g2[j] == g2[i]).

## Rules

• Input can be in any order and in many flexible output formats.
• You may assume that the outputs will always result in integers.
• If your language has a builtin for this for some reason, please also implement your own solution.

# Sandbox questions/notes:

• I've done two of these so far and found a reference to a musical that is somewhat appropriate, any suggestion is appreciated there.
• Need to add test cases
• Need to work a bit harder on the explanation of how ave works.
• You could call this something along the lines of "Ave Maria von Trapp"? Aside from that I understood your description well enough to write a (poor) answer. – FryAmTheEggman Jun 26 '19 at 19:45

# Introduction

A list is a common, well-understood data structure. Neo4j's property graph model can represent any data structure. Using the Cypher query language, write a collection of statements for managing a todolist

# Challenge

Manage a todo list using parameterized Cypher.

Todo list items are composed of two pieces of information:

• todo:string - the textual content describing the thing to do
• completed:boolean - whether this todo has been done

Todo list operations:

• add new, view, edit, remove, complete, un-complete individual todo list item
• re-order todo list item
• view all items
• view all completed items
• view all "active" items (items not yet completed)
• complete all todo list items

Considerations:

• empty todo list

Out of scope:

• multiple lists

For each operation, provide a code block of Cypher. Identify the operation with its description. Separate each operation with a --- line. Like this...

1. Create an empty node:
CREATE ()

1. Create a generic relationship:
CREATE ()-[:RELATES_TO]->()

## Proposed tags

[cypher] [graph-theory]

• (1) This is a long way from being self-contained. What's Neo4j? (Sounds like a Java library). What's Cypher? (2) The operations need more explanation, particularly those which rely on properties which haven't been mentioned. (Reorder? But there's no position-in-order property. Operations on individual item: what's its identity?). (3) This site discourages questions which restrict answers to a single language unless there's a good reason for the restriction. I don't see a good reason here. – Peter Taylor Jul 6 '19 at 7:54

## Can the cursor reach the bottom?

A cursor position is valid if either of its two sides touches whitespace (i.e. a space or a newline(CR+LF or LF, depending on your OS)). The input will always consist of valid cursor positions.

This takes one input(a character matrix), and for a cursor on the up right corner of the input, can the cursor reach the bottom of the input?

Example input:

..... Same, delete text like this in order
......
. . . .
.      Same to get normal input
...... Same

The cursor can reach the bottom in this case. This process of moving the cursor will work: down, right(touches spaces on the left), down(touches spaces on the right), down, right(touches spaces on both sides) 6 times, and down(touching spaces and a linefeed).

Notably, this will also work:

Code Golf deletes trailing whitespace by default
..
. trailing

The cursor starts at the up-right corner. After moving right two times, it can move down (due to touching a newline character). Then, it can move down, which touches the bottom of the line.

This example will not work:

...
... Same reason as above

The cursor cannot move down, as there is no sufficient whitespace to be touched.

Posted here

• Interesting challenge, but I'm afraid a lot of trivial solutions exist. E.g. 123 which prints 123 in many languages. More interesting would be to require all three/four characters to be unique, and that they be printed in reverse. – Adám Jul 8 '19 at 20:04
• now that this has been posted, you can edit it to only include a link to your post and delete it :-) – Giuseppe Jul 9 '19 at 18:50

# There's an echo in my array... echo in my array... my array...

Posted. Thanks for all of the suggestions and happy golfing!

• "0≤n<1000" The input has 0–1000 elements or the elements are in the range 0–1000, or both? – Adám Jul 8 '19 at 21:24
• Can there not be multiple correct solutions? – Adám Jul 8 '19 at 21:26
• Will the echo ever begin at the first element? – Adám Jul 8 '19 at 21:26
• I'm not sure I fully understand how the echo works. Why can [2,4,6] not be [1,2,3] with an echo overlapping at the first element? – Adám Jul 8 '19 at 21:31
• In fact, would there be one solution for each step, so dividing the input by 2 is always a valid solution? – Adám Jul 8 '19 at 21:32
• @Adám ah yes, that's why echo cannot begin at the first element. The echo'd version will always be longer than the original un-echoed version. I'll clarify that. – 640KB Jul 8 '19 at 21:33
• @Adám have updated rules and test cases from your comments. Thanks! – 640KB Jul 9 '19 at 18:32
• As suggestion: if there is no echo, don't output nothing or false - the challenge is to correct the echo. If there is none, the echo is corrected to be... no different from the input. In a bid for consistency, I would therefore suggest that if there is no echo, they should output the original input, since that is the 'normal' version of the array. – Geza Kerecsenyi Jul 10 '19 at 8:09
• Also, I'd suggest to make the program return the shortest possible array in the case of multiple solutions, to remove the most possible reverb - i.e choose the one that removes the most values from the input. – Geza Kerecsenyi Jul 10 '19 at 13:42
• @GezaKerecsenyi I've been trying to come up with a case where there are multiple solutions, and cannot. You can easily have many echo'd versions for a given un-echo'd version, but there seems to only be one or zero un-echo'd versions for an echo'd version. I'm not a mathematician, so I cannot conclusively prove this, and I'm happy to be proven wrong, but I don't see a way that a correctly-constructed echo'd version could produce more than one answer. – 640KB Jul 10 '19 at 14:52
• @gwaugh after further consideration, I have come to the conclusion that you're correct. It's like a Fourier transform: every wave function always have a unique value, either in terms of phase or magnitude. Here, the phase is always different, and since the phase is shifted, the 'transform' of these numbers (imagining they are Y values at the X point of their index) must also be unique. So feel free to remove that rule - there can never be two answers. – Geza Kerecsenyi Jul 10 '19 at 17:12

## Story

I began studying the Collatz Conjecture

And noticed this pattern in the numbers that go to 1 in one odd step, like 5,10,20,21,40,42... and looke in up on OEIS and found this formula.

$$\floor(sqrt(4*n + 1)) - 1\$$

Which can plot these numbers in their natural order like so;

$$\\frac{\left(8\cdot2^{\operatorname{floor}\left(\sqrt{4\operatorname{floor}\left(x\right)+1}\right)}-2^{\left(\operatorname{floor}\left(\sqrt{4\operatorname{floor}\left(x\right)+1}\right)-1-\operatorname{floor}\left(\frac{\left(4\operatorname{floor}\left(x\right)+1-\operatorname{floor}\left(\sqrt{4\operatorname{floor}\left(x\right)+1}\right)^2\right)}{2}\right)\right)}\right)}{3}\$$

Then I looked at numbers going to 1 in two steps, like 3,6,12,13,24,26...
Where I found another pattern that I could not find a formula for on OEIS

long nth(int n){if(n>241)return -1;return (((1<<Y[n]+5)-(1<<1+Y[n]-((Z[n]&1)+Z[n]*3)))/3-(1<<Y[n]-2*X[n]-(2*(Z[n]&1)+Z[n]*3)))/3;}

With X[],Y[] and Z[] being these lookup-tables

int[]X=new int[]{
0,
0,
0,  1,
0,  1,
0,  1,  2,
0,  1,  2,                              0,
0,  1,  2,  3,                          0,                          0,
0,  1,  2,  3,                          0,  1,                      0,
0,  1,  2,  3,  4,                      0,  1,                      0,  1,
0,  1,  2,  3,  4,                      0,  1,  2,                  0,  1,
0,  1,  2,  3,  4,  5,                  0,  1,  2,                  0,  1,  2,
0,  1,  2,  3,  4,  5,                  0,  1,  2,  3,              0,  1,  2,                  0,
0,  1,  2,  3,  4,  5,  6,              0,  1,  2,  3,              0,  1,  2,  3,              0,              0,
0,  1,  2,  3,  4,  5,  6,              0,  1,  2,  3,  4,          0,  1,  2,  3,              0,  1,          0,
0,  1,  2,  3,  4,  5,  6,  7,          0,  1,  2,  3,  4,          0,  1,  2,  3,  4,          0,  1,          0,  1,
0,  1,  2,  3,  4,  5,  6,  7,          0,  1,  2,  3,  4,  5,      0,  1,  2,  3,  4,          0,  1,  2,      0,  1,
0,  1,  2,  3,  4,  5,  6,  7,  8,      0,  1,  2,  3,  4,  5,      0,  1,  2,  3,  4,  5,      0,  1,  2,      0,  1,  2,
0,  1,  2,  3,  4,  5,  6,  7,  8,      0,  1,  2,  3,  4,  5,  6,  0,  1,  2,  3,  4,  5,      0,  1,  2,  3,  0,  1,  2,      0,
0,  1,  2,  3,  4,  5,  6,  7,  8,  9,  0,  1,  2,  3,  4,  5,  6,  0,  1,  2,  3,  4,  5,  6,  0,  1,  2,  3,  0,  1,  2,  3,  1, 2
};
int[]Y=new int[]{
0,
1,
2,  2,
3,  3,
4,  4,  4,
5,  5,  5,                              5,
6,  6,  6,  6,                          6,                          6,
7,  7,  7,  7,                          7,  7,                      7,
8,  8,  8,  8,  8,                      8,  8,                      8,  8,
9,  9,  9,  9,  9,                      9,  9,  9,                  9,  9,
10, 10, 10, 10, 10, 10,                 10, 10, 10,                 10, 10, 10,
11, 11, 11, 11, 11, 11,                 11, 11, 11, 11,             11, 11, 11,                 11,
12, 12, 12, 12, 12, 12, 12,             12, 12, 12, 12,             12, 12, 12, 12,             12,             12,
13, 13, 13, 13, 13, 13, 13,             13, 13, 13, 13, 13,         13, 13, 13, 13,             13, 13,         13,
14, 14, 14, 14, 14, 14, 14, 14,         14, 14, 14, 14, 14,         14, 14, 14, 14, 14,         14, 14,         14, 14,
15, 15, 15, 15, 15, 15, 15, 15,         15, 15, 15, 15, 15, 15,     15, 15, 15, 15, 15,         15, 15, 15,     15, 15,
16, 16, 16, 16, 16, 16, 16, 16, 16,     16, 16, 16, 16, 16, 16,     16, 16, 16, 16, 16, 16,     16, 16, 16,     16, 16, 16,
17, 17, 17, 17, 17, 17, 17, 17, 17,     17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17, 17,     17, 17, 17, 17, 17, 17, 17,     17,
18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18
};
int[]Z=new int[]{
0,
0,
0,  0,
0,  0,
0,  0,  0,
0,  0,  0,                              1,
0,  0,  0,  0,                          1,                          2,
0,  0,  0,  0,                          1,  1,                      2,
0,  0,  0,  0,  0,                      1,  1,                      2,  2,
0,  0,  0,  0,  0,                      1,  1,  1,                  2,  2,
0,  0,  0,  0,  0,  0,                  1,  1,  1,                  2,  2,  2,
0,  0,  0,  0,  0,  0,                  1,  1,  1,  1,              2,  2,  2,                  3,
0,  0,  0,  0,  0,  0,  0,              1,  1,  1,  1,              2,  2,  2,  2,              3,              4,
0,  0,  0,  0,  0,  0,  0,              1,  1,  1,  1,  1,          2,  2,  2,  2,              3,  3,          4,
0,  0,  0,  0,  0,  0,  0,  0,          1,  1,  1,  1,  1,          2,  2,  2,  2,  2,          3,  3,          4,  4,
0,  0,  0,  0,  0,  0,  0,  0,          1,  1,  1,  1,  1,  1,      2,  2,  2,  2,  2,          3,  3,  3,      4,  4,
0,  0,  0,  0,  0,  0,  0,  0,  0,      1,  1,  1,  1,  1,  1,      2,  2,  2,  2,  2,  2,      3,  3,  3,      4,  4,  4,
0,  0,  0,  0,  0,  0,  0,  0,  0,      1,  1,  1,  1,  1,  1,  1,  2,  2,  2,  2,  2,  2,      3,  3,  3,  3,  4,  4,  4,      5,
0,  0,  0,  0,  0,  0,  0,  0,  0,  0,  1,  1,  1,  1,  1,  1,  1,  2,  2,  2,  2,  2,  2,  2,  3,  3,  3,  3,  4,  4,  4,  4,  5, 5
};

## Challenge

The challenge is to write a "reasonably fast" function or expression that replaces and extends these lookup tables.
Think of the lookup tables as a 3D structure. Pictured is the top 720 boxes of this structure.

## Input

An integer which is the index of a cube in the structure. You can assume the input will be in the range 0 to 719 inclusive.

## Output

The x,y,z coordinates for the given index. Assuming the input is between 0 and 719 the output ranges are x, 0 to 13 y, 0 to 27 z, 0 to 8

It's fine to accept and return larger indexes correctly just not required.

## Examples

i  ->   x   y   z
0  ->   0,  0,  0
12  ->   0,  5,  1
30  ->   4,  8,  0
65  ->   2, 11,  1
100  ->   0, 13,  2
270  ->   1, 19,  3
321  ->   1, 20,  6
719  ->   1, 27,  8

If you collapse the z-coordinate, then the structure is indexed top-down left right like shown below; Examples are marked in square brackets []

Y,Z 0,
0   | [0]
1   |  1
2   |  2   3
3   |  4   5
4   |  6   7   8                                1,
5   |  9  10  11                                 |[12]                           2,
6   | 13  14  15  16                             | 17                             | 18
7   | 19  20  21  22                             | 23  24                         | 25
8   | 26  27  28  29 [30]                        | 31  32                         | 33  34
9   | 35  36  37  38  39                         | 40  41  42                     | 43  44
10   | 45  46  47  48  49  50                     | 51  52  53                     | 54  55  56                    3,
11   | 57  58  59  60  61  62                     | 63  64 [65] 66                 | 67  68  69                     | 70                4,
12   | 71  72  73  74  75  76  77                 | 78  79  80  81                 | 82  83  84  85                 | 86                 | 87
13   | 88  89  90  91  92  93  94                 | 95  96  97  98  99             [100] 101 102 103                |104 105             |106
14   |107 108 109 110 111 112 113 114             |115 116 117 118 119             |120 121 122 123 124             |125 126             |127 128
15   |129 130 131 132 133 134 135 136             |137 138 139 140 141 142         |143 144 145 146 147             |148 149 150         |151 152
16   |153 154 155 156 157 158 159 160 161         |162 163 164 165 166 167         |168 169 170 171 172 173         |174 175 176         |177 178 179        5,
17   |180 181 182 183 184 185 186 187 188         |189 190 191 192 193 194 195     |196 197 198 199 200 201         |202 203 204 205     |206 207 208         |209    6,
18   |210 211 212 213 214 215 216 217 218 219     |220 221 222 223 224 225 226     |227 228 229 230 231 232 233     |234 235 236 237     |238 239 240 241     |242     |243
19   |244 245 246 247 248 249 250 251 252 253     |254 255 256 257 258 259 260 261 |262 263 264 265 266 267 268     |269[270]271 272 273 |274 275 276 277     |278 279 |280
20   |281 282 283 284 285 286 287 288 289 290 291 |292 293 294 295 296 297 298 299 |300 301 302 303 304 305 306 307 |308 309 310 311 312 |313 314 315 316 317 |318 319 |320[321]
X->|  0   1   2   3   4   5   6   7   8   9  10 |  0   1   2   3   4   5   6   7 |  0   1   2   3   4   5   6   7 |  0   1   2   3   4 |  0   1   2   3   4 |  0   1 |  0   1

Note that at even y-coordinates the structure expands in the x-direction, and at 0 and 5 mod 6 in the z-direction. Expect for the very top block.

# Rules

This is code-golf, the shortest code in bytes wins.

Reasonably fast As an additional requirement although not a competition of fastest code,
the code must still be shown to compute coordinates in a reasonable amount of time. You may for example use try it online and run a loop through all coordinates under 720 without exceeding the time limit of a minute, printing is optional.

"storing information as you go" is forbidden. For example executing f(100) should not depend on having computed f(99) previously.

Lookup tables are allowed but included in bytecount so aim to make them sparse if you choose to use them.

# Example code

non-competing

coord coords(int index){
int a=0,b=0,c=0;
int x=0,y=0,z=0;
long n,k,one;
n = k = 3;
int t=0;
while(t<index){
int s=0;k++;n=k;
while(n>1 && s<4){ n/=n&-n;n=n*3+1; n/=n&-n;s++;}
if(s==2)t++;
}
n=k;
one=n&-n;k = one;while(k>1){k>>=1;c++;} n=3*n+one;
one=n&-n;k = one;while(k>1){k>>=1;b++;} n=3*n+one;
one=n&-n;k = one;while(k>1){k>>=1;a++;}
coord r;
r.x = (b-c-1)>>1;
r.y = a-5;
r.z = (a-b-2)/6 +(a-b-4)/6;
return r;
}

Try it online!

• Will the input always be between 0 and 321 (inclusive)? – streetster Jul 10 '19 at 6:27
• Good question, let's go with 797 @streetster – PrincePolka Jul 10 '19 at 10:59
• @streetster 719.. i counted the boxes wrong, good thing I began in the sandbox – PrincePolka Jul 11 '19 at 17:58

# Decode a RISC-V J-type immediate

RISC-V is an open processor instruction set, which defines a somewhat typical RISC instruction set. However, in order to make decoding simpler in hardware, the encoding for immediate values tends to be quite complex, with the bits essentially shuffled around. And the worst offender for that is without a doubt the type J (jump) instruction type.

So, the challenge is, given a (non-compressed) RISC-V instruction word, decode and output its type J immediate part.

A type J instruction has the following format:

31      30-21     20       19-12   11-7  6-0
|imm[20]|imm[10:1]|imm[11]|imm[19:12]| rd |opcode|

The only fields we are interested in are the imm fields. The immediate is sign extended, and its least significant bit is always 0, so the immediate (in term of instruction bits) is:

31-20       19-12       11        10-1     0
|...inst[31]|inst[19:12]|inst[20]|inst[30:21]| 0 |

Sample pseudocode: 0xFFF00000 * ((instr >> 31) & 1) | (instr & 0x000FF000) | ((instr & 0x100000) >> 9) | ((instr & 0x7FE00000) >> 20).

## Test cases

I: 0x4DFAB06F (j 0xABCDE)
O: 0x000ABCDE

I: 0xFD9FF0EF (jal ra, -0x28)
O: 0xFFFFFFD8

I: 0x8000006F (j -0x100000)
O: 0xFFF00000

The answer with the smallest byte count wins, standard loopholes apply, etc... Your program may take input and write output in any format it requires.

• It took a bit of puzzling to figure out the second code block. The ... notation is liable to misunderstanding (I'm not sure whether JS developers would find it more or less confusing), and there's no clear reason for 10-5 and 4-1 to be split up. This is one case where a reference implementation in generic C-like pseudocode could help: I think 0xfff00000 * ((imm >> 31 & 1)) | (imm & 0x000ff000) | ((imm & 0x00100000) >> 9) | ((imm & 0x7fe00000) >> 20) is correct and fairly generic. (In particular, I've deliberately avoided making assumptions about how the sign bit is treated under >>). – Peter Taylor Jul 16 '19 at 8:10
• @PeterTaylor I copied the instruction format diagram from the RISC-V specification and I didn't realize the 10-5 and 4-1 parts could be merged. Oops. And I added a pseudocode for the decoding. – TuxCrafting Jul 16 '19 at 11:38

# Alphanumeric Line and Curve Counting

Posted here.

## Bits and Bytes constant generation

In this challenge, you have to generate the shortest Bits and Bytes program that outputs an integer input. For the simplicity of the challenge, you only have to search with ! and <.

## Bits and Bytes quick reference

Bits and Bytes operates on a one-byte accumulator. There are 4 operations (only 2 are neccecary for this challenge):

• ! : Invert all of the bits in the accumulator
• < : Shifts all bits in the accumulator one bit to the right. The leftmost bit becomes a 0 and the rightmost bit is discarded.
• > : Shift right
• @ : Swap nybbles

## Input / Output

Input will be two integers. The first integer sets the accumulator to the value of that integer. The second integer indicates the resulting value. Your program should output the shortest program in Bits and Bytes that sets the accumulator to that value.

0
255
!
0
4
!<!<!<

## This is a code-golf contest; the shortest program wins.

• I'd recommend having the question be self contained and explaining what the instructions actually do – Jo King Jul 21 '19 at 11:34
• This is similar enough to some previous challenges that I wouldn't be surprised if someone finds a dupe. Also, should there be a second input for the starting value of the accumulator? – Peter Taylor Jul 21 '19 at 23:04

# WANTEDM?VEMENTANDACALMCOURSE?FE???UENCE

## Challenge

Inspired by puzzles appearing on my website's chat, your job (should you choose to accept it) is to accept a string (say (?@Nbgkx¨¾ÃÐÕã÷øĆĊċĎďěĨīĺŏšŴŹǣǩǮ˘͵ΖΫΰξρφ) and:

• Find the Unicode points for the string: [40, 63, 64, 78, 98, 103, 107, 120, 168, 190, 195, 208, 213, 227, 247, 248, 262, 266, 267, 270, 271, 283, 296, 299, 314, 335, 353, 372, 377, 483, 489, 494, 728, 885, 918, 939, 944, 958, 961, 966]
• Find the differences between elements: [23, 1, 14, 20, 5, 4, 13, 48, 22, 5, 13, 5, 14, 20, 1, 14, 4, 1, 3, 1, 12, 13, 3, 15, 21, 18, 19, 5, 106, 6, 5, 234, 157, 33, 21, 5, 14, 3, 5]
• For every element in the differences between elements:
• If the element is less than 27, add it by 64 and output it converted to a Unicode character (e.g. 1 -> "A", 2 -> "B", $$\\ldots\$$ ).
• If the element is greater than or equal to 27, output a non-alphabet character ([^A-Za-z])

## Test Cases

The test cases output in uppercase and use the question mark for the non-alphabet character.

(?@Nbgkx¨¾ÃÐÕã÷øĆĊċĎďěĨīĺŏšŴŹǣǩǮ˘͵ΖΫΰξρφ --> WANTEDM?VEMENTANDACALMCOURSE?FE???UENCE
!1CRYkly¤´ÉãýĉĎġĢİĴķņŊŏŖťűŷ --> PROGRAM?PUZZLESANDCODEGOLF

## How to convert

This is a placeholder for the convertion process.

def normal_to_malbolge(prog):
pos = 0
malbolge = ""
for i in prog:
char = ord("' ( > D Q b c u".split()["*jpovi</".find(i)]) - pos
while char < 33:
char += ord("~")-32
malbolge += chr(char)
pos += 1
return malbolge

### Explanation

Iterate over the normalized Malbolge program, and then convert all "*jpovi</"'s to a character in "'", '(', '>', 'D', 'Q', 'b', 'c', 'u'. Then, minus the position.

While the temporary Malbolge representations' ASCII code is less than 33, increment the char by the ASCII code of "~" minus 32.

Append the resulting character to the output.

## Rules

• This is a contest; the shortest answer wins.
• The default I/O methods are allowed.

## Sandbox

• Is it a duplicate? This probably is.

• Is the challenge well-written?
• You need to include the instructions for converting normalized malbolge to malbolge (will give later) – MilkyWay90 Aug 21 '19 at 1:18
• ^ Check my code to convert and make an explanation out of that. Some people don't know python, and my code is very ugly – MilkyWay90 Aug 21 '19 at 4:18
• You could include a link to the standard loopholes, and put in that default I/O methods are allowed. Other than that I /support – MilkyWay90 Aug 21 '19 at 15:33

# I need help rewording the prompt.

I learned from last time about having convoluted scoring and having too broad of a focus from my last question. I hope this one is more clear.

# Church Subtraction

Lambda calculus has always been a fascination of mine and the emergent behaviors of passing functions into each other is delightfully complex. Church numerals are representations of natural numbers contructed from the repeated application of a function (normally the unary addition of a constant). For example, the number zero returns and "ignores" the input function, one is f(x), two is f(f(x)) and so on:

ident = lambda x: x
zero = lambda f: ident
succ = lambda n: lambda f: lambda x: f(n(f)(x))
one = succ(zero)
add1 = lambda x: x + 1
print(to_int(one))
>>> 1

From this we can easily see that addition is accomplished by applying the first function to x then applying the second function to x:

add = lambda m: lambda n: lambda f: lambda x: n(f)(m(f)(x))
>>> 3

Addition is relatively easy to understand. However, to a newcomer it might be inconceivable to think of what subtraction looks like in a Church encoded number system. What could it possibly mean to un-apply a function?

# Challenge

Implement the subtraction function in a Church encoded numeral system. Where subtraction performs the monus operation and unapplies a function n times if the result will be greater than zero or zero otherwise. This is code-golf so shortest code wins.

# Input

Two Church numerals that have been encoded in your choice of language. The input can be positional or curried. To prove these are true Church numerals they will have to take in any function and apply them repeatedly (add1 is given in the examples but it could be add25, mult7, or any other unary function.)

# Output

A Church numeral. It should be noted that if m < n then m - n is always the same as the identity function.

Examples:

minus(two)(one) = one
minus(one)(two) = zero
...

also acceptable:

minus(two, one) = one
minus(one, two) = zero

Credit:

This github gist for giving me a python implementation of Church Numerals.

• 1. I'm not sure how to parse "the number zero is a cat function Church encoding". Perhaps it would be better expressed as "the Church encoding of the number zero is the identity function"? 2. Explaining multiplication is an unnecessary distraction (unlike addition, which is relevant context). You've got a link to Wikipedia for people who want to learn more. 3. There is a technical term, monus, which describes the truncated subtraction. The truncation at zero should be described in the Challenge section, not the Output, and you might want to introduce this term there. – Peter Taylor Aug 23 '19 at 7:31
• 1. I missed an "in" and a cat function is pretty known in esolangs (esolangs.org/wiki/Cat_program), thank you for catching this. 2. I could explain exponentiation as well and maybe that might make a more compelling story. Or should I just stick with addition? 3. Thanks for the suggestion. – Ryan Schaefer Aug 23 '19 at 12:04
• 1. cat is well known in POSIX too, and in both cases it does I/O. I think it's misleading and confusing to call ident a cat function. And the word order of the edited version is ambiguous, and IMO tends to the parse "(the number zero) (is) (a cat function in Church encoding)". – Peter Taylor Aug 23 '19 at 12:29
• @PeterTaylor that work better? – Ryan Schaefer Aug 23 '19 at 13:22

# Determine the minimal indices needed to cover all queries

This challenge is based on Mongo's handling of compound indices and index intersection, inspired by a problem that came up at work, but I'll restate the relevant details here.

## Background

In any database, relational or not, the primary purpose of indices is to optimize data lookup.

For example, if the task of finding all questions on this site had to be accomplished by looping through all posts and looking for the code-golf tag, it would be unusably slow. An index, however, organizes this data in a way that enables fast and efficient lookup of the data we want, which drastically reduces the resource cost of queries in exchange for some more work and space in maintaining the index.

However, the cost of maintaining indices is not negligible, so it quickly becomes untenable to create 2^N indices for N fields. (Databases designed for this purpose do exist and are the better choice when this functionality is actually needed. I'm ignoring this fact because it's a more interesting challenge this way.) Thus, careful index construction and selection is important to get the most bang for your buck.

## Details

A simple index only organizes data based on one field but Mongo provides two ways to efficiently query on more than one field: compound indices and index intersection.

### Compound Indices

Compound indices organize data based on a sequence of fields, e.g. [A, B, C]. Here, order matters. If data is sorted by A then B then C, then doing a lookup based on C first cannot be done efficiently since there are no guarantees on where the desired data might be located within the index (whereas one could do e.g. a binary search based on A).

Note: compound indices enable efficient queries on prefixes of that index as well. That is, a compound index on [A, B, C] enables efficient queries that have [A], [A, B], or [A, B, C]. However, as previously mentioned, it does not support queries that have [B], [C], [A, C], or [B, C].

### Index Intersection

Exactly two indices can be used to optimize a query if there does not already exist a compound index for the desired fields. That is, if there is an index on [A] and an index on [B], then a query on [A, B] can be executed fairly efficiently (though not as efficiently as if there was a compound index, but let's ignore that). This also applies to prefixes of indices, so an index on [A, B, C] and an index on [C] can be intersected to support a query with [A, C].

## Problem

Given N fields, determine the minimal indices needed to make all possible queries on those fields efficient. That is, minimize the total number of fields indexed. There may be more than one minimal set.

Note: the order of fields in the query doesn't matter since the query analyzer can reorder these fields to be as optimal as possible before running the query.

## Input/Output

Input is a single positive integer and the output should consist of clearly-delimited sequences.

## Examples

A variety of output formats are shown here to demonstrate what I mean by "clearly-delimited sequences".

N: 1

[0]

N: 2

AB
B

N: 3

[['A', 'B', 'C'], ['B', 'C'], ['C']]

['AB', 'BC', 'CA']

To elaborate on the first example in this N=3 case, the first index covers a query with all three fields, index intersections cover all choices of two fields, and index prefixes cover all queries with one field.

Note: for N=5, the obvious pattern does not hold; the indices ABCDE BCDE CDE DE E do not enable an efficient query on A, C, E.

## Meta

I am really hoping this doesn't boil down to [A, B, ..., X], [B, ..., X], [C, ..., X], ... [X]. I haven't taken a look at the N=4 case yet though so I don't know if this pattern holds.

Thankfully, the pattern breaks down for N=5.

# N-bonacci from a Seed

An N-bonacci sequence is a Fibonacci-like sequence where the N previous terms are added to get the next term. The Fibonacci series is a 2-bonacci sequence.

Given a list of integers L of length l and an integer n, output the first n digits of the l-bonacci sequence starting with the sequence L.

# Input

Input is a list, array, delimited string, stream, etc of integers, and an integer. Input is flexible, provided L and n are separable. It is guaranteed that n >= 0, and l >= 1.

# Output

Output the first n digits of the l-bonacci sequence starting with L. Output is flexible here also: a list, array, string, stream, etc.

Samples:

[1,1], 5       --> 1, 1, 2, 3, 5
[0,1,2], 1     --> 0
[10,1,-1], 10  --> 10, 1, -1, 10, 10, 19, 39, 68, 126, 233
[-1,0,1], 0    --> //no output, or empty output
[-1], 3        --> -1, -1, -1
[-1,-2,1,0], 9 --> -1, -2, 1, 0, -2, -3, -4, -9, -15

This is , so smallest in bytes wins.

Related

• You'd probably need to explain what an l-bonacci sequence is. That said I'm not sure this isn't a dupe of the related challenge you posted since at least some answers (including mine) would be able to be reposted with [1]*n replaced with L and n replaced with len(L). – FryAmTheEggman Aug 27 '19 at 14:42
• Closely related: codegolf.stackexchange.com/q/70476/31716 – James Aug 27 '19 at 14:58
• n <= l seems like an odd restriction, which your test cases don't always follow. If that is an actual requirement, this would be L[:n] in Python, which I don't think you want. – Hiatsu Aug 28 '19 at 13:56
• Hmm. I'll axe n <= l then and change it to n >= 0. – bigyihsuan Aug 28 '19 at 17:37

# Solve a cubic equation code-golf

(Is this really not a duplicate?)

• Apparently not. I can find multiple quadratic equation challenges: 1; 2; 3, but there doesn't seem to be any cubic equation challenges yet. – Kevin Cruijssen Sep 13 '19 at 9:35
• Sounds like it might be a dupe of either codegolf.stackexchange.com/q/154001/194 or codegolf.stackexchange.com/q/11694/194 – Peter Taylor Sep 13 '19 at 10:58
• @PeterTaylor The first challenge only asks for integer solutions, while yours has some constraints that this challenge might not have. – Erik the Outgolfer Sep 13 '19 at 13:48
• @EriktheOutgolfer, I said "might" because "solve" is so vague that there's no way of knowing what the challenge is. And I don't think my challenge has constraints so much as licence to not have to be accurate to 1ulp. It's true that cubics can't be as ill-conditioned as higher-order polynomials, but there are still some nasty cases. – Peter Taylor Sep 14 '19 at 8:48
• @PeterTaylor I think there's a lot of subtleties in specifying challenges like this. I'd really like to push solvers to do something like the cubic formula rather than some generic method to solve or brute-force a polynomial equation. It's also fair that it's hard to judge anything from just a title. I'll try writing something up later and would be happy to hear your thoughts. – xnor Sep 14 '19 at 8:53
• Regarding Peter's comment about the ambiguity of not including the description, one important thing to include is whether we must at least find one solution, the real solutions, or all solutions (I'm in favor of the last option). Also, "pushing solvers to do work" can be as simple as encouraging them to implement an algorithm that's more than just a built-in solving function (including the built-in solution for reference doesn't hurt, if it exists). – Erik the Outgolfer Sep 14 '19 at 15:38
• @EriktheOutgolfer Can you explain why you like the last option of requiring all solutions? I had thought a bit about this and was leaning pretty heavily to only asking for one solution because it gives less advantage to generic solvers (even non built-ins) over writing a formula, and it means one never has to output a complex solution for languages that don't support them natively. – xnor Sep 14 '19 at 19:47
• The "less advantage" restricting the output to one solution gives is simply a need for the answer to just pick one of the solutions it has found, in the worst case. Also, there are some cases where there are only complex solutions. If you want to account for such languages, you will need to add a guarantee that the equation will have at least one real solution, and none of the aforementioned cases will ever be input (there's some ambiguity about this currently). – Erik the Outgolfer Sep 14 '19 at 19:53
• @EriktheOutgolfer Doesn't every cubic equation have a real solution? I'm not intending to include ones where the leading coeff is zero so it's really quadratic. – xnor Sep 14 '19 at 19:55
• Hm, must've been thinking of something else (I'm currently doing other stuff). And yeah, a cubic equation $ax^3+bx^2+cx+d=0$ is cubic precisely because $a\ne0$. – Erik the Outgolfer Sep 14 '19 at 19:58

# Randomize $$\SL_n(\mathbb R)\$$

Given a positive integer $$\n > 1\$$, return a random element from $$\SL_n(\mathbb R)\$$.

### Details

• $$\SL_n(\mathbb R)\$$ is the set of $$\n \times n\$$ matrices with determinant $$\1\$$.
• In theory the output must cover the whole $$\SL_n(\mathbb R)\$$ (that is, if the RNG you're using was perfect and we could actually represent real numbers).
• We don't require an uniform distribution.
• Instead of real numbers it is sufficient to work with floating point numbers.
• I suspect the interesting solution you have in mind is to start with the identity and do random row operations. But maybe it's shorter to just generate a random matrix and divide the first row by its determinant, even if your language means you need to implement det yourself? – xnor Sep 14 '19 at 7:30
• On second thought, random row operations is probably shorter to golf. And there's probably niftier ways to it like generating the LU decomposition, or taking the exponential of a trace-zero matrix. So this definitely seems like an interesting challenge to golf, at least for languages that don't make it too easy. A technical issue that might be worth addressing is whether it's OK to never be able to generate some probability-zero subset. For instance, what if the method only generates matrices with distinct eigenvalues? I think this should be allowed since floats can't reach everything either. – xnor Sep 14 '19 at 7:43
• @xnor Thanks for you input! This task actually came up when I was trying to test a function I've written and I ended up using the random matirx/scale by determinant solution. I see your point about the zero-probability sets. The only problem I see is that it is hard to define it in a way that cannot be abused: As matrices with floats have only rational entries you could argue that we can only represent a zero-probability set in the first place. (If we use this exact wording.) So I'm not actually sure how to specify this. – flawr Sep 14 '19 at 17:49
• I think it would be OK to say that in theory, the output must cover cover the whole space except for some probability-zero subset of it. I see what you're saying about floats being measure zero, but I think this wrinkle is already present and covered by you saying "in theory" and that floating points suffice for reals, so I don't see the change making it more abusable. I also realized that the code probably should be allowed to fail with theoretical probability zero, like if you go the determinant-scaling route, you could get det zero. Maybe defaults cover this already, I'm not sure. – xnor Sep 14 '19 at 19:53
• As a side thought, it could be possible to avoid these annoying real-representation issues by changing the challenge to generating integer examples or ones over F_2, but I suspect this won't allow as wide a variety of solutions. – xnor Sep 14 '19 at 20:01
• "We don't require an uniform distribution." -- would a Dirichlet distribution be allowed? – Jonathan Frech Sep 17 '19 at 7:38
• @xnor Even though $\mathbb{F}_2$ allows the possibility for bit-fiddling in solutions, possibly being interesting in their own rights. – Jonathan Frech Sep 17 '19 at 7:43
• @JonathanFrech Can you elaborate how you'd define a Dirichlet distribution over $SL_n(\mathbb R)$? I'm not familiar with this distribution and I don't quite see how we can apply it as the support seems to be defined as $(x_1,\ldots,x_n)\in \mathbb R^n$ with $\sum_i x_i =1$. – flawr Sep 17 '19 at 7:43
• I though of something along the lines of $P[X\neq\mathrm{id}]<\epsilon$, where $X$ models the output and $\epsilon$ represents machine accuracy, however on second thought this case is covered by your theoretical surjectivity requirement. – Jonathan Frech Sep 17 '19 at 7:50

# Battleships TDM

In this (not so simple) game of commanding a battleship, you are tasked to defeat the opposing team. Cooperation is essential in order to win the battle.

Each ship starts with $${500\cdot\bigg\lfloor\frac{10}{\log{\frac{n}{3}}}}\bigg\rfloor$$ health (rounded down), where n is a number of players. At 30 players, it is 5000.

## Setup

The game starts with a square map of length 50+3n. On top and bottom there is 15% of the width, in which the players' ships will spawn. The rest of the map will be prodedurally generated with islands.

The sample map looks like this:

## Phase 1: Issuing commands

On your turn, your program will be given a file input.txt located in the program's directory, with following format:

TURN=(turn number)
SIZE=(size of the map)
YOUR_SHIP=(first 6 chars from SHA1 hash of your ship's name; in case of conflicts a random one will be generated)
POS=(position of your ship in 0,0 format)
TERRAIN:
(21x21 square of characters, centered on the ship)
PROXIMITY:
(line-separated list of ships within 10 squares, with its properties separeated by semicolon)
CHAT:
(line-separated history of text sent by teammates from the last and current round)

For example:

TURN=21
SIZE=110
YOUR_SHIP=acf44a
YOUR_TEAM=1
HEALTH=3231
POS=64,121
SPEED=3
DIR=NW
TERRAIN:
.....................
###.............x....
##.................##
(etc.)
PROXIMITY:
bd439a=1;69,132;S;3 (ship's id, team, position, direction, speed)
43351f=2;78,112;NE;4
(etc.)
CHAT:
58ab38@21: ENEMY_SHIP 582af2 @ 142,62 NE 3
902dd1@20: 033b2c 4 92,62 SW 1
(etc.)

The map shows . for water, # for land, x for wrecks, 1 and 2 for ships belonging to particular team.

Your program is allowed 3 actions per turn. The actions are:

NONE - do nothing
TURN_LEFT - rotates ship counterclockwise by 45 degrees
TURN_RIGHT - rotates ship clockwise by 45 degrees
SPEED_UP - increases speed by 1. At speed 5 it is ignored.
SPEED_DOWN - decreases speed by 1. At speed -1 it is ignored.
MESSAGE=message - sends a message to chat
FIRE=x,y - fire a projectile in specified location. Can be done only once per turn.
The cannon has range of 25. Issuing a command which exceeds it is ignored.

For example:

TURN_LEFT
SPEED_UP
FIRE=62,69

must be written to output.txt. After each round the file is cleared.

## Phase 2: Movement phase

All ships in random order move forward defined by their speed.

• If ship hits the land or wreck during movement, the ship stops and takes damage worth 50x of ship's speed.

• If ship hits the map border, same situation applies.

• If ship hits other ship, it is considered ramming:

• If rammed from the front, both ships receive damage worth 100x sum of ships' speeds. Both ships stop.

• If rammed from the back, rammed ship receives damage worth 20x difference of ships' speeds. Rammed ship moves one step forward and ramming ship ends its movement.

• If rammed from the side, rammed ship receives damage worth 100x speed of ramming ship, while the ramming one receives 50x. Ramming ship stops.

• If rammed at the angle, rammed ship receives damage worth 50x speed of ramming ship, while the ramming one receives 20x. Ramming ship stops.

• If the rammed ship is friendly, ramming ship receives 1 point of friendly fire.

## Phase 3: Firing phase

In the same order ships fire from the cannons (if any). If the cannon hits a target:

• That is within range 10: Shots deal 500 + 0-99 damage

• That is beyond range 10: Shots deal 500 + 0-99 damage + 0-99 damage for each unit beyond 10th (up to 2084 total damage at range 25)

• If the target is friendly, the damage is 0 and shooting ship receives 1 point of friendly fire.

• There is 5% chance to make a hit critical: The total damage is tripled and shooter recieves 1 critical point.

• If it is a fatal blow, it is considered a destruction:

• The fatal blow dealer receives a fatal point.

• Attacker with most dealt damage receives a kill point (it may be the same ship as the dealer).

• Everyone else with a hit receives an assist point.

• If it is a solo kill, the dealer receives 2 of each points instead.

## Phase 4: Checking conditions

Each ship is considered a wreck if:

• Health reaches below 0 HP,

• Ship gains 5 friendly fire points.

Wrecks remain on the map, but they are removed from the queue and program of such ships is being not executed.

Game ends whenever entire team gets destroyed or after 1000 turns, in which the points are being calculated as follows:

• 1 point for each 10 damage dealt

• 500 points for each kill

• 200 points for each fatal blow

• 100 points for each assist

• 150 points for each critical hit

• -250 points for each friendly fire hit

• 1000 points for each winning team member

• Points for achievements (names are just for decoration):

500 (awarded once) Beyond the horizon - Hit on enemy from 13 sq or more
500 (awarded once) Maximum range - Hit on enemy from 23 sq or more
500 (awarded once per participant) Coordinated attack - 3 or more ships attacking the same target
500 (awarded once) Hammer - Ram a ship on full speed
500 (awarded each time) - Survive a critical hit
1000 (awarded once per participant) Anihilation - Both ships getting destroyed in headfront ramming

The ship with most points after 10 games wins.

## Code

The controller code is here.

## Rules

• store data in files within its own directory

• communicate with teammates through the team's chat

• read files outside its scope

• disrupt the communications

• Attack friendly ships on purpose

• Copy other competitors' functionality (No duplicates)

## Sandbox questions

• I'm not sure whether to allow the challenge in any usual language or require one specific (in this case Java 8)?
• Wouldn't be achievements unnecessary? If not, could be any added/modified/removed?
• Are there some rules that require clarification?
• What does "procedurally generated with islands" mean? Could you provide a small example map? What does "15% of the width where players' ships spawn" mean? Are they distributed randomly, or packed into a corner (or do they have a choice)? – the default. Sep 7 '19 at 15:18
• @someone 1. "Procedurally generated islands" I meant. 2. Added. 3. Area reserved for ships to spawn. 4. Randomly across the spawn area. – CuttingChipset Sep 7 '19 at 18:48
• a) Ship health and particularly map size, in my opinion, scale in a weird way with participant count. b) I would highly recommend avoiding file I/O in favor of sending data to programs via STDIN and reading their actions via STDOUT. c) Additionally, I would recommend using a ubiquitous I/O format, like JSON or XML. This will reduce the amount of boilerplate code that the participants will have to write. Moreover, it would prevent d) the problem of newlines in chat. e) What order are the programs asked for output in? This is important for chat, for example. – Alion Sep 7 '19 at 22:32
• f) Does the damaging behavior differ depending on whether the ramming ship hit the front-right/left or the back-right/left? g) Does ramming a friendly ship deal damage to it? Please make that clear. h) Does solo-killing also provide 2 assist points? I'm guessing it doesn't, but it's not clear either. i) Shooting right at the current position of an enemy ship seems ridiculously effective. You've got a 50% chance to hit by definition, while all the other methods necessarily have less, since the ship can dodge. I can see very few edge cases. That's just my opinion, however. – Alion Sep 7 '19 at 22:47
• j) I misunderstood the "1000 points for each winning team member" the first 2 times I read it. "1000 points for member of the the winning team" is clearer in my opinion. k) Coordinated attack achievement is perhaps a bit unclear, but I can't seem to put into words why that is. l) 10 games is not an awful lot. While I understand that you don't want to run this for too long, this game does seem to be a bit random. m) Attacking friendly ships "on purpose" is difficult to define rigorously, and is already punished by the game, which makes it Emo Wolf-y. All in all I find the rule unnecessary. – Alion Sep 7 '19 at 23:03
• n) It would be lovely if the challenge was available for all standard languages. I would definitely not participate if it was Java-only. p) How are teams chosen? Randomly every game? r) I strongly recommend making a dedicated chat room for participants once the challenge hits main - you seem to be looking forward to coordinated plays, and I don't think they're possible without an agreed-upon communication format, which in turn is unlikely to develop without any group discussion amongst players. – Alion Sep 7 '19 at 23:19
• Correction for j) - I meant "1000 points for each member of the winning team". There's also a general problem of weird English present in all parts of the spec, but as long as it's understandable (which it is), there shouldn't be any problems here. Anyway, looking forward to the updated spec, and of course to the challenge itself. Good luck! – Alion Sep 7 '19 at 23:26
• @Alion The main issue is that I have no idea how can I run programs from multiple languages, so my controller could capture it and interpret all actions within reasonable time (since I'd have to run each program thousands of times to make an action). I don't want to end up copying/pasting/calculating everything by hand each turn, which could take a week or more to finish the game. The further points will refer to this one as I go – CuttingChipset Sep 8 '19 at 5:32
• a) True, but the ship health has at least been addressing the time constraints. I could end up with some long functions for both of those anyway. b) STDIN/OUT capture issue. c) Haven't thought of this. d) Oh? e) What order? I'm not sure what do you mean. f) FL/R and BL/R deal the same damage. g) Uh, yes. h) Would have to think about it. i) Do you suggest any alternatives? l) Time constraints, again. n) Here we go back to the issue with multiple languages. p) Random every game. r) I would if I had the power to do so. Currently I don't. (BTW English is not my first language) – CuttingChipset Sep 8 '19 at 5:48
• I've cobbled together a simple demo of how a language-agnostic controller could work. As I don't write Java, I used C# instead, but the code should be mostly readable for a Java developer as well. You will certainly need to find the Java equivalents of the methods and classes used, but I would be very surprised if Java doesn't support something akin to what I've done in C# at all. I also assumed Windows all throughout. Here's a demo.. Contains the C# controller and the files required for a sample Python entry. – Alion Sep 8 '19 at 12:27
• a) After understanding what the ship health function does, I don't have a problem with it anymore. The map size, however, grows quadratically with the ship count. d) You've defined chat as a line-separated history of messages. But what happens if an entry decides to put a newline into its message? e) Are the programs queried for actions in a consistent order? If so, what is the initial order? Random? Additionally, being early in the call order is a huge disadvantage, since most of the messages received will be from the previous turn, as I understand it. – Alion Sep 8 '19 at 12:36
• i) It's really difficult to come up with any alternatives from my position. I don't have access to your vision of the game. Inevitably I end up overhauling the battle system one way or another and remain unsatisfied with it. Considering previous challenges, however, I can't say for sure if this really is a notable flaw. – Alion Sep 8 '19 at 12:42
• Alion's point (b) is addressed at the execution speed issue you raise. See github.com/pjt33/ppcg36515 (linked from the KotH tag wiki) for an example which supports Java submissions natively and other languages by stdin/stdout communication. Another issue which Alion has touched on briefly is the team business: it needs to be clear how the teams will be assigned. – Peter Taylor Sep 9 '19 at 8:34
• I have slightly edited your equation, feel free to roll back if you disagree. – Jonathan Frech Sep 17 '19 at 8:03

# Black And White Shirts 3

This is the third in a series. The first can be found here, and the second here. The premise is similar to the first two, but with some changes and a new goal.

Assume I have some number of black shirts and some number of white shirts, both at least 1. Both colors of shirt have a non-zero Vividness. All shirts of a given color start with the same Vividness.

Every day, I pick out a clean shirt to wear, and it becomes dirty. Once I run out of all clean black shirts or all clean white shirts, I wash all my dirty shirts of both colors and start over. Clean shirts do not get washed. Whenever a shirt gets washed, its color changes based on its Vividness and the Vividness and colors of the other shirts being washed, then its Vividness goes down by one to a minimum of 0. All things being equal, over time, all shirts will generally tend towards a shade of gray.

If a shirt is ever closer to the opposite color (eg. a black shirt looks light gray), it becomes a shirt of that color.

When picking which shirt to wear, I choose the shirt which is either closest to black or closest to white. If there is a tie, I choose the one with the highest Vividness.

# Challenge:

Take in an arbitrarily long sequence of two indicators (eg. b b w w b w b b w b...) representing my choice of shirt to wear on that day. Continue execution until either my last black shirt or my last white shirt loses its last vividness. Once this occurs, stop consuming input and print out the colors of all shirts.

## Inputs:

Number of black shirts, number of white shirts, Vividness of black shirts, Vividness of white shirts, and a sequence of shirt selections of arbitrary length at least long enough for one color of shirt to run out of Vividness (can be considered infinitely long). The selection can be represented by any two characters (eg. b, w).

## Output:

Color of all shirts, sorted from lightest to darkest, as a percent of how close it is to white, rounded to the nearest whole percent. A completely black shirt is 0, and a completely white shirt is 100.

## Color changing:

The color of a shirt tends towards the average of all shirts' colors in the wash. How close it gets depends on its own Vividness.

TODO: Determine if this rule is necessary (I don't think it is): If all shirts in the wash have 0 Vividness, none of them change color.

When washed, shirts are changed based on the following pseudocode algorithm (some of which may not be necessary for your simulation):

struct shirt {
int vividness
float color
}

func washShirts(shirt[] allDirtyShirts) {
totalVividness = allDirtyShirts.sum(shirt => shirt.vividness)
if (totalVividness == 0)
return

averageDirtyColor = allDirtyShirts.sum(shirt => shirt.color * shirt.vividness) / totalVividness

for each shirt in allDirtyShirts
{
shirt.color = (shirt.color * shirt.vividness + averageDirtyColor) / (shirt.vividness + 1)
if shirt.vividness > 0
shirt.vividness--
if shirt.isBlack && shirt.color > .5
shirt.isBlack = false
else if !shirt.isBlack && shirt.color < .5
shirt.isBlack = true
}
}

Make sure that all shirts base their calculation on the Vividness and color values of all other shirts before the change. Perform no rounding beyond normal floating point restraints within your language of choice (within reason) during any calculation. Only round the value during output. When rounding for output, choose any convenient rounding method among:

• truncating (always round down)
• rounding to the nearest integer
• .5 rounds up
• .5 rounds down
• .5 rounds to the nearest even integer

## Test cases:

Note: These test cases use rounding to the nearest even integer. Your output may vary in some cases.

1 2 1 1 w b
100 75 25

3 3 2 1 w b w b w w w w w w w w
71 71 71 14 14 0
#note that processing would stop after w b w b w. The remaining input would be ignored.

#todo: more test cases

# General rules:

• This is , so shortest answer in bytes wins.
• Default I/O rules apply

## Title: Lossless Compression

Implement the following lossless compression pseudo-algorithm and its decompressor; scored by the number of bytes output by your compression algorithm, after you've put your source-code for both the compressor and decompressor through your own implementation of the compressor algorithm, described below:

## Algorithm Description

Essentially, this is a simple dictionary compression algorithm (which isn't always guaranteed to compress the output, especially for short inputs). You want to scan for sequences of characters that appear multiple times, and then create a lookup; in order to shorten the input string.

The input string to generate your score must contain all characters in your submission; however the program must also be capable of compressing successfully the test-cases below.

The dictionary (which forms part of the output string) can use any other character as an indexer character, except a single separate character of your choice (| in my examples), which is reserved.

The output format should be a sequence of IndexcharValuestring| (i.e. index character, followed by the value string, followed by the separator - collectively "the dictionary"); followed by the compressed input string.

## Some examples:

1. testRattesttestRattesttesttesttestRattest -> _test|+Rat|_+__+____+_ - because test is represented by _ and Rat is represented by +; then the compressed string is shown. each section is separated by the character |.

To decompress, simply replace _ with test and + with Rat in the output (after the last |).

The dictionary entry can also be nested - for example:

ininputinputininput -> &in|*&put|&**&* because in is represented by & and &put is represented by *

Exactly which characters end up being grouped will depend on your compression algorithm. For example, the previous string could also be output as &input|in&&in&, or &in|*put&|&&**&put

Note that the recursive compression could go even further, but at this point the output gets longer again:

ininputinputininput -> &in|*&put|^&*|^*^

It's up to you how much compression your algorithm performs, as long as it matches or beats the longest of the outputs for each example in this post.

1. AbcAbcDefDefDeggggggggggggggggggAbc

could output:

-Abc|£De|#£f|*ggg|--##£****-

1. Well I've heard there was a secret chord That David played and it pleased the Lord But you don't really care for music, do you? Well it goes like this, The fourth, the fifth, the minor fall and the major lift! The baffled king composing Hallelujah. Hallelujah Hallelujah Hallelujah Hallelujah

could output:

+ you|/ing |-ed |%pl|¬it|#or|^th|)ll|(he|"T( |$t( |*We) |_Ha)elujah|*I've (ard t(re was a secret ch#d That David %ay-and ¬ %eas-$L#d But+ don't rea)y care f# music, do+? *¬ goes like ^is, "four^, $fif^,$min# fa) and $maj# lift! "baffl-k/compos/_.____ 1. %Testttttttttt%%%%%%%% could output:$%%%%|_ttttt|%Tes__

must output:

(because no compression is possible)

## Acceptance Criteria

In order to class as valid, the algorithm you create should:

• Meet the algorithm description above
• Be able to match or beat the length of the test cases above (shorter = better)
• Output from the compressor (and therefore input for the decompressor) should be in the format shown (dictionary and separator characters may differ). Input for the compressor (and therefore output for the decompressor) should also be in the format shown.

## Sandbox Notes and Questions

• Is the challenge clear?
• Is the scoring mechanism fair? I'm still not sure how to deal with characters vs bytes
• Is the spirit of the challenge clear? (i.e. to actually make an algorithm, rather than simply beat the examples and get the best score)
• Is there any interest in this challenge?
• I'm confused: not only does the output format explanation use = but the question explicitly says that = is reserved, and yet none of the examples use it. – Peter Taylor Apr 3 '18 at 14:37
• @PeterTaylor I changed my mind half way through, sorry fixed now – simonalexander2005 Apr 3 '18 at 14:53
• Mostly irrelevant nitpick: no lossless compression algorithm is guaranteed to make its input smaller, a result often known as the "no free lunch theorem." – Nathaniel Apr 11 '18 at 7:54
• @Nathaniel Good to know, thanks – simonalexander2005 Apr 11 '18 at 9:25
• How would you score a submission containing characters different from the ones allowed in input? – Leo Apr 11 '18 at 9:38
• @Leo yes, it does limit the source somewhat, doesn't it? What would be better then? - increasing the range of characters allowed to allow any character except, say, | (and the dictionary has to key on missing characters only); or keep the limited input and also limit people's source? – simonalexander2005 Apr 11 '18 at 13:29
• One possibility would be letting people choose the separator character (instead of fixing it as |), and requiring that a submission works on inputs consisting of all the required characters plus all the characters contained in the submitted source. This should give enough freedom to make solutions possible in more languages. – Leo Apr 11 '18 at 22:22
• @Leo helpful, thanks. Updated - hope it's clear – simonalexander2005 Apr 12 '18 at 15:42
• Are you sure that you want to work on characters and not bytes (and thus facing multiple complicated codepage issues)? Especially consider that the program itself is compressed. – user202729 Apr 12 '18 at 15:56
• @user202729 could you expand on what issues would occur? I'm not quite sure I get what the issues could be here – simonalexander2005 Apr 17 '18 at 13:51
• The "program" is most likely an arbitrary byte string, and thus it may be invalid UTF-8. – user202729 Apr 17 '18 at 15:29
• @user202729 but it will be convertible to something, using a custom code-page of some sort. Even if it's UTF-16 or some other encoding, right? – simonalexander2005 Apr 18 '18 at 8:52
• I still feel that it's open to abuse. We had reasons to score by byte count instead of character count. – user202729 Apr 18 '18 at 8:59
• @user202729 The scoring is a byte count; just the program uses characters to compress/decompress. The compression ratio for someone using a golfing language is likely to be very poor, compared with say someone using ><> or even VB.NET - but it's the job of the coder to decide which language will get them the best score for the question; right? – simonalexander2005 Apr 27 '18 at 12:38
• Brute force is the best – l4m2 Apr 29 '18 at 11:16