# What is the Sandbox?

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

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

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

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

• How are tags added to questions? – guest271314 Jan 9 at 7:51
• @guest271314 You can use this markup to create a tag in a draft: [tag:code-golf] – DJMcMayhem Aug 29 at 15:19
• Why no featured anymore? Can't we have it auto-added or something? – JL2210 Sep 26 at 15:57
• @JL2210 We now have a permanent info box that links to the Sandbox, so the featured tag isn't necessary – caird coinheringaahing Sep 29 at 13:43
• I think the sentence 'replace the post here with a link to the challenge and delete it' may specify that the deletion should be done immediately . – AZTECCO Oct 5 at 19:39

# 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 at 21:24
• Can there not be multiple correct solutions? – Adám Jul 8 at 21:26
• Will the echo ever begin at the first element? – Adám Jul 8 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 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 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 at 21:33
• @Adám have updated rules and test cases from your comments. Thanks! – 640KB Jul 9 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 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 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 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 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 at 6:27
• Good question, let's go with 797 @streetster – PrincePolka Jul 10 at 10:59
• @streetster 719.. i counted the boxes wrong, good thing I began in the sandbox – PrincePolka Jul 11 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 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 at 11:38

Posted here.

# Brute-force the switchboard

Posted here!

• It looks good to me! I'll remove my old comments now. Also, thanks for using the sandbox! :) – FryAmTheEggman Jul 18 at 20:55
• @FryAmTheEggman Thank you so much for the suggestions! I'll keep it up a bit longer in case anyone else remembers or finds a dupe. – Rin's Fourier transform Jul 18 at 20:56
• Poor guy indeed having to do binary counting instead of using a Gray code... – Neil Jul 18 at 20:56

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

## Examples

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 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 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
!$37<CR^deswz¤«®¶·ÃÏÔâéîā --> CODEGOLFANDC?GCHALLENGES !5=BShqt¢¹ÇÍÜôþēĠİĵĹňŞţŵƉƑƖƢƣƽǖǚǩǰȃ -> THEQUIC?WNFOXJUMPEDOVERTHELAZYDOGS  ## Notes • The difference between the Unicode points for the string will always be greater than 0. • The input's Unicode points will be strictly increasing. • You may output in lowercase. • The non-alphabet character does not need to be consistent. • I suggest using less than or equal to 26, so that Z can be represented – wastl Aug 1 at 12:59 • @wastl Yeah, done – MilkyWay90 Aug 1 at 16:07 • What stops us from just adding 97 to all the differences, since outside that range is non-alphabetical? – Jo King Aug 2 at 4:09 • @JoKing Nothing stops you from doing that. – MilkyWay90 Aug 2 at 4:54 I've had an idea for a coding challenge, but I'm a). not 100% certain it's not already been done, and b) not sure if some of the golfing specific languages will trivialise it too much. Basically the premise is thus: The scoring for your question is achieved in the following fashion: 1. All comments are removed from your script 2. +1 point per character in your script 3. +1 point per character in your output 4. The following algorithm applied to the concatonation of your script and your output: • +1 point the first time a character shows up • -1 point the second time a character shows up • -2 points the third time • -4 points the fourth time • -8 points the fifth • double ad infinitum 5. The scores for character repetition above are cumulative. So, a would yield 2 points (1 for length, 1 for first occurance of character). aa would yield 2 points (2 for length, +1 for first instance, -1 for second instance). aaa would yield 1 point (3 for length, +1 for 1st, -1 for 2nd, -2 for third) Rules: • No standard loopholes I'm also not even sure what I would tag this question as. • As far as tagging goes: code-challenge. – Sriotchilism O'Zaic Aug 2 at 14:12 • One issue is I could just write a comment with 65,000 unicode characters in it. – Redwolf Programs Aug 2 at 14:45 • @RedwolfPrograms ah so there needs to be a rule excluding comments – Scoots Aug 2 at 14:49 • Hmm and I also need a creative way to say “script cannot simply be print ‘abcdefg...’ – Scoots Aug 2 at 14:51 • @Scoots Well, that's where it gets complicated. This could also be considered a code-bowling challenge in a way, since the goal is to make the longest source code (or output) possible. The issue with code bowling questions is that they often have exploitable loopholes like comments, regexes, variable names, etc. I'd find a way to work this into the scoring, such as reducing points for source code lengths and adding points for output length – Redwolf Programs Aug 2 at 14:52 • @RedwolfPrograms that falls afoul of a for loop and a given language’s chr function. This will take some thinking. – Scoots Aug 2 at 14:57 • @Scoots Maybe base it on some other element, like execution time? – Redwolf Programs Aug 2 at 14:59 • @RedwolfPrograms Nah that's too contingent on circumstances outside our control (how busy is the server when it runs the script etc)... I'm going to think on this for a while. Maybe something creative with exclusives between script and output – Scoots Aug 2 at 15:45 • @Scoots I haven't seen too many good posts based on getting the longest source code/output, and I'll be excited to see something new. Good luck! – Redwolf Programs Aug 2 at 16:00 • I only see a scoring system, but no challenge. Also, in languages like Unary or Whitespace it would be trivial to get arbitrarily large negative scores - and in most languages you can add effective no-ops. I think this kind of thing has been tried before, but it may not have made it past the sandbox because it has big problems which can't really be fixed. – Peter Taylor Aug 5 at 7:53 • @PeterTaylor The challenge would be to get the highest possible positive score of course, but sadly my thinking has led me to concur with the rest of your statement. Sandbox being the filter it is supposed to be :) – Scoots Aug 5 at 16:58 This puzzle is based on this Math.SE post. 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 durability. All shirts of a given color start with the same durability. 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 durability goes down by one. Immediately after washing, if the durability of a shirt reaches 0, it must be thrown out. When picking which shirt to wear of a particular color, I always choose a shirt with the highest durability of that color to ensure even wear and tear among shirts. # Challenge: Take in a sequence of two characters of arbitrary length (eg. b b b w b w 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 is thrown out. Once this occurs, stop consuming input and halt execution immediately. Note that the program must not consume any more input than is required before halting. ## Inputs: Number of black shirts, number of white shirts, durability of black shirts, durability of white shirts, and an arbitrary number of two single characters, your choice (eg. b and w) ## Output None. The program must simply halt when the last shirt of either color is thrown away. ## Test cases 1 1 1 1 b 1 999 1 999 b 1 999 1 999 w w w w w w w w b 2 999 1 999 b w w w b 2 999 2 999 b w w w b w b w w w b 5 3 6 1 w w w w w b b b b b b b b b b b b b b w  # General rules: • This is , so shortest answer in bytes wins. • Default input rules apply for the first four arguments. For the arbitrarily long input sequence after the first four arguments, input must come from a source which can provide input one character or byte at a time, of theoretically infinite length, such as STDIN or some other stream. • How exactly are you going to test that only a certain amount of input has been used? – Jo King Aug 8 at 5:04 • Typically you should address concerns made in Sandbox before posting to main. – Jo King Aug 8 at 5:31 # Calculate mobile data coverage ## Background You've been hired by the HQ of Vodafizon - a relatively new mobile network provider interested in spreading to the global market. In particular, your job description involves working as a marketing rep to produce ads for each country, where you give a figure of the data coverage, as a percentage, in that country. You get this data from the data scientists, but you've started to notice a pattern: the number always seems to be 98%, 99% or 100% (which, in your experience, seems to be far too high). Despite your trust in Vodafizon, you seem to find this suspicious, so you write your own program to investigate, ensuring maximum precision, even implementing your own floating-point and circle rasterization algorithm to minimize error. You end up making a 112KB monster of a program, but the result confirms your suspicions: these figures are, for the most part, made up by the data scientists, to try and exaggerate their claims. When you mention this discovery to a coworker, they act surprised at first, but later tell you to keep quiet: upper management probably know about the forgery, and in fact endorse it. Telling them that you know their dirty secret could will result in losing your job. But here's the thing: you know that advertising these fake numbers could result in massive lawsuits to Vodafizon, the effects of which could result in you getting laid off. You know you can't risk getting fired, but just using the data scientists' figures could be disastrous in the long term. After consulting Workplace SE, you come up with a plan: keep using your program, but hide it from your superiors. The only issue is, that the data scientists responsible for providing you the data also happen to be the makeshift sysadmins in Vodafizon HQ, so your program can't attract too much attention to itself. 112KB is far more than Vodafizon uses on average (they prefer to split code into lots of tiny files), so when filtering through by file type, the sysadmins will easily see this file as potentially twenty times larger than all the others. So clearly, you need to compress it, without sacrificing the accuracy. ## Input The input will consist of a nested array of form [[x, y], [x, y]] (or alternatively an object of form [{"x":x, "y":y}, {"x":x, "y":y}]) of line segments, in clockwise order, defining the border of a country. The input will also contain a nested array of form [[x, y, strength], [x, y, strength]] (or an object of form [{"x":x, "y":y, "s":strength}, {"x":x, "y":y, "s":strength}]), which will describe the location of the mobile data towers, and the strength: the radius (or diameter, you can request either in your answer (but not both)) of the circle in which that given tower provides mobile data. ## Output Your program should output an approximation of the mobile data coverage of the input given. Of course, this is impossible to get perfect (unless you live in Indiana, that is), so you need to provide an approximation, but while reducing your byte count as much as possible. Note that your program must halt by itself before 5 seconds of runtime (for any test where the number of towers is less than or equal to 500, and the number of edges is less than 100), or alternatively continuously provide output such that once it is stopped after 5 seconds, the last output will be taken as the result. ## Scoring Like I mentioned, my program also needs to be small, therefore size will factor into the equation. So, to score your program: • Get the number of bytes, B • Run your code with the randomly-generated test cases provided by tests.py in this repo, and save the ref outputted. • Run your outputs through score.py, providing the ref at the start. The last input you will be asked for will be B. Get the score outputted by score.py, and post it in your answer. # Sandbox • Is my background too long? • Is my scoring system too long-winded? I intend to use a complex algorithm (which I have mentally worked out, but not coded yet) which essentially creates a weighted average of all of the scores as a percentage of a value which is correct to 16 decimal places. Is referring people to some code, instead of telling them the algorithm, standard practice? I don't want to spend ages describing a confusing algorithm, when I could just write a program to do it. • Is this challenge not a duplicate? Is is unclear in any way? ## Broken mouse This is just an idea, I have not elaborated it. My mouse accidentally fell to the ground, and now there is a double click for each of my single click(which makes window-closing very hard to do). :( Most computer screens have a higher resolution ratio than 16x12, but let's assume that my computer screen has a 16x12 resolution ratio. Example: A Window looks like this: 0-----OX | | --------  The number 0 is the indicator of the window. O is a dragging button that allows windows to be moved. X is a closing button that closes the window. (You can not resize windows.) Assume that there is a window below that window looking like this: 1-----OX | | --------  If I click X, I will close both windows. However, what should(or must, if appropriate) I do if I only want to close the first window? I can move my mouse to the O tab and drag the window around by using mousedown. After 1 drag to the right: 10-----OX || | ---------  Now I can click the X to close the window 0 after I click the O button again to remove the dragging effect. (Note that there is the window "1" below that window.) Wait, I changed my mind and wanted to close the window 1. What should I do? I should click the number 1; then, the window 1 goes to the top and the X button shows. Now I can click the X button to close the 1 window. For reference, this is the TUI commands I used(when the mouse starts at 0x0): 0-----O >>>>>>.>.<<<<<<<.>>>>>>.  What should I do if I want to close the windows that I specified? (Output the TUI instructions.) (Your score is -(code length + output); you want to keep your score as high as possible.) ## TUI Instructions • ^v<>: Move the mouse up, down, left, or right • .: Mouse down+mouse up (i.e. click) • What does the input look like? – TheOnlyMrCat Aug 12 at 21:35 • I have no idea. – A _ Aug 13 at 4:36 • Output for what (set of) input? – user202729 Aug 16 at 4:49 • @The Obviously a list of coordinates of the input windows... – user202729 Aug 16 at 4:49 • Is this always possible? If the frontmost window is as large as the screen, by dragging the "O" you cannot make the lower-leftmost cell appear. What if the "X" of the desired window is there? – user202729 Aug 16 at 4:51 • I guess I will make the windows draggable for at least 1 direction and at most 4 directions. (The window is always smaller than the screen.) – A _ Aug 16 at 4:59 • Oh I see, otherwise output impossible to avoid this situation. – A _ Aug 16 at 7:00 # I mainly need help with scoring as I want to encourage use of esolangs. I also would like to know how to improve the answer-ability of this question in languages that don't specifically have defined functions # Church booleans A church boolean is a function that returns x for true and y for false where x is the first argument to the function and y is the second argument to the function. Further functions can be composed from these functions which represent the and not or and xor logical operations. # Challange Construct the church booleans and and not or and xor church gates in a language of your choice. # Scoring The total length of all of the code required to make church true and false in your language and the and not or and xor church gates excluding the functions name. (for example, false=lambda x,y:y in python would be 12 bytes). You can reuse these names later in your code. # Pseudo code Examples: true(x, y) -> x false(x, y) -> y and(true, true)(x, y) -> x and(true, false)(x, y) -> y # ... etc  • instead of functions, you should also accept full programs. I also don't understand what your examples represent(is and supposed to be a curried function?) – SuperStormer Aug 16 at 20:43 • @SuperStormer and returns a church boolean which is a function which is then called with variables x and y and returns x or y based on whether that function is the true or false church boolean. In the examples I was just trying to get across the nature of church gates and church booleans without answering the question. I wanted to break it up into discrete functions for readability and to ensure that the question is actually being answered correctly – Ryan Schaefer Aug 16 at 20:46 • I'm not really sure it's possible to make this work for all languages, except by just operating on lambda calculus expressions with no actual significance within the language, but that aside you definitely don't need anything additional to encourage esolangs on this site! – Unrelated String Aug 16 at 20:55 • @UnrelatedString as far as fit for this site goes do you think there is anything I should add to improve the question? – Ryan Schaefer Aug 16 at 20:58 • Esoteric languages usually don't support function as first-order object very well, but they usually have eval so it may work using some "function" representation. – user202729 Aug 17 at 6:46 • Otherwise I don't think there is a problem. – user202729 Aug 17 at 6:46 # Solve All the Rubik's Cubes! I want to solve a Rubik's Cube. Unfortunately, I am blind, and my friend doesn't know how to solve a Rubik's Cube, so I just make one move at a time and ask my friend if it is solved. This generally doesn't work very well, so I would like to know a specific thing I could do to increase my chances of eventually fixing it. Also, I don't like memorizing things, so please keep your solution as short and simple as possible. ## Rules • I cannot see the cube or anything about it. • The only thing my friend will tell me about the cube is whether or not it is solved. • My friend and I are fully willing to wait until the heat death of the universe to solve this, if necessary. • I don't have a great memory, so keep your instructions as short as possible. • I can feel around the cube enough to turn whatever face you tell me to turn in whatever direction. • I can turn the cube in my hands. • I can memorize anything you give me, but I won't like it. ## Solution Format Give me a description of turns to do on my Rubik's Cube, to be repeated endlessly (or until I solve it). F: Turn the front face clockwise B: Turn the back face clockwise R: Turn the right face clockwise L: Turn the left face clockwise U: Turn the top face clockwise D: Turn the top face clockwise x: Turn the cube so the top face becomes the front y: Turn the cube so the left face becomes the front z: Turn the cube so the left face becomes the top  ' can be appended to any of these commands to make them go in the opposite direction. Also, to make things easier, you can give me inner repetitions. Write these as {...commands...}*4  where 4 is the number of times it is repeated. Inner repetitions can be nested. ## Scoring Non-memorability: • Each turn gives one point. • For nested repetitions, double the point value of everything inside the repetition and add the number of times I do it. Effectiveness: • Any sequence of moves on a Rubik's cube will eventually return to the initial state. The effectiveness is how many turns are required before this happens (roughly equivalent to how many states it passes through). Total score = non-memorability / effectiveness Solutions that are easier to remember are probably better than solutions that are hard to remember but will be solved. Lowest total score wins. ## Questions: • Will people actually answer this question? • Is the specification clear enough? • This is my first question. Is there anything else I need to consider before posting? • This sounds like an interesting question, however it may actually be a better fit for puzzling.stackexchange.com. Either way, it's not entirely clear what the end goal is; Am I trying to find the series of moves that will make it likely for the cube to be solved quickly (on heatdeath timescale), or am I looking for a series of moves that garuntees it will be solved eventually? Also see (similar but not duplicates I'm pretty sure) math.stackexchange.com/questions/1694536 and math.stackexchange.com/questions/184760 – Shelvacu Aug 19 at 10:36 • I'm looking for something easy to remember, with a reasonable chance of eventually solving it. This doesn't have a definite answer and should focus more on space optimization (golfing) (the existing Hamiltonian Circuit is probably very difficult to remember and would score poorly), so it might not fit as well on Puzzling. – Hiatsu Aug 19 at 20:48 • As written, I agree with Shelvacu that this is for puzzling. This is still a programming site, so here it would be better to ask for a program to output the solution. But that's probably necessary anyway, given that the fully expanded solution will have at least 43.252.003.274.489.855.999 moves. – Peter Taylor Aug 20 at 15:38 • @PeterTaylor Actually, it would most likely be between 34,326,986,725,785,600 and 43,251,683,287,486,463,996. This is basically the Devil's Algorithm: a set of moves that when applied, repeatedly if necessary, will eventually return a Rubik's Cube to a solved state regardless of the starting configuration. – Kevin Cruijssen Aug 27 at 9:35 # Get the number of upvotes of your own answer Write a piece of code which makes a request to codegolf.stackexchange.com and prints the, up to date, number of upvotes to the specific answer in which you've posted that piece of code. As a test case I'll post a (poor!) answer below (obviously only in the real question). This is just a random idea I had when reading some other code golfing challenges, and I thought I'll post it here to see if it will fly. • Standard procedure(although weird, it is inevitable): Post a placeholder answer, copy the URL, and then make a request to that URL. (Although how can I access the number of votes?) – A _ Aug 20 at 13:59 • Yes, it would inevitably involve editing your answer (unless you embed a unique string in your answer just to find it...?). I admittedly have not tested this yet. I’ll have a play in python and make sure it’s not too hard to extract the information about the number of upvotes... – MarcinKonowalczyk Aug 20 at 14:08 • I recognise this would be a longer than usual challenge for core golf, but I thought exactly that would maybe make it interesting. – MarcinKonowalczyk Aug 20 at 14:12 • Can you define "core golf"? – A _ Aug 20 at 14:18 • I'm afraid it's already done before 3 years ago, so it would be closed as a duplicated. – Kevin Cruijssen Aug 20 at 14:21 • Thank you for using the Sandbox and finding out it was a duplicate rather than posting it on main first. – MilkyWay90 Aug 20 at 19:19 • No worries. I came up with it all by myself so I’m still happy. ;) Also, @A__ “core golf” was, of course, a typo. – MarcinKonowalczyk Aug 20 at 20:29 ## Talk interpreter "Talk" is a baroquified accumulator-based language that is created in order to make it difficult to put on Try It Online. The "Talk" language has 4 commands: • 00 If the accumulator is 0, set the accumulator to 0. • 01 If the accumulator is 0, set the accumulator to 1. • 10 If the accumulator is 1, set the accumulator to 0. • 11 If the accumulator is 1, set the accumulator to 1. ## Input: • The input can be taken via any acceptable input method by our standard I/O rules. • The input will always be a sequence of the commands above. • The program will take an input that is either 1 or 0 to set the accumulator to. ## Output: • On the end of a command execution, the accumulator is outputted implicitly. ## Rules: • The input has to be a single string or character list, and splitting it in parts of size 2 is part of the challenge. • As this is , the shortest answer, in bytes, wins. • So we take two inputs? The starting 0/1, and the sequence of commands? Since you state I/O is flexible, would for the commands a list of 2-character strings be allowed (i.e. ["00","01","11","11","01"])? Or does the input have to be a single string or character list, and splitting it in parts of size 2 is part of the challenge? – Kevin Cruijssen Aug 19 at 8:02 • Um, commands 00 and 11 don't seem to do anything, while the other two seem to be just 'set the accumulator to 0/1' – Jo King Aug 19 at 8:07 • The commands 00 and 11 was added in order to avoid uninteresting abuses like directly printing the last character of the code. – A _ Aug 19 at 13:42 • Why would this be difficult to put on Try It Online? Does the accumulator ever do any accumulating? – Shelvacu Aug 19 at 19:21 • This will overlap with the existing talk.tryitonline.net. – A _ Aug 20 at 0:16 • Um, it's not that hard to change the name slightly. Languages like ><>, /// and ??? already have url friendly names – Jo King Aug 21 at 6:49 • Do you know how to change the name "Talk" slightly? – A _ Aug 21 at 7:04 • @Shelvacu, I imagine that it would be difficult to persuade Dennis that a "language" this useless is worth space on his server. – Peter Taylor Aug 23 at 7:45 ## Normalized Malbolge to Malbolge translator In this task, you will write a program/function that takes a Normalized Malbolge program and outputs the resulting Malbolge program. (This is a secret tool that all Malbolge programmers are using!) ## Input A data structure that (somehow) represents a Normalized Malbolge program. ## Output A data structure that represents the resulting Malbolge program. ## Examples jpoo*pjoooop*ojoopoo*ojoooooppjoivvvo/i<ivivi<vvvvvvvvvvvvvoji: (=BA#9"=<;:3y7x54-21q/p-,+*)"!h%B0/.~P<<:(8&66#"!~}|{zyxwvugJ% jjjj*<jjjj*<v ('&%#^"!~}{XE jjjjjjjjjjjjjjjjjjjjjjj*<jjjjjjjjjjjjjjjjjjjjjjjj*<v ('&%$#"!~}|{zyxwvutsrqpnKmlkjihgfedcba_^]\[ZYXWVT1|


## 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 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 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 at 15:33

# BotNets KotH

Controller, Example and Submission Template now added

flavor text not yet written

This is a web-based JS KotH where submissions have 2 parts, a Worker Bot and a Controller Bot. The goal is to have the most gold at the end of the game, by killing other bots and collecting gold found on the grid, while navigating the grid and surviving.

# Worker Bots

A Worker Bot is a class(ES6 or ES5) based on this format:

class YourWorkerBot extends WorkerBot {
performAction(message) {}
sendMessage(x, y, surroundings) {}
}


Each botnet has 20 Worker Bots. For every botnet, its worker bots are

### Method Descriptions:

• constructor(index): sets the color that the controller displays the bot as
• performAction(message): returns an action(described below).
• sendMessage(x,y,surroundings): x and y are zero-indexed coordinates. surroundings is a flat array of the 5x5 area around the bot. returns message(string) to send to controller bot

### Actions

Each move is formatted as a 2 element list([action, param]) where action is a string

• Movement: formatted as ["move", square] where square is an integer that represents the square you want to move to, using the same index as the surroundings object. You can only move one square orthogonally or diagonally. Moving onto a square with a coin will collect the coin.
• Kill: formatted as ["kill", square] where square is an integer that represents the square you want to attack, using the same index as the surroundings object. You can only kill a bot one square orthogonally or diagonally. If you kill a square with no bot, you do nothing. You get half the coins(rounded down) of the bot you attacked.
• EMP: formatted as ["emp",undefined]. It causes all bots including itself in the 7x7 surrounding area can't move next turn. This costs 3 coins.
• Any invalid action is treated as you doing nothing.

### Surroundings

The surroundings object will be a flat array of the 5x5 area around you, starting from the top left corner and going left to right and top to bottom. The grid below shows how the indexes of the array map to the actual grid area. Each square will be either a string, where "B" is a bot, "C" is a coin, "E" is an edge(not a valid move target) and "" is empty.

 0  1  2  3  4
5  6  7  8  9
10 11 12 13 14
15 16 17 18 19
20 21 22 23 24


# Controller Bot

A Controller Bot is a class(ES6 or ES5) that extends the following class:

class YourControllerBot extends ControllerBot{
constructor(locations){
super(locations)
this.storage=""
}
sendMessage(messages,index){
return ""
}
}


Each botnet has only 1 Controller Bot.

### Method Descriptions

• constructor(locations): locations is an array of the initial locations([x,y]) of the worker bots.sets initial storage value
• sendMessage(messages,index): messages is a list of lists of the messages sent by all the worker bots(not just your own), always in the same order and grouped by botnet. returns message to its worker bots whose index is index.

# The Game

The arena will be a 100x100 grid with 100 random coins scattered around it. Each game will have 1000 rounds and will have up to 15 randomly selected botnets. Every round, 10 coins will spawn at a random unoccupied spot. Every worker bot will get 1 turn per round. Each botnet's worker bots will perform an action in the same order for the entire game, but the order in which botnets take turns is randomized every round. Every turn, all the worker bots' sendMessage methods will be called(not just the worker bot taking the turn). After that, the controller bot's sendMessage method will be called. Finally, the worker bot's performAction method will be called and the action will be executed. This will repeat for every worker bot in a round.

# Scoring

Each botnet's score is the sum of the coins collected by each of the worker bots. Botnets are ranked by most score.

# Controller(WIP)

https://botnets-koth.firebaseapp.com

# Example

function sampleBotnet() {
class SampleControllerBot extends ControllerBot {
constructor(locations) {
super(locations);
this.storage = "";
}
sendMessage(messages, index) {
let surrondings = messages.find(message => message[0] === index)[1];
let otherBot = surrondings.findIndex(
(square, i) =>
square === "B" && [6, 7, 8, 11, 13, 16, 17, 18].includes(i)
);
if (otherBot !== -1) {
return ["kill", otherBot];
}
let coin = surrondings.findIndex(
(square, i) =>
square === "C" && [6, 7, 8, 11, 13, 16, 17, 18].includes(i)
);
if (coin !== -1) {
return ["move", coin];
}
let validMoves = [6, 7, 8, 11, 13, 16, 17, 18].filter(
x => surrondings[x] === ""
);
return [
"move",
validMoves[Math.floor(Math.random() * validMoves.length)]
];
}
}
class SampleWorkerBot extends WorkerBot {
performAction(message) {
return message;
}
sendMessage(x, y, surroundings) {
return [this.index, surroundings];
}
}
return {
name: "SampleBotnet",
color: "red",
controllerBot: SampleControllerBot,
workerBot: SampleWorkerBot
};
}

#Submission Template
javascript
/* eslint constructor-super:0,no-this-before-super:0,no-unused-vars:0*/
import ControllerBot from "./src/scripts/ControllerBot.js";
import WorkerBot from "./src/scripts/WorkerBot.js";

//copy the part below
function yourBotnet() {
class YourControllerBot extends ControllerBot {
constructor(locations) {
super(locations);
this.storage = "";
}
sendMessage(messages, index) {
return [];
}
}
class YourWorkerBot extends WorkerBot {
performAction(message) {}
sendMessage(x, y, surroundings) {}
}
return {
name: "YourBotnet",
color: "",
controllerBot: YourControllerBot,
workerBot: YourWorkerBot
};
}


# Rules

• Standard Loopholes apply
• Bots cannot modify or add global variables
• Bots cannot call controller functions or other bots' methods
• Bots cannot read or modify other bots storage
• Bots may not access the internet
• I may disqualify any bot which does anything I deem to be cheating.

# Sandbox

• Is the bar to entry too high?
• Can the current turn/round system be improved?
• Any better names for the 2 bots/title?
• Is there enough room for creativity?
• Would it be better if I merged the 2 classes into one class?
• Is there anything broken with the spec?
• How many workers per controller, and how many controllers per game? Also, are controllers supposed to be able to message to all workers, or just their own? – Unrelated String Aug 12 at 4:05
• @UnrelatedString should be fixed – SuperStormer Aug 12 at 13:25
• performAction(surroundings, message) { return eval(message); } sendMessage(surroundings) { return JSON.stringify(surroundings); } There are, of course, countless other ways to circumvent the size restrictions. I also find said restrictions quite brutal. Additionally, I don't see the point of worker-side storage. Finally, the whole document is difficult to read - giving a short summary of the goal at the beginning would go a long way. Nitpick: it's "surroundings", not "surrondings". – Alion Aug 16 at 10:46
• Since your latest revision is "fixed spec": a) The WorkerBot class is invalid - calling super there is a syntax error. Do you want to show the base class that should be extended, or a template of how to extend said class? The second option makes more sense in my opinion, although the text right above seems to indicate otherwise. b.1) Under "Controller Bot", what is index? How is it chosen? b.2) What do bots that don't have the specified index receive as the message? b.3) Are there duplicate worker bot indexes possible? If not, please fix sendMessages descripiton. – Alion Aug 18 at 8:21
• c) Under 'The Game', sendMessages instead of sendMessage for controller bot. d) I'm worried about the split between worker bot and controller bot. I don't see how it would be anything but a minor nuisance under the current rules. Previously it was code-golf, but that's gone now. I'm also aware that it is supposed to be the essence of this challenge, so I'm hoping there's just a big misunderstanding somewhere. Perhaps it'll become clear once (b) is addressed. – Alion Aug 18 at 8:24

# 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 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 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 at 12:29
• @PeterTaylor that work better? – Ryan Schaefer Aug 23 at 13:22

# 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 at 14:42
• Closely related: codegolf.stackexchange.com/q/70476/31716 – DJMcMayhem Aug 27 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 at 13:56
• Hmm. I'll axe n <= l then and change it to n >= 0. – bigyihsuan Aug 28 at 17:37

# Is there enough room to stack the statues?

Inspired by this stack of little statues that are currently on my desk at work, given to me by my colleagues from Sri Lanka when they visited The Netherlands:

## Challenge:

Input:

You are given two inputs:

1. $$\statues\$$: a multi-line string (or character matrix), containing only the characters \n|-# (where the # can be another character of your own choice)
2. $$\height\$$: an integer

Output:

Two distinct values of your own choice indicating truthy/falsey; so yes, 1/0 is allowed as output in languages like Java/C# .NET and such (relevant forbidden loophole).
The output will be truthy iff both of these are truthy:

1. The statues can be stacked
2. The total height of all stacked statues is $$\\leq height\$$

Statues input example:

      ##|
####    |
# ##
#  #  |##
----  |######
|   ###
|##   |##   #
|## - |######
# |####


The | and - represent the bases of the statues. So with the input above, we'll have the following statues:

       ####
## #
## ##
####   #  ##
# ##  ## ###  ##      #
#  #  ## ###  ##  #   #
----  ------  --  -  --


How can the statues be stacked?

When stacking statues, we can only stack statues with a width of the base that is $$\\leq\$$ the width of the top of the statue beneath it. So with the statues above, these are all possible pairs of how we could stack two statues on top of each other:

####
# ##    ##
#  #    ##      #        #
----    --      -       --
####    ####    ####    ####    ##
## #    ## #    ## #    ## #    ##    #      #
## ##   ## ##   ## ##   ## ##   --    -     --    #    #
#  ##   #  ##   #  ##   #  ##   ####  ####  ####  -   --   #
## ###  ## ###  ## ###  ## ###  # ##  # ##  # ##  ##  ##   -
## ###  ## ###  ## ###  ## ###  #  #  #  #  #  #  ##  ##   #
------  ------  ------  ------  ----  ----  ----  --  --  --


One possible complete stack keeping that in mind could therefore be:

 #
-
#
--
##
##
--
####
# ##
#  #
----
####
## #
## ##
#  ##
## ###
## ###
------


Which has a total height of 18. So, if these statues would be the input, as well as a given target-$$\height\$$ of $$\\geq18\$$, the output would be truthy.

## Challenge rules:

• You can use a different consistent character other than # for the statue border if you want (other than |- \n). Please state which one you've used in your answer if it's different than #.
• You are allowed to take the $$\statues\$$ input in any reasonable format. Can be a multi-line string, a list/array/stream of strings, a character matrix, etc.
• You can assume statues are always separated by at least one space/newline from one-another, so something like #|#| isn't possible.
• It is possible that a smaller statue is within the rectangular boundaries of another oddly shaped statue. For example, this is possible:
# ##
- ##
##
####
# #
----

• You are allowed to pad the statues input with trailing spaces.
• You can assume all statues will only be placed on top of each other, and never next to each other if the top of a statue is large enough to hold two adjacent statues with small bases, or if it could fit on a smaller ledge. For example, these towers of statues aren't possible:
                        #
#                     # #
#--                     - -
####                    ###
----                    ---
Statue on lower ledge   Two statues next to each other on top of single statue

• You can assume the top and base part of a statue is always a single piece, without any gaps. So a statue like this wouldn't be possible:
#  #
----


But a statue like this is possible:

#
#  #
----

• You can assume the base determines the width of a statue. So it's not possible to have a statue like these:
#######
#####
####     ###
---     --


## General rules:

• This is , so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
• Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
• Default Loopholes are forbidden.

## Test cases:

Truthy test cases:

20
##|
####    |
# ##
#  #  |##
----  |######
|   ###
|##   |##   #
|## - |######
# |####


Falsey test cases:

10
##|
####    |
# ##
#  #  |##
----  |######
|   ###
|##   |##   #
|## - |######
# |####


# Sandbox questions:

• Should I make the statues always solid without inner spaces, so it's slightly easier to parse?
• Any edge cases I should think about in the rules/test cases?
• Any suggested test cases?
• If the top of a statue is wide enough, can you put two statues on top of it? – Hiatsu Aug 30 at 23:52
• @Hiatsu Oh, that's a pretty good question. I think I will add a rule that will disallow it, to not complicate it too much. Thanks for asking though, hadn't considered that! :) – Kevin Cruijssen Aug 31 at 9:20
• Related – Shaggy Sep 1 at 16:02
• Another thing that should probably be cleared up: Can the base and top row/column consist of multiple parts? (e.g. is a 5x5 square with the top, bottom, left and right middle square respectively missing a valid statue?) – ar4093 Sep 4 at 11:09
• Hm, is there a possibility that a statue can "fall into" a bigger statue if the latter's top has a wide enough hole on it and there's no other place to put the smaller one on? – Erik the Outgolfer Sep 4 at 12:36
• @ar4093 & ErikTheOutgolfer Added some rules to prevent this. I have the feeling the rules are becoming a bit large with all this blacklisting of statues which aren't possible, though. – Kevin Cruijssen Sep 4 at 12:49
• This seems like two challenges now: sum of statue heights <= maximum height (trivial), and all statues can be stacked somehow (the fun part). Given the effort you've gone through to keep the first part trivial, you might just want to remove it. – Hiatsu Sep 4 at 15:38
• @Hiatsu You might be right. Will probably change it later on to actually stack the statues. Will the input format and irregular shapes be different enough from this challenge in that case? I personally think it will, but I'd like some other opinions before I change it. – Kevin Cruijssen Sep 4 at 16:58

# 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 at 20:01
• "We don't require an uniform distribution." -- would a Dirichlet distribution be allowed? – Jonathan Frech Sep 17 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 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 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 at 7:50

# Solve a separable differential equation

A first order separable ordinary differential equation is (arguably) the easiest type of differential equation to solve, and takes the form of

$$N(y)\frac{dy}{dx} = M(x) \\ y(x_0) = y_0$$

For two given functions $$\N(y)\$$ and $$\M(x)\$$ and an initial condition $$\y(x_0) = y_0\$$.

Your task is to take $$\N(y)\$$, $$\M(x)\$$ and $$\y(x_0) = y_0\$$ and output the solution to that differential equation.

## How to solve a separable differential equation

The differential equation

$$f(y)\frac{dy}{dx} = g(x)$$

can be solved through the following method:

\begin{align} f(y)\frac{dy}{dx} & = g(x) \\ \int{f(y)\frac{dy}{dx}dx} & = \int{g(x)dx} \\ \int{f(y)dy} & = \int{g(x)dx} \end{align}

Once the integrals have been calculated, we can remove one of the constants of integration, leaving the equation

$$F(y) = G(x) + c$$

where

$$F(y) = \int{f(y)dy} \\ G(x) = \int{g(x)dx}$$

After this, $$\c\$$ can be calculated by applying the initial condition:

$$c = F(y_0) - G(x_0)$$

and a final solution for $$\F(y)\$$ can be given.

## Challenge

You are to take in three inputs:

• The function $$\N(y)\$$
• The function $$\M(x)\$$
• A mapping from $$\x_0\$$ to $$\y_0\$$

The mapping can be defined in any reasonable way: a Python-style dictionary, a two-element array/tuple, two individual inputs etc. If you're not sure, ask. However, both $$\x_0\$$ and $$\y_0\$$ can be any real number.

The functions, in order to avoid having to focus on parsing mathematical input, will be limited to a type of Laurent polynomials - i.e polynomials in the form

$$p(x) = \alpha \cdot x^n + \beta \cdot x^{n-1} + \dots + \gamma + \delta \cdot x^{-2} + \epsilon \cdot x^{-3} + \dots + \zeta \cdot x^{-m+1} + \eta \cdot x^{-m} \\ \alpha, \beta, \dots, \eta \in \mathbb{R}, \:\: n, m \in \mathbb{N}$$

Notice that we'll never have $$\x^{-1}\$$ in the polynomial, and that because of this, the integrals will always be Laurent polynomials of the same form (with $$\x^{-1}\$$ included after integrating).

With inputs in this format, there are multiple ways you could represent them for input. As with the mapping, any reasonable representation is acceptable, and if you aren't sure, ask. However, here are some that are def]initely allowed (for the example $$\p(x) = 3x^2 + x + 6 - 2x^{-2} + 7x^{-5}\$$):

• Nested list: [[3, 2], [1, 1], [6, 0], [-2, -2], [7, -5]]
• A pair of lists of coefficients: [3, 0, 1, 6] and [-2, 0, 0, 7]
• A string representation: 3x^2 + x + 6 - 2x^-2 + 7x^-5
• etc.

Given these three inputs, you are to output the solution to the differential equation they represent.

In order to avoid having to algebraically manipulate your solutions to get into the form $$\y(x) = ...\$$, you can output two Laurent polynomials, in the same form as the input; one representing $$\y\$$ and the other $$\x\$$.

This is so the shortest code wins!

## Test cases

Both the MathJax and text-based inputs will be included for each example, where the text based will use the nested list input format above. In addition, I will walk through the first example for clarity.

In:
N = [[1, -2]]
M = [[6, 1]]
1 -> 1/25 = 0.04
Out:
y = [[-1, -1]]
x = [[3, 2], [28, 0]]


\begin{align} \frac{1}{y^2}\frac{dy}{dx} & = 6x \\ y(1) & = \frac{1}{25} = 0.04 \\ \\ \int{N(y)dy} & = \int{M(x)dx} \\ \int{\frac{1}{y^2}dy} & = \int{6xdx} \\ -\frac{1}{y} & = 3x^2 + c \\ -25 & = c + 3 \implies c = -28 \\ -\frac{1}{y} & = 3x^2 - 28 \end{align}

In:
N = [[2, 1], [-4, 0]]
M = [[3, 2], [4, 1], [-4, 0]]
1 -> 3
Out:
y = [[1, 2], [-4, 1]]
x = [[1, 3], [2, 2], [-4, 1], [-2, 0]]


$$N(y) = 2y - 4, \:\: M(x) = 3x^2 + 4x - 4 \\ y(1) = 3 \\ \:\\ y^2 - 4y = x^3 + 2x^2 - 4x + c \\ c = -2 \\ y^2 - 4y = x^3 + 2x^2 - 4x - 2 \\$$

In:
N = [[1, 0]]
M = [[3, 2], [2, 0]]
1 -> 0
Out:
y = [[1, 1]]
x = [[1, 3], [2, 1], [-3, 0]]


$$N(y) = 1, \:\: M(x) = 3x^2 + 2 \\ y(0) = 0 \\ \:\\ y = x^3 + 2x + c \\ c = 0 \\ y = x^3 + 2x \\$$

# Meta

• Is this clear enough? I'm worried too much is spent on MathJax and may not be very clear
• Is this a duplicate? I can't find anything, but you never know
• Any nice edge cases to add for the test cases?
• The tags are , and . Anything else?
• Any further feedback?
• "For two given functions" -- note that not even two integrable functions, the first being differentiable, meaning the ODE and 'solution' can be at least defined, necessarily lead to the above being a solution. – Jonathan Frech Sep 17 at 7:36
• @JonathanFrech I'm not sure I follow? – caird coinheringaahing Sep 18 at 7:37
• What I am trying to say is that I would expect there to be a condition on $N,M$ for them to be well-behaved in a sense. – Jonathan Frech Sep 18 at 10:01

# 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)? – someone Sep 7 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 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 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 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 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 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 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 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 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 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 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 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 at 8:34
• I have slightly edited your equation, feel free to roll back if you disagree. – Jonathan Frech Sep 17 at 8:03

I came across this little web game Drench Its a fairly mindless game , I wrote a small JS snippet to play this game for me in the background of my browser, it cycles through and clicks on the 6 possible moves

let ind =0;
let games =0;
let wins =0;
let lastMoves = "";
setInterval(function(){
if (jQuery('.moveNum').text() != lastMoves) {
lastMoves = jQuery('.moveNum').text();
ind++;
ind = ind%6;
jQuery('.pbutton:nth('+ind+')').click();
} else {
games++;
if ((jQuery('.moveNum').text()*1)) {wins++;}
jQuery('#myCanvas').click();
}
},200);


This Strategy wins slightly less than 3% of the time My question is, is there a more optimal strategy that will allow me to win a greater % of the time (without looking at the board)?

• Hi and thanks for using the sandbox! Though this is a bit unusual for this site, I think your question is on-topic, just far too broad. "Can I do better" just isn't something you can really ask on the SE network. I think the best way for you to move forward is to fully explain the game in the body of your post, and then score submissions based on their win percentage. – FryAmTheEggman Sep 21 at 19:37
• I really like the idea though - I think win% is the way to go – simonalexander2005 Sep 23 at 15:20
• Make this a code-challenge? To verify, you can run it for, for example, 500 times and calculate the winning percent? – HighlyRadioactive 20 hours ago

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

1. aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789 ?!.,;

must output:

aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789 ?!.,;

(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

Posted. I prefer to retain the content for potential issues.

## Duck, duck, gone!

Here is the (quite childish) Five little ducks song(it is not long):

Five little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only four little ducks came back.

Four little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only three little ducks came back.

Three little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only two little ducks came back.

Two little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only one little duck came back.

One little duck went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but none of the little ducks came back.

Mother duck herself went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
and all of the little ducks came back.


Your task is not to output this song. You should take a verse and output the next verse (the next verse of the last verse is the first verse).

## Rules

• Input/output will be taken via our standard input/output methods.
• The exact verse must be outputted, and there should be no differences when compared to the song lyrics. The input will not be different when it is compared to the song lyrics too.

## Examples

Mother duck herself went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
and all of the little ducks came back.


Expected:

Five little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only four little ducks came back.

Three little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only two little ducks came back.


Expected:

Two little ducks went out one day,
over the hills and up away.
Mother Duck said, "Quack Quack Quack Quack",
but only one little duck came back.


## Sandbox

• Is it detailed enough?
• Is the input/output rules clear enough?

• So a simple (no regex needed, case insensitive) string replacement FiveFour, FourThree, ThreeTwo, Two little ducksOne little duck, One little duckMother duck herself, fourthree, threetwo, two little ducksone little duck, only one little ducknone of the little ducks, noneall of? – Adám Sep 23 at 9:44
• Yes. (It seems quite repetitive, a better algorithm might be possible.) Do you think that outputting the whole lyrics is better? – A _ Sep 23 at 9:46
• No, it is no more interesting than 99 bottles etc. – Adám Sep 23 at 9:49
• You might replace the content with "posted" and a link now. – JL2210 Sep 26 at 10:58

# Hexdump quine

Your task is to write a valid quine where your program is in the form of a hexdump. Specifically, a hex dump in this format:

0000: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0010: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0020: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................
0030: 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00  ................


where:

• Each row starts with the $$\16\$$ times table in hexadecimal (0000, 0010, 0020, etc, until FFFF), followed by a : and a space
• The 00s represent the hex codes of each byte in your code, from 00 to FF, using whatever coding you like (UTF-8, Jelly, 05AB1E etc.).
• The .s represent the actual characters used. If the character is outside the printable ASCII range (char codes 32 to 127), the character is replaced with a ., otherwise the character itself is used

You are to take no input and to output only your source code, with an optional trailing newline. Your source code must be in the above hexdump format, meaning that it cannot be longer than 65535 (FFFF) bytes long in whatever encoding you're using.

This is , so the shortest code, in bytes, wins!

# Meta

• Is this clear enough?
• I don't believe this is a duplicate (I found this, but its quite different), but does anyone recognise this?
• The tags as , . Anything else?
• Any further feedback?
• I'm not really sure how this is 'quite different' from the linked challenge. The only significant change I can see is the rules for showing printable characters. – Jo King Sep 30 at 2:13
• I have to agree with Jo King. I don't see much of a difference, either. – AdmBorkBork Oct 1 at 15:31

# Polynomials Through Points

You will get a set of n Cartesian coordinates. You must output a polynomial going through all of the points.

## Input

• Points are 2-dimensional.
• You may assume that no two points share a x coordinate.
• You may take points as a tuple of pairs, or pair of equal length tuples.
• 1<n<1000

## Output

• For polynomial y=x^3+3*x^2+1, you may output as:
• y=x^3+3*x^2+1
• x^3+3*x^2+1
• y=x^3+3*x^2+0*x+1
• x^3+3*x^2+0*x+1
• y=x^3+3*x^2+x^0
• x^3+3*x^2+x^0
• y=x^3+3*x^2+0*x^1+x^0
• x^3+3*x^2+0*x^1+x^0
• y=1*x^3+3*x^2+1
• 1*x^3+3*x^2+1
• y=1*x^3+3*x^2+0*x+1
• 1*x^3+3*x^2+0*x+1
• y=1*x^3+3*x^2+1*x^0
• 1*x^3+3*x^2+1*x^0
• y=1*x^3+3*x^2+0*x^1+1*x^0
• 1*x^3+3*x^2+0*x^1+1*x^0
• [1,3,0,1]
• You may output any polynomial satisfying the condition.

## Rules

• Stabdard loopholes are forbidden.
• Any method approved by Standard I/O is allowed.
• This is code-golf, so shortest code wins!