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

To post to the Sandbox, scroll to the bottom of this page or click on the "Add Proposal" link below, and click "Answer This Question". Click "OK" when it asks if you really want to add another answer. Write your challenge just as you would when actually posting it. You may also add some notes about specific things you would like to clarify before posting it. Other users will help you improve your challenge by rating and discussing it. When you think your challenge is ready for the public, go ahead and post it, replace the post here with a link to the challenge and delete it.

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

# A Picture is Worth a Thousand Words

The average word is four characters/bytes long. So a picture, according to the old saying, is worth 4 kilobytes. But how complicated can that picture get?

Using any language or length of code you want, generate an image exactly 4,000 bytes in size with the highest possible entropy. You may use any standard image format. Your score will be the compression ratio when your image is compressed as a .zip file. For example, an image that compresses to 2,000 bytes will score 2, but if it expands to 4,100 bytes it will score 0.9756. Lowest score wins.

• What image formats are allowed? – wastl Aug 13 at 2:41
• @wastl All of them. – Purple P Aug 13 at 3:19
• should the program output to a file or can it print a list of bytes? – SuperStormer Aug 13 at 12:20
• Interesting challenge. .zip is a file format, not a compression method, though. You'll need to specify what compression method is used -- DEFLATE, LZMA, etc. -- because that could drastically affect the scoring. – AdmBorkBork Aug 13 at 12:51
• @SuperStormer It shouldn't matter as long as you upload the image file. – Purple P Aug 13 at 15:03
• @AdmBorkBork How about gzip? I would specify version 1.6 because that's what I have. – Purple P Aug 13 at 15:04
• If you say something like gzip 1.6 using DEFLATE with default settings that should probably suffice. – AdmBorkBork Aug 13 at 15:58
• I didn't test this but I feel that any uncommon image format of raw data will have the optimal score (assume the compressor is smart enough to store without compression) – user202729 Aug 16 at 4:42

tags: "code-golf", "ellipse", "geometry"

## Sandbox Questions

Is this a proper code-golf question?

A major challenge is: How to verify the computed shape? Numerical verification is impossible, since there are infinitely many possible solutions. Is there an easy way to plot xy-data online, or should I provide a script myself? Your suggestions are greatly appreciated.

### edit:

after 3 days of being posted here in the sandbox, I still have no clear answer to the above question. I therefore propose to ask participants to include their own plot in the answer, which they can make with whatever plotting tool they wish. If people feel inclined to cheating, they only fool themselves, don't they?

# Introduction

To create a circle you can stick a nail in a piece of board, put a loop of string around it and hold it taut with a pencil at the other end. Move the pencil and you get a circle. If you put the loop of string around two nails and move your pencil, you create an ellipse. But what happens if you use three nails, or four, or ten perhaps? It's gonna get ugly soon if you try this in real life, and that's where computers come in handy.

# Challenge

Your task is to write a program or function that accepts two inputs:

• A list of (x,y) coordinates (viz. the nails), of arbitrary length>2.
• The length of the rope.

And produces the following output:

• A list of coordinates of the poly-oval, which could be fed to a plotting-tool. Plotting the output does not need to be part of your program!

## Details:

• You may assume that the input coordinates form a convex shape (no inner points on which your program could crash).

• As coordinates, you can use tuples, pairs, complex numbers or even two separate scalars if you like.

• The output resolution (ie. the length of the list) is not so important, but is should give a fair representation of the real curve. In my experience, you'll need between 100 and 1000 points. For smaller rope lengths, you need an even higher resolution.

## Rules and scoring:

• This is code-golf, so shortest answer in bytes for each language wins.
• Standard rules and default I/O rules apply.
• Loopholes forbidden (of course).

# Example Input and Output

Provide at least one example input and output. Make sure they match your own description of what the input should look like.

Input can be any of the following:

P = [2+0j, -2+1j, -2-1j]

P = [(2,0),(-2,1),(-2,-1)]

X = [2,-2,-2] and Y = [0,1,-1]

Output should be in one of the following forms:

[0.862+1.591j, 0.703+1.668j, 0.527+1.729j, ...]

[(0.862,1.591), (0.703,1.668), (0.527,1.729), ...]

X = [0.862, 0.703, 0.527, ...], Y = [1.591, 1.668, 1.729, ...]

• "You may assume that the input coordinates form a concave shape" I think you mean convex. This is a very helpful assumption though, as you would otherwise need to calculate the convex hull before doing anything interesting. – Beefster Aug 13 at 22:05
• "How to verify the computed shape?" - Two possibilities: 1. don't worry about it and make this a graphical output challenge ; 2. specify a starting angle and angle step and require accuracy to within 2 decimal points. ... I personally would go with #1 – Beefster Aug 13 at 22:11
• @Beefster Thank you, I did indeed mean convex. As per your second comment, frankly I am not interested in how to write short plotting code, I am interested in the calculation itself. But thanks a lot for your help, I think I will post in a couple of days:) – Hermen Aug 14 at 16:28
• One solution would be to specify a pixel resolution and require that the density of output points should be sufficient that the maximum separation between the curve and the piecewise linear output should be half a pixel. Then you can compare the output with the output of a reference implementation by looking for separations of more than one pixel. – Peter Taylor Aug 20 at 15:55

## Black Hole Evaporation

Background: In empty space, occurring all the time, there are pairs of particles that appear and then, usually soon after, cancel each other out. At a certain distance from a Black Hole, it's possible that a pair of particles might spontaneously appear and, if the distance is just right, one of the particles will fall into the Event Horizon while the other escapes off into space, never getting a chance to cancel each other out. The exit of those particles is Hawking Radiation. Eventually, this process causes the entire Black Hole to evaporate away.

Challenge

Given a string of numbers, emit the negative of the single digit number closest to, in front of, the infinity symbol ∞ (the event horizon), and continue emiting it until there are no digits left in front of the infinity symbol. Then print the rest of the string masking each character uniquely and different from the masked character (burst of energy that might take place at the final instant), excluding any infinity symbols.

Test cases

Input:                      Output:
111∞4567                    -1 -1 -1 jkl;
3∞                          -3
3-145∞962                   -5 -4 1 -3 ™©®
4-567-9∞1-23                 9 -7 -6 5 -4 😐😈😎😻
2-1∞                        1 -2
34∞67∞89                    -4 -3 9876
-123∞456                    -3 -2 1 ♫♪#
6-6∞6                       6 -6 ä
48120∞                      0 (or -0) -2 -1 -8 -4
---5∞555                    5 オゼヰ


Challenge rules

• Anything after the first infinity symbol can be ignored as it has fallen into the Black Hole and we know nothing more about it anyway until after evaporation, where the information is a bit scrambled.
• The code should only expect numbers, negations, and infinity symbols. No decimal points or other symbols. The input can be an array, list, etc..., but each character must be separate, including the negation and infinity characters.
• A negation only applies to the single digit immediately after it. See the test cases above.
• You may mask the remaining characters after evaporation with any character set of your choice, as long as the resulting character is different from the masked character, and each character in the resulting output is unique. For languages limited to smaller character sets (or type constraints), characters may repeat after each possible unique character has already been utilized in the output.
• You may use the '_' symbol instead of the '∞' symbol.

General rules

• This is , so shortest code in bytes in its respective language wins.

• Standard rules apply for your answer with default I/O rules, so you are allowed to use STDIN (with the specification above)/STDOUT, functions/method with the proper parameters and return-type, full programs.

• Default Loopholes are forbidden.
• I'm thinking of expanding this to all alpha numeric characters. – ouflak Aug 7 at 19:04
• What does it do if there is a single number after the infinity symbol? – TheOnlyMrCat Aug 8 at 6:53
• I'll update the rules and the test cases. Curiously, I already sort of demonstrated that case by having nothing after the infinity symbol. Nice catch. – ouflak Aug 8 at 6:55
• If 121 remains after evaporation, is reversing that string an acceptable scrambling? – Adám Aug 8 at 7:21
• Any particular reason to use ∞? Adding Unicode into the mix is an unnecessary complication for many languages. Maybe allow substituting _? – Adám Aug 8 at 7:22
• @Adam, "If 121 remains after evaporation, is reversing that string an acceptable scrambling" Absolutey! Our understanding of what happens to the information after Black Hole evaporation is still under much debate. It is entirely possible that the result of scrambling might result in the same information. We just don't know. – ouflak Aug 8 at 7:46
• @Adam, "Any particular reason to use ∞? Adding Unicode into the mix is an unnecessary complication for many languages." Yeah I thought about that. It can even be excluding factor, which I don't like. I really want that infinity symbol though.... I'll have a think about it, but any suggestions like yours are welcome. – ouflak Aug 8 at 7:49
• @Adam, "If 121 remains after evaporation, is reversing that string an acceptable scrambling?". After re-reading through the Information Paradox, I think the answer is 'no'. '121' should definitely end up different. I'll have to find some way to re-word the challenge, and I can be talked out of this. This requirement seemed rather innocent, but as I'm trying to code this up in my head, it can get complicated. – ouflak Aug 8 at 8:01
• The connection between the background and the task is not very clear. The comment about information suggests that you have a much clearer idea which you haven't included in the question. There's no need to overload the question with back story, but a link to a more detailed explanation might make it feel less arbitrary. – Peter Taylor Aug 8 at 8:23
• @PeterTaylor, I've been mulling over your comment and I'm not sure what to include. Links to the Information Paradox or Hawking Radiation, or both? – ouflak Aug 8 at 8:41
• Probably both. AIUI, the infinity symbol represents the event horizon, the symbols to the left represent virtual pairs which become Hawking radiation, the symbols to the right represent the captured information, the emission of the inverted symbols to the left corresponds to the emission of Hawking radiation, and the shuffling of the symbols to the right corresponds to the information paradox. (I'm not sure without checking some reference why there's anything left to the right after evaporation). It would be good to sketch the correspondences and have some "Further reading". – Peter Taylor Aug 8 at 8:46
• @PeterTaylor, Ok thanks. The final stage of evaporation might release a detectable packet of energy (which has yet to be seen or is even theoretically certain), so that's kind of what that represents. There might be something left over afterwords, or maybe not. When I get the chance, I'll edit some links in and parenthesize some metaphors in there as well. – ouflak Aug 8 at 8:55
• @ouflak Regarding ∞ you can use it but allow substitution. Btw, _ is the infinity symbol in the J language. – Adám Aug 8 at 9:27
• @Adám, What about, "If your language has a built-in substitute for ∞, you may use that. If your language can't use Unicode, or use it efficiently, you may use the '_' symbol instead." Does that sound fair and inclusive enough? – ouflak Aug 8 at 10:03
• @ouflak What if your language's infinity is inf? That's three symbols, so it complicates matters a lot. "use it efficiently" is unclear? Does that include causing higher byte count? How about just: You may use the _ symbol instead of ∞. – Adám Aug 8 at 10:06

# Determine the minimal indices needed to cover all queries

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

## Background

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

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

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

## Details

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

### Compound Indices

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

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

### Index Intersection

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

## Problem

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

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

## Input/Output

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

## Examples

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

N: 1

[0]


N: 2

AB
B


N: 3

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

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


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

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

## Meta

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

Thankfully, the pattern breaks down for N=5.

## Up side down keyboard

Jono 2906 wants you to create a translator from plain Australian to up-side-down text after inventing a keyboard dedicated to typing up-side-down text, since they still want to demonstrate that their keyboard is powerful after failing to program in their keyboard.

However, they want your implementation to be typed with their own keyboard, since they also want to get used to programming using their keyboard.

## Input/Output

The whole ASCII character set mapped to their up-side down variation (the up-side down " is a double ,):

 !"#$%&'()*+,-./ 0123456789:;<=>? @ABCDEFGHIJKLMNO PQRSTUVWXYZ[\]^_ abcdefghijklmno pqrstuvwxyz{|}~ ¡,,#$%⅋,)(*+'-˙/
0ƖᄅƐㄣϛ9ㄥ86:;>=<¿
@∀qƆpƎℲפHIſʞ˥WNO
ԀQɹS┴∩ΛMX⅄Z]\[^‾
,ɐqɔpǝɟƃɥᴉɾʞlɯuo
dbɹsʇnʌʍxʎz}|{~


The rest of the characters are kept as-is(yes, the unprintable characters are in the ASCII character set). The characters that are larger than 0x7f will be mapped back by subtracting the character code by 128.

If you are using a character that is larger than 256, modulo the character's character code by 128 before checking the availability.

## Rules

• Input and output will be taken with our standard input methods.
• If you force Jono 2906 to change a key on their keyboard (allowing typing your specified character), you will get a penalty of +2 bytes for every key you add.

• I don't think I quite follow. Are we given a character as input and need to output the upside-down version? – AdmBorkBork Aug 27 at 14:06
• (1) I still find the question confusing even as to the basic functionality required. The "Input/Output" section seems to me to say that it's a Kolmogorov problem, but the "Rules" section talks about input. (2) If a character remapping is involved, the question should list Unicode codepoints for the characters in question, and should list test cases with Unicode codepoints. (3) Is the last rule saying that the program must work as is and after mangling? Or is it just a gimmick ("Post your code upside down, but it only has to work the right way up")? – Peter Taylor Aug 28 at 8:39
• "The rest of the characters are not kept as-is(yes, the unprintable characters in the ASCII character set)." should this not be there? As for that entire paragraph, if I understand correctly: unprintable characters < 33 (as well as 127) will be kept as is; printable ASCII characters displayed will be converted to upside down; other printable ASCII characters and any character above 127 will be modulo-128 before doing the same check. – Kevin Cruijssen Aug 28 at 9:24
• As for the last rule: we can only use those upside down characters in our source code, and when converting it to regular it should also work? So both programs ABC and ∀qƆ should work exactly the same? – Kevin Cruijssen Aug 28 at 9:25

## Wrong position

I typr re;atively accuratrly, but so,etimes I made a whole nlock of text illegible by shifting a key right. So I need a program that corrects my text back to its original meaning.

## Rules

• You have to left shift on a standard English QWERTY keyboard.
• Whitespace do not count for the procedure before left-shifting and are kept as-is in a standard left-shifting procedure. If the key is the leftmost letter/symbol on a keyboard(i.e. The ~key, Q key, A key, Z key.), the key is kept as-is. If you reach a control character while left-shifting (Caps lock and Shift), their effects will not be triggered and the character before left-shifting is kept.
• This is a contest; the shortest answer wins.
• Both the input and the output shall be given via our default methods.

## Representation of a subset of the QWERTY keyboard that you will need

The two lines connected are possible values of the key: shifted/unshifted.

~!@#$%^&*()_+ 1234567890-= QWERTYUIOP{}| qwertyuiop[]\ ASDFGHJKL:" asdfghjkl;' ZXCVBNM<>? zxcvbnm,./ (Space) (Space)  ## Input The input will always be a non-empty string conforming the rules above. ## Output The output will be the input string corrected to the originally intended meaning. ## Examples: Yjod ,sfr yjr, imjsppu/ -> This made them unhappy. vpfr hp;g -> code golf  ## Feedback I think this is not a duplicate; however, is any part of this challenge unclear or needs improvements? • I think you are mixing up left and right. Clearly, ~, Q, A and Z are leftmost keys, NOT rightmost. And your examples appear to be left-shifting, not right-shifting. – wastl Sep 7 at 11:27 • "I think this is a duplicate" - so why sandbox it? Or did a not go missing in editing? – Peter Taylor Sep 9 at 8:36 • Thank you. Predominantly my mouse was not working again, I didn't get around to fix this. – A _ Sep 9 at 8:56 • "sonetimes" and "vlock" are shifted the wrong way. – Hiatsu Sep 9 at 16:20 # Path to Path Rearrangement In the xkcd comic "Map of the Internet", a special fractal path was used, similar to this: 0 1 14 15 3 2 13 12 4 7 8 11 5 6 9 10  Ascii art version: -0---1 14---15--16 19--20---21 | | | | | 3---2 13---12 17---18 23---22 | | | 4 7---8 11 30---29 24---25 | | | | | | | 5---6 9---10 31 28--27---26 | 58---57 54---53 32 35--36---37 | | | | | | | 59 56---55 52 33---34 39---38 | | | 60---61 50---51 46---45 40---41 | | | | | 63---62 49---+---47 44--43---42 \|/  This path, known as the Hilbert curve, has some interesting properties. Among other things, it can be flipped diagonally without changing most of those properties. -0 3---4---5 58--59---60 63-> | | | | | | 1---2 7---6 57---56 61---62 | | 14---13 8---9 54---55 50---49 | | | | | | 15 12--11---10 53--52---51 48 | | 16---17 30---31--32--33 46---47 | | | | 19---18 29---28 35---34 45---44 | | | | 20 23---24 27 36 39---40 43 | | | | | | | | 21---22 25---26 37---38 41---42  Your task is to apply this transformation. Given a space on one path, find the corresponding location on the other. For example, the fourth space in the top path is located at (0, 2), which is the 14th space along the second path, so the correct output for 4 is 14. As with similar challenges, this can be done as: • An infinite sequence along the second path of the corresponding locations along the first path • A function/program that takes a numbered position on the first path and returns the distance to that point on the second path. • A function/program that takes a numbered position on the first path and returns all path 1 positions along path 2 to the point specified. The first 64 terms of this sequence (zero indexed, add one to each for one indexed) are: 0 3 2 1 14 15 12 13 8 11 10 9 6 7 4 5 58 57 56 59 60 63 62 61 50 49 48 51 52 55 54 53 32 35 34 33 46 47 44 45 40 43 42 41 38 39 36 37 26 25 24 27 28 31 30 29 18 17 16 19 20 23 22 21  This is code golf, so shortest code in bytes wins. ## Meta Questions • Do I need a better description of the paths? • Is the challenge itself clear? • Any other issues I should fix before posting? • The default output formats for sequence challenges can be found in the tag wiki – Jo King Sep 10 at 4:03 • (1) Related. (2) I don't find "Find the location along the second path of a point on the first path" at all clear. It seems to be talking about output in 2D. I think it would be clearer to say "Given an index on the first path, output the index of the same coordinate on the second path". And then give a worked example (e.g. 4 vs 14). – Peter Taylor Sep 10 at 10:53 # Is this number part of a Collatz Prime sequence? Each step of a Collatz Sequence can be summarized as: $$p_{2} = \frac{3*p_1+1}{2}$$ Where p1 is the input number, and p2 is the output number. You task is to find where both the input and output are primes. Here are some test cases: 1 -> (3*1+1)/2 = 4 : false 3 -> (3*3+1)/2 = 5 : true 5 -> (3*5+1)/2 = 8 : false 7 -> (3*7+1)/2 = 11 : true 11 -> (3*11+1)/2= 17 : true 15 -> (3*15+1)/2= 23 : false 91 -> (3*91+1)/2=137 : true 97 ->(3*97+1)/2 = 146: false  Output should be some truthy value, and false may be an error. • What is the definition defining? Is $p$ a Collatz prime iff it's a prime and $\frac{3p+1}2$ is a prime? If $p$ a Collatz prime iff it's a prime and $\frac{2p-1}3$ is a prime? Or is a prime Collatz if either of those conditions hold? – Peter Taylor Sep 13 at 10:56 • @PeterTaylor are they not the same thing? – Pureferret Sep 13 at 11:09 • Alternative phrasing: which of $p_1$ and $p_2$ are you calling a Collatz prime? – Peter Taylor Sep 13 at 11:11 • @PeterTaylor I mean $p_1$ – Pureferret Sep 13 at 11:22 • So neither the input prime nor the Collatz prime need to be prime? – Jonathan Frech Sep 17 at 7:56 • "Input MAY be non-prime, in which case the output is always false (see 15)" -- did you specifically define this behavior or why is the above the case? – Jonathan Frech Sep 17 at 8:00 • @JonathanFrech I'm (personally) only interested in going from prime to prime, but I wanted to define the haviour for non-prime input. When I say 'may be non-prime' I mean, it should be able to handle it, it's an allowed/expected input but not one that gives a True output. – Pureferret Sep 17 at 10:55 • To me it feels like an unnatural extra constraint. – Jonathan Frech Sep 17 at 12:54 • @JonathanFrech it's just defining how to behave with certain inputs. – Pureferret Sep 18 at 9:12 • Citing Exceptional edge cases; such out-of-place definitions are generally frowned upon. – Jonathan Frech Sep 18 at 9:56 • @JonathanFrech I've changed the initial ask, and now it shouldn't be an exception – Pureferret Sep 18 at 10:23 • Cf. A158709. – Jonathan Frech Sep 18 at 10:53 ## Maximize the Hello, world's in code permutations In this task you should output this exact string: hi orb (because Earth is a sphere). However, here is the catch: you must output as many hi orb's as possible in all of your code permutations. Identical permutations do not count(e.g. aa's permutations count as one permutation) Say you have a program abc that outputs this string. You should try your best to make acb, bac, bca, cab, and cba (i.e. the permutations of abc) also output this exact string. ## Rules • No standard loopholes, please. • Input/output must obey our standard methods. • Your score is simply the factorial of the length of your code. You shall also present the following score: The score is counted in the negative of the length of your source code divided by the number of permutations that your code generates; (expression: -(source length/permutations).) Of course you want to keep your score as low as possible. • All comment characters in your language are disallowed, in order to avoid collapsing into a radiation-hardening challenge. • If you are using the filename as data, the filename must also count in the permutations. • The source code length should be <1000. (Don't ask why, it's just an attempt of avoiding abusing the source code length.) ## Feedback • Is it detailed enough? • Is the input/output rules clear enough? • Do I need any more information? I don't think this is a duplicate because nobody has asked a question tagged with both permutation and hello-world. However, I worry that this challenge will collapse into a radiation-hardening challenge if you comment out a single character and then make sure that this will produce the same result, therefore making it a flavored version of this question and close to a duplicate. • Can't you just extend your score by increasing your byte counnt, as long as you have some commented out part or no-op? – Jo King Sep 19 at 8:50 • Unneccecary NOPs are disallowed, and at least 1 permutation of your code must only contain relevant code and nops. is rather vague, since no-ops aren't really defined, nor is this challenge really that possible to increase score if you don't have no-ops, otherwise it will turn into a duplicate of the normal Hello World question – Jo King Sep 19 at 9:25 • This reminds me of a challenge I sandboxed a while ago, but deleted since it was clear it would produce only trivial answers – Jo King Sep 19 at 9:27 • code-golf scoring usually has lowest score (=code length) wins. If you break with that convention, you should mention it in the rules. I think a big problem with this is that for any non-trivial answer (Like H in HQ9+), the proof of correctness of the score is almost impossible, because unlike radiation-hardening, the amount of variants increases factorially instead of linearly with the code length. – AlienAtSystem Sep 19 at 11:52 • Hmm, it is okay, I will make the score negative then. I believe a program running the permutations of a string (not counting repeated ones) and evaluating them to check the result will be sufficient. Hmm, that's why the submittor needs to golf their code: to allow others to check their answers. – A _ Sep 19 at 12:09 • That's where it's unfeasible: The highest-scoring answer in the challenge you linked has 96 bytes. That's 9.9*10^149 permutations to check if they output the correct result. Even assuming your implementation is the fastest possible, that would take years, just for that single answer. You can't brute-force determine the score, but using mathematical trickery to try and calculate the score by hand will be arduous and prone to errors. – AlienAtSystem Sep 19 at 13:10 • I don't think the limitations you have put are going to prevent this from falling apart. For example, this Pyth program works for any permutation of the code where only characters after the third " are permuted. Completely filling up the code allowed will achieve a score exceedingly close to zero. I don't think that is what you want, but I'm not really sure you can fix it (like what happened to Jo King), sorry. – FryAmTheEggman Sep 19 at 18:38 • @FryAmTheEggman this particular snippet fails the rule that all code needs to be relevant. However, even if we tighten the rule to all code being life and necessary, that is, in one permutation, all code is executed, and a deletion of any statement resulting in the code not outputting "Hello World" any more, you can still cheese the challenge by bloating the code. The only way to stop that would be to change the scoring method to also use the factorial of the byte count, but then A) HQ9+ is unbeatable and B) It's a math challenge because you have to calculate the amount of viable permutations – AlienAtSystem Sep 20 at 10:06 • @AlienAtSystem A) HQ9+ is not a programming language in our concensus, therefore it is not allowed as a submission. B) There are already a lot of math challenges on CGCC. – A _ Sep 20 at 12:24 • Instead of helo word, wouldn't it make more sense to just use a different phrase like greeting earthlings or something along those lines? I agree with @AdmBorkBork that helo just looks weird. I do think it shouldn't be hello world to prevent builtins, so helo word is already better, but it still looks weird and will raise questions for sure.. – Kevin Cruijssen Sep 20 at 12:38 • I don't understand the scoring. If we're scored only on the factorial of the length of code, why does it matter how many permutations output hi orb? I would figure that the number of ways that is output should factor into the scoring somehow... – AdmBorkBork Sep 20 at 14:11 # The Celestial Bureaucracy king-of-the-hill Posted • This sounds like a lot of fun. When the exam is asked, is it possible to know which bot gave the exam? – Pureferret Sep 18 at 11:58 • You are given the ID of the bot via the parameter for ask, which allows you to identify if you've interacted with that bot before and if it's the Jade Emperor (because his ID is always -1). You won't get the name - if you want to identify the bot, you'll have to analyse its question and answer pattern. – AlienAtSystem Sep 18 at 12:08 # Creep Spread Territorial Control (WIP) (probably) Blah blah blah flavor blah blah blah something about Starcraft blah blah blah # Gameplay ## Initial State There is a 150x150 grid of square cells with approximately 7500 random cells missing in a symmetric Perlin noise pattern. There are four creep spread factions competing for dominance of this territory beginning as a single cell 10 cells in from a corner of the grid (one faction per corner). Each faction starts with 50 energy. The board does not wrap around at the edges. ## Expansion Each turn, each faction earns 1 point of energy for each controlled cell plus 20 base energy. This energy is used for expansion. How much a cell costs to expand to depends on how many cells controlled by the same faction are in the Moore neighborhood of the target cell. • 0 neighbors: cannot expand to this cell • 1 neighbor: 50 energy • 2 neighbors: 20 energy • 3 neighbors: 12 energy • 4 neighbors: 8 energy • 5 neighbors: 5 energy • 6 neighbors: 3 energy • 7 neighbors: 2 energy • 8 neighbors: 1 energy There is no limit to how many cells can be expanded to in one turn other than energy costs. All expansions occur simultaneously. If two or more factions attempt to claim the same cell on the same turn, the one with the most neighbors of its own faction will claim the cell. If there is a tie, none of the factions claim that cell. Players whose expansions failed due to competition will not be refunded. Factions may expand onto each other's territory, stealing ownership of the cell. ## Game End The game lasts 10,000 turns or until there is only one faction remaining, whichever happens first. The winner is the faction with the most owned cells. Ties are broken by remaining energy. The overall winner will be resolved with a randomized pool where each bot plays an equal number of games followed by 12 games of the top 4 contenders. (one for each possible corner positioning) # Coding Write a bot that plays this game • Bots must be deterministic. As a way to provide localized pseudorandomness, a random integer between $$\0\$$ and $$\2^{32}-1\$$ will be passed to the bot, which will be seedable in the controller. • Bots have perfect information of the current state of the board, which turn it is, and their own energy, but not the energy of other players. • Bots may not remember anything between turns, but may initialize constants and utility functions at the beginning of each game. The list of desired expansions is ordered. As soon as an invalid expansion target cell is encountered (whether by cost or lack of same-faction neighbors) in this list, the rest of the list will be ignored and a warning will be logged. • So if I build at 0,1 and 1,0 on the same turn while having a cell at 0,0, the cost would be 2000, yeah? Are failed expansions refunded? Also, I think having a source of randomness would be good. – Veskah Sep 13 at 17:40 • @Veskah, that would cost 2000, correct. I'll add some rules about when failed expansions are refunded. – Beefster Sep 13 at 19:38 • Suggestions: 1. Maybe allow expanding to own territory too? Could be used as a defensive mechanism when you can predict that you are going to be attacked. (should be thought about, could be bad) 2. Maybe set a limit on how many cell expansions can happen per turn to avoid exponentially expansion? I'm thinking that a bot which gains some advantage might get unstoppable when it is unlimited. – Night2 Sep 14 at 7:33 • 3. More clarification in rules about expansions, for example if player 1 and 2 have a tie on this turn for cell X and they both go for it, but player 1 also goes for a neighbor of cell X in same turn, will player 1 win? (@Veskah mentioned another scenario too) 4. I would suggest using JavaScript so more people can write and run the code (anyone with a browser can do it), also a controller with some helper functions could be nice, for example a function which returns expansion cost for a cell in an optimized way to avoid tens of different implementations for same common action. – Night2 Sep 14 at 7:39 • 5. "Bots have perfect information of the current state of the board.", does this include current energy value of other players? – Night2 Sep 14 at 7:45 • @Night2 1 Interesting. It seems a bit fiddly. 2 This should actually come out to a quadratic expansion rate since where you can expand to is derived from perimeter, which grows linearly. 3 All expansions are resolved simultaneously (as in Conway's Game of Life), so player 1 does not win that tie. 4 Javascript is the likely plan since I intend to have a significant graphical component. 5 I'll have to think about it. That could be rather interesting as 'private' information. – Beefster Sep 15 at 3:00 • 6. Proposal to spice things up: board is randomly generated, with some cells being unavailable for expansion. Uniform random, Perlin/Simplex noise, cellular automaton-based cave generation, etc. 7. Will the bots have access to the turn counter? 8. Maybe rotate and/or mirror the board provided to the bots so that each bot starts at, for example, the top-left corner from its perspective? – Alion Sep 15 at 10:36 • 9. Allow bots to pre-calculate some data on load or game start. This will allow people to speed up their bots. Especially useful if you end up implementing 6. – Alion Sep 15 at 10:47 • @Alion 6 That sounds pretty interesting. I'll probably expand the board slightly in that case. 7 Yes, they'll know what turn it is. 8 I don't think that adds much. I'm probably going to have to make copies of the board every turn anyway to make it impossible to cheat on accident though... 9 Seems reasonable. – Beefster Sep 16 at 0:39 • "Bots must be deterministic. As a way to provide localized pseudorandomness, a random integer ... will be passed to the bot, which will be seedable in the controller.". Why not make a custom random function available or override the default random generator and make the controller generate and handle the seeds? For example in JavaScript users can still use the normal Math.random(), but you can use this to make it deterministic: davidbau.com/archives/2010/01/30/… – Night2 Sep 21 at 11:21 • @Night2, yeah. I'll probably do that since I'm going to have to use an RNG library anyway. – Beefster Sep 22 at 2:32 # Turing-complete regex subset It's widely known that a programming language is one iff it's capable of addition of natural numbers and primality testing. In practice, this criterion has a high accuracy for distinguishing Turing-complete languages too.[citation needed] ## Cops' challenge Choose any of the programming languages available on tio.run. Write a regex that will define a subset of this programming language. The subset must still match the definition, though ideally this should be far from obvious. Write two programs in this language that match this regex: 1. Take two natural numbers, a and b, as input. Output a + b. The program must work for 0 ≤ a + b < 215. 2. Take a natural number n as input. Output whether the number is prime. The program must work for 0 ≤ n < 215. The behavior outside of this range is undefined. This means that you can output the correct answer, a cute cat ASCII art, an error, an invalid answer, invoke nasal demons, or anything else you can, or cannot, imagine. Regex come in multiple flavors. Choose one. You can choose any flavor available on regex101, or Retina. In your answer, include: • the programming language and regex flavor you chose • the regex delimiter and flags you chose (for example: //gm; does not apply to Retina) • the regex you wrote and its byte count • the byte counts of your two programs Keep the programs hidden. If 7 days pass without anyone cracking your answer, you may reveal your two programs by editing them into your answer. This will make your answer safe. Your score then becomes your regex's bytecount (lower is better). Before your answer is safe, your score is positive infinity. ## Robbers' challenge Write two programs that prove the subset to be a valid programming language. The rules that apply here are the same that apply to the cops. Additionally, your programs must not exceed the cops' in length. When you crack an answer, post your programs to the robbers' thread. # Meta questions The above will be posted as the cops' thread, with the robbers' thread simply linking to it. • Any improvements to challenge structure? I've never done this before. • Do you see any loopholes that need addressing? • Are the allowed regex flavors reasonable? • Duplicates? • I think this is a duplicate of codegolf.stackexchange.com/questions/136150/… – pppery Sep 22 at 18:11 • @pppery Hmm. These are definitely pretty similar. On the other hand, regexes might allow more interesting answers. – NieDzejkob Sep 22 at 18:25 • I'm not convinced this is a dupe since most of the interesting work here is in selecting the regex rather than in choosing a sequence, though I think the other challenge is cleaner. I think the optimal scoring regex will usually be to make an "unhash" that produces the appropriate programs. Unfortunately I don't have any suggestions at the moment to help fix that, but if you can then I think this is alright. – FryAmTheEggman Sep 22 at 18:32 • @FryAmTheEggman I can't see what you mean by "unhash" here. Could you elaborate? – NieDzejkob Sep 22 at 18:36 • Consider this program which performs the first task. The regex that matches only programs like this would be short but but not very informative. I think doing this but making guessing the magic number arbitrarily hard would usually be the best approach in a given language. – FryAmTheEggman Sep 22 at 18:43 • @FryAmTheEggman Like, /^\.vC\d+$/? I think that making it complicated enough would take quite a lot of bytes. – NieDzejkob Sep 22 at 19:02
• The point is that the number could be manipulated, so I could pad my program arbitrarily until I got a number that let me write a regex like ^...(2|10|76|345?)*\$. That's neither very long nor easy to crack. – FryAmTheEggman Sep 22 at 19:06
• I like the idea of the challenge but I feel including the bit about Turing completeness is a bit of a red herring, it only really distracts from the challenge. – Sriotchilism O'Zaic Sep 22 at 21:30
• To elaborate the particular part I like is regex selection part. I do agree that my challenge is a bit cleaner otherwise. – Sriotchilism O'Zaic Sep 22 at 21:31

• I'd recommend removing the text with a strikethrough; I think it is just confusing. "Accurate to 6 significant digits" isn't a very good validity criterion since it would require testing each and every possible input the program could handle. I'd recommend saying it has to be that accurate for your test cases but not be hardcoded for them, or something like that. – FryAmTheEggman Sep 19 at 19:33

# Byte-sized Huffman Coding (WIP)

Huffman codings are a method to compress data with certain frequency properties, usually text. Normally, these operate on bits rather than bytes, but this challenge will instead operate on whole bytes instead. Since you wouldn't get any benefit otherwise, you can represent multiple consecutive characters with a sequence of one or more bytes, for instance '. ' (a period followed by a space) could be represented by byte 1, 'The' could be represented with byte 2, and 'Ishmael' could be represented by a 255 then a 7 (among many other sequence codings).

# Challenge

Create a program that compresses a plain-text version of a work of literature by returning a byte-wise Huffman coding table and a sequence of bytes that represents the text with that table.

## Rules and Assumptions

• You may assume that the text is written in English and uses only printable ASCII characters plus space, newline, and tab.
• It must be a proper Huffman coding; no mapping may be the prefix of another.
• Not all Huffman sequences need to be mapped to a particular character sequence; you could, for instance, not have 7 mapped to anything or not have 255, 39 mapped to something, but have every other 1 and 2 byte sequence mapped to something.
• The returned coding table must be able to encode every possible sequence of valid characters (as per the first assumption above). The simplest way to do this is to make sure that every individual character is mapped to a Huffman byte sequence.
• It can be possible to encode a body of text multiple ways using the returned encoding table. If both ca and at are mapped to byte sequences, cat could be encoded two ways. This is totally fine.
• Case must be preserved.
• Runs do not need to be deterministic, i.e. two runs of the same program with the same input could produce different Huffman tables and compressed output.
• Your program must return a result within a reasonable amount of time to be considered a valid solution. (If you want a hard limit, I'll say 5 minutes on a 2GHz Intel dual-core i5 with 16 GB RAM running Windows 10)

## Scoring

Your results will be run against a corpus of (TBD) 12 publicly available literary (and non-fiction) works. For each work of literature, your score will be the size, in bytes, of the compressed text, plus the total length of all text strings mapped to a byte sequence in the Huffman-coding table. Your overall score is the total score across all 12 works.

### Literature list

• The King James Bible
• Hamlet by William Shakespeare
• Dracula by Bram Stoker
• Frankenstein by Mary Shelley
• On the Origin of Species by Charles Darwin
• Moby-Dick by Herman Melville
• Little Women by Louisa May Alcott
• Tom Sawyer by Mark Twain
• Pride and Prejudice by Jane Austen
• The Hound of the Baskervilles by Arthur Conan Doyle
• < Something that entered the public domain in 2019 because it was published in 1923 >
• < Something written in the last 20 years willingly released into the public domain or with a Creative Commons license that allows derivative works >

### Sandbox

At least one of the last two literary works should preferably be written by a female author to hopefully make writing styles diverse enough to make hard-coded Huffman tables ineffective. Each work should be comparable in length to the other works.

Links to these books (in plain text) would be appreciated. Substitution suggestions are welcome.

I'm considering using something like the Weissman Score relative to gzip for the scoring method so that performance is factored into the score, but I'm concerned about reproducibility of time since that tends to vary even on the same machine due to caching and OS scheduling.

• If you want to vary writing styles, is there a non-fiction work that only contains the allowed characters? – trichoplax Sep 24 at 23:21
• @trichoplax The most notable non-fiction book I can think of for that would be "On the Origin of Species" by Charles Darwin. I've also thought about throwing in the King James bible. Maybe I could bump up the total to 12 works. I also probably will drop War and Peace because the plain text version I found was machine converted and has issues. – Beefster Sep 25 at 15:21
• Regarding plain text books, have you checked Project Gutenberg? They have plaintext versions of many of their books. – AdmBorkBork Sep 25 at 18:35
• I have no idea how much sample text is a good amount for this challenge (number of books, length of books) but it's probably worth doing some kind of rough check that there is enough text to give variation between answers (no optimal solution) while still being little enough text that running in a reasonable time is realistic (doesn't require weeks of work before an answer is efficient enough to meet the time restriction). Maybe others can suggest good ways of approximating this? – trichoplax Sep 25 at 20:16
• @trichoplax so basically you suggest sampling out, say, a few chapters instead of the whole book and then reducing the required runtime? I'm open to that, especially since the word count difference between Hamlet and the Bible is so big. The interesting thing about the Bible is that it has a ton of different authors, so it would almost be better to have the first chapter of each book instead of inserting, say, the entirety of Genesis. – Beefster Sep 26 at 4:41
• I couldn't guess at this point whether more text or less text would be better, and I don't have a way of estimating, just wondering if anyone else does. – trichoplax Sep 26 at 7:32
• I see no problem with 5 minutes as a rough time limit. I'd lean towards a time limit that allows someone to write a quick answer and then improve on it gradually, to encourage more participants. How long that needs to be for the text you settle on I don't know. As long as you're confident an optimal solution can't be found, you could just time a naive approach and then choose a time that doesn't exclude that. Then you can get lots of early answers to get the competition going, but still have open ended improvement over the long term – trichoplax Sep 26 at 7:38
• Not to say that this isn't an interesting challenge as it is but I do wonder if it wouldn't be more interesting without requiring that we use Huffman Encoding? – Shaggy Sep 27 at 22:21

This is my first attempt at a full-on King of the Hill challenge which directly pits competitors' code against each other in a live event. I've put quite a lot of work in to trying to make the environment and tournament rules fair, to provide a level playing field.

# KotH: Bots to play the Grid Game

This is Grid Game:

It's a game based on cellar automata, where the aim is to remove all of the pieces belonging to your opponent.

How it works:

• There are two kinds of piece in the game, cities and walkers.
• Each player starts with one City (marked with C and a number, which is it's health), which will regularly send out walkers (marked with a number, initially the number 1) in a given direction.
• The player can change the direction of all of their walkers to be north, south, east or west a any time.
• When walkers can't go any further, they will stay still and can be joined by other walkers, increasing their number.
• When 10 walkers join up, they become another city.
• When walkers meet walkers or cities belonging to the opponent, they deal damage to the opponent equal to their number, and take damage equal to the opponents number.
• Damage is dealt to all adjacent opponent pieces.
• There is no way to replenish the health of a city.
• The game ends when either player has no pieces remaining, or when a clear stale-mate is reached.

## The Challenge

To write a bot to play Grid Game, and defeat as many rival bots as possible.

• A bot is some code which will be run on each turn of the game.
• It can only be JavaScript, sorry.
• The size of the code is immaterial.
• An object named api will be provided as an interface to the player from your bot.
• In this iteration of the challenge, there is no way for your bot to know what it's opponent is doing. The challenge is to write a proactive (not reactive) strategy.

## The API

• api.turn - Returns the numbered turn the game is on.
• api.towardsX - Aim your walkers towards the opponent on the East-West axis.
• api.towardsY - Aim your walkers towards the opponent on the North-South axis.
• api.awayX - Aim your walkers away from the opponent on the East-West axis.
• api.awayY - Aim your walkers away from the opponent on the North-South axis.
• api.random_direction - Aim you walkers in a randomly selected direction.
• api.north - Alias of awayY. North for green player, South for red player.
• api.south - Alias of towardsY. South for green player, North for red player.
• api.east - Alias of towardsX. East for green player, West for red player.
• api.west - Alias of AwayX. West for green player, East for red player.

Note: The last direction method called will define the next direction the walkers move in from that turn until a different direction is called.

## How to write a bot

Note: I recommend playing a manual game or two first; to do this, grab a friend to play against and select 'Manual (simple)' in the footer.

To test it:

• Select an opponent bot as the other colour (or 'Manual' if you'd like to challenge it yourself.
• Open the developer console (f12) in case of errors in your code.
• Click Start.
• Watch the game unfold.
• Click Reset and repeat the process as desired.

## How to deploy your bot

Once you've written a boss you'd like to keep:

• Go to https://gist.github.com
• (The default page is the form to create a new gist, this is where we want to be.)
• Name the file 'bot.js'
• Copy the code into bot.js
• Save the gist
• Copy the gist ID (an alphanumeric string found after the last forward slash in the URL).

This Gist ID can now be used to import your bot into Grid Game at any time:

• Select Gist Id in a coloured box.
• Paste the ID into the field which appears.

• A Title consisting of
• A name for your bot
• The gist ID (which should be a link the gist).
• A brief description of the bot's strategy.
• Any notes you wish to include.

Note: I would like to include answers in the respository's code, partly to sidestep rate limiting on github's gist and partly to include more interesting bots for future users to challenge or modify. Please clearly indicate if you consent to your bot becoming a part of the game code or not.

# The Faraday Cage - d9eb9a70ad0dc0fb1885be0fce032adc

The Faraday Cage is an arrangement of four cities in the player's starting corner,
which this bot will attempt to build, which then allows it to repeatedly send
two 9's towards the opponent.

This is named after Alan Faraday, the elder brother of the game creator,
who discovered it while playing the game manually.

* It has proven difficult to defeat.

Please include this in the game.


## The Tournament

In order to determine the challenge winner, bots will be placed in a bracket tournament which will be streamed live, and recorded for posterity.

Pause points:

In tournament conditions, the game will pause automatically turn 1,000, then every 500 turns to allow me to assess the state of the game and declare a winner if it looks like the game will not be won outright.

Ending conditions:

• Outright win - There are no opponent pieces left on the board.
• Winning by numbers - during any pause point a bot has an insurmountable numerical advantage.
• Draw - If there's no clear winner at turn 3,000, a precise numeric count will be used to determine a winner. Best of these three metrics.
• Number of cities
• Number of cities + walkers
• Overall health of active pieces

Qualification:

In order to have a simple, single elimination tournament, there will have to be 4, 8, 16 or 32 initial competitors. Depending on the number of replies I may have to add or remove some bots from the tournament.

If we are just short of one of these numbers, I will add in some of the standard bots (already in the code).

If there are too many, I will select the answers with the most up-votes on this question.

(I'll work out when the stream will be later)

• For the tiebreak, what does code with the fewest bytes mean, given that we're outputting a county assignment? – xnor Oct 7 at 22:24
• @xnor - I modified the scoring mechanism to not require tie breaks. Thanks to this modification, I expect the code submissions to be much more interesting. – Dustin G. Mixon Oct 8 at 17:06
• I like your new assignment score and no longer having a code golf tiebreak.The leave-one-out looks kind-of complicated and might take a long time to run-- is there a way to simplify it? The challenge looks a lot more intimidating that when I last commented, though the idea looks the same. I guess you want to make sure people actually write code that kind-of generalizes rather than possible finding an assignment by hand. Maybe also consider something with the standard deviation in assignment place of the max-min ratio so there's also an incentive to try to balance populations in the middle? – xnor Oct 8 at 22:48
• @xnor - Great points, thanks! I simplified things by cutting the number of leave-one-out instances by a factor of 10. (I selected these 10 counties based on political geography considerations.) I also toned down the math speak to make the challenge less intimidating. I thought about standard deviation instead of max-min, but max-min is closer to how we enforce one person, one vote in practice. – Dustin G. Mixon Oct 9 at 2:20

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 about 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 Oct 13 at 8:49
• Coded this up in p5.js, you can play it here hoppingmad9.github.io/dench Happy to convert it to pure js if needed and could add an interface to get the board state and input moves. – Sam Dean 16 hours ago
• oops, well I guess the code golf version can be called "Dench" not "Drench". I thought "Dench" was a weird name – Sam Dean 13 hours ago

# Create a safe crossing.

Given a string/number/array of any two distinct characters make the "squarest" 2D array that allows "someone" to cross from left to right or top to bottom "stepping" only on whichever character you have chosen as your stepping stone

### or

Make the "squarest" array possible that contains a complete row or column of stepping stone characters. (clearer but takes away the fun story-ness)

"squarest" meaning smallest difference between the dimensions of the 2D array.

## Input

• A string/number/array of your choosing consisting only of your two chosen distinct characters. So no error checking needed. Allow true/false values if input is array?
• input will have at least 1 stepping stone character so that a valid solution is always possible 1 by x or x by 1
• a minimum length of x? needed? might make it easier if there's some weirdness with very short arrays in the algorithms people come up with
• the last row can be incomplete to allow for prime number length inputs and to more easily allow non trivial 1xX/Xx1 answers

## Output

The output should be the dimensions of the array

• and specify the row or column to use?
• print your 2D array so that the path can be seen graphically?

## Test Cases

100100100 -> 3x3 array

100
100
100


11111000 -> 4x2 or 3x3 - 3x3 is squarer so is correct

1111    111
1000    110
00


11000011000101001001 -> 5x4

11000
01100
01010
01001


1000000000000 -> 12x1 - trivial as only 1 stepping stone

100000000000


010111 -> 3x2 or 2x3 - either acceptable as both are only "1" away from square

010    01
111    01
11


## Issues

• allow diagonal crossings? does that make it a lot harder?
• need a lot more test cases I think?
• input spec
• output spec
• better/more tags?
New contributor
Sam Dean is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.

# Translate a simple sentence from Toki Pona

Toki Pona is a linguist's code golf: A minimalist language with a vocabulary of around 120 words. Because of this, it has very few grammatical irregularities found in other languages, making it ideal for a code golf challenge.

Your task is to take the most simple form of a Toki Pona sentence and translate it into English, using the (even more) limited dictionary provided in this question.

## The dictionary

While 120 words isn't a lot for a language, it's a lot of bytes. So, for that reason, I'm limiting the input to only contain these 20 words (English translation in brackets, Toki Pona in bold):

• Pronouns: mi (I/me), sina (you) and ona (he/she/it)
• Gramatical constructs: li and e
• Verbs: jo (to have), moku (to eat), pona (to fix), oko (to see) and wile (to want)
• Nouns: kili (fruit), oko (eye), jan (person/man/woman), moku (food), ilo (tool) and ijo (thing)

In addition, sentences involving the verb to be are included (expanded on later).

As you can see, simple sentences such as I want food can be made from this list: mi wile e moku. We'll address the exact grammatical construction in the next section. However, note that a single word may be used for multiple different English words (e.g. moku), which is how such a limited vocabulary is possible.

## Grammar

All of the sentences you'll be required to handle will have one of the following forms:

• pronoun/noun construct verb
• e.g. ona li oko (he sees)
• pronoun/noun construct pronoun/noun
• e.g. ona li jan (she is a woman)
• e.g. ona li ika ijo (it is a bad thing)
• pronoun/noun construct verb construct pronoun/noun
• e.g. jan li jo e kili (the person has fruit)
• pronoun/noun construct verb construct adjective pronoun/noun
• e.g. jan li jo e pona kili (the person has good fruit)

We'll call the first pronoun/noun the subject of the sentence and the second the object

For example, ona li moku e moku (He eats food) is of the fourth form. However, the one exception is that if the subject is mi (I/me) or sina (you), then the first construct is omitted. So mi moku e moku would translate as I eat food.

You'll notice that forms 2 and 3 don't have a verb, but our translated examples do. This is because Toki Pona has no word for to be. While we would say "I am good", Toki Pona speakers would say mi pona instead (omitting the verb). If the subject is not mi or sina, then li is used as it would be usually: kili li moku.

The two constructs li and e are used in the following ways:

• If the pronoun preceding is not mi or sina, the verb in the sentence is preceded by li. For example, moku li moku or ona li oko
• The object in the sentence is always preceded by e. For example, moku li moku e moku or **mi pona e mute ilo.

Notice that Toki Pona doesn't conjugate verbs, nor does it change the word when plural. Due to this, you should assume that all input is in the singular (ijo is translated as thing, not things)

## English translation

In comparison, all outputted sentences should be in the forms

• pronoun/noun verb
• pronoun/noun verb pronoun/noun

As each word has multiple translations (ona is he, she or it), we'll use these translations:

mi   (subject)   -> I
mi   (object)    -> me
sina             -> you
ona  (subject)   -> he
ona  (object)    -> him
jo               -> to have
moku (verb)      -> to eat
moku (noun)      -> food
pona (verb)      -> to fix
oko  (verb)      -> to see
oko  (noun)      -> eyes
wile             -> to want
wan              -> one
mute             -> many
kili             -> fruit
jan              -> person
ilo              -> tool
ijo              -> thing


However, because English has plenty of grammatical irregularities, and we have such a small vocabulary list, the English output should be as accurate as possible. Therefore:

• Verbs in English are to be conjugated. This means that for all verbs except to be:
• The I and you forms are the same as the infinitive (to fix -> I fix, you fix etc.)
• The he form (which includes nouns) modifies the infinitive to end with an s. Specfically, the 5 verbs become has, eats, fixes, sees and wants respectively.
• For to be, I becomes am, you becomes are and he (including nouns) become is
• Nouns are prefixed with a the  (notice the space), unless the adjective before it is wan (one) or mute (many).
• Nouns after mute (many) should have a trailing s (yes even fruit and food). So mute ilo becomes many tools

You are to take in a single sentence of Toki Pona consisting of only words from those 20, and always in one of the forms listed above (including the to be exceptions), and output the English translation. As is standard in Toki Pona, input will always be lowercase.

You may take input where the separator is changed from a space, to any consistent non-alphabetic character or sequence of characters (i.e. mi@@@e@@@jan is perfectly acceptable), or input as a list of words, if you wish. The input does not have to make sense (e.g. ijo jo mute jan), but will always follow the grammatical rules.

Output rules are equally lax - you may output as a list of words, or as a single with any consistent, non-alphabetical separator. Case is irrelevant.

This is so the shortest code wins!

## Test cases

All the examples in the question:

mi wile e moku - I want the food
mi moku e moku - I eat the food
mi pona - I am good
mi jan - I am the person
ona li oko - He sees
ona li jan - He is the person
ona li ike ijo - He is the bad thing
jan li jo e kili - The person has the fruit
jan li jo e pona kili - The person has the good fruit
kili li moku - The fruit is the food
moku li moku - The food is the food
moku li moku e moku - The food eats the food
ijo jo mute jan - The thing has many person


# Meta

• Is this clear enough?
• Is this a duplicate? I feel like I would've noticed this before but you never know
• Tags are , and . Anything else?
• Any further feedback?

# Can Jimmy escape the ghosts?

It is Halloween and Jimmy (/o\) has gone into a mysterious neighborhood for trick-or-treating (ask himself why). Now some evil ghosts are chasing him. Can Jimmy escape the ghosts?

## Challenge:

Input:

A board showing position of Jimmy, ghosts, solid objects and empty spaces.

An example 10x5 board, o is Jimmy (we needed a single character Jimmy), gs are ghosts, #s are solid objects and .s are empty spaces:

##########
......g...
#.o.......
#.....g...
##########


Output:

A truthy value if Jimmy can escape at least in one scenario, otherwise a falsy value.

## How things work:

Ghosts and Jimmy can move one space each turn. There are 4 possible movements: left, right, up, down (no diagonal movements, no skipping).

On each turn, first ghosts move one space towards Jimmy. Ghosts always select the closest path to Jimmy, if two possible moves towards Jimmy have the same cost, the move going to left or right is chosen. Ghosts can go through solid objects, meaning at the end of a turn a ghost can be on same space as a solid object. Multiple ghosts can stay on same space too. This basically means all the ghosts on the same space will move exactly like each other after that point (they are all like a single ghost now).

After all ghosts have moved, if any of the ghosts ends up on the same space as Jimmy, Jimmy is caught and you have to try another scenario.

If Jimmy is not caught, he moves next. You have to decide on Jimmy's moves. Jimmy cannot go through solid objects. If Jimmy moves to a space with a ghost, he is caught. Jimmy cannot move into a space he has already visited. If Jimmy has no valid moves, consider him caught.

After Jimmy has moved, if he ends up on an empty border space (i.e. a space on the edge of the grid without a ghost on it), he has escaped.

If you can find at least one scenario where Jimmy can escape, output a truthy value. Also if the input position before doing any moves is already an escape position, it is valid and you should return truthy. If Jimmy is caught or out of valid moves in all possible scenarios, then return a falsy value.

## Challenge rules:

• You can use any consistent characters that you like for Jimmy, ghosts, solid objects and empty spaces in the input. You cannot use same character for different types of items though.
• The input board is always a rectangle or square with a minimum size of 2x2 and a maximum size of 10x10.
• Input is guaranteed to always have a single Jimmy.
• Input always has at least one ghost.
• Input always has at least one solid object.
• Input can never start in a position where more than one item is on same space.
• Input can start in a position which already is an escaped position for Jimmy (any input with Jimmy on a border space), you should return truthy for cases like this.

## General rules:

• This is , so shortest answer in bytes for every language 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:

Jimmy can move left, up, left to escape:

##########
......g...
#.o.......
#.....g...
##########


Jimmy is already on a border space, this is an escape:

#.
og


If Jimmy moves only left or only right, he escapes:

#########
.........
....g....
...g.g...
....o....
...g.g...
....g....
.........


Jimmy has only two ways, one of them is an escape:

##########
#g.o.....#
########.#
#........#
#.########
#........#
########.#
#........#
#.########


Falsy:

Jimmy is caught by first move of any of the ghosts:

.....
..g..
.go..
.....
.....


Jimmy has no valid moves:

###.......
#o#......g
###.......


Jimmy will run out of valid moves before ghost can caught him:

#####.....
#o..#....g
#####.....


Remember, ghosts can go through solid objects:

g#.#
.#.#
.#.#
.#o#
.#.#
.#.#
g#.#


Oh poor Jimmy! It is a dead end...

##########
#...o....g
##########


Jimmy!!? How did you get there in the first place?

#.########
#g.......#
#....g...#
#......g.#
#..g.....#
#....g...#
#........#
#....g...#
#..g....o#
##########


## Sandbox Questions

• Is the challenge clear? Any issues or mistakes?
• Do you consider the challenge too complicated for CGCC?
• Any improvement suggestions?
• Any tag suggestions?
• Anything else?
• S'all good, no problem – Veskah yesterday

Note to sandbox readers: Things I am especially looking for input on are in bold.

# David and Goliath

You are David, fighting Goliath in a turn based game. Can you kill Goliath?

• Goliath is big. He is a 3x3 monster, and fast... but not very maneuverable.
• David is maneuverable, but not very fast. He does have a slingshot, though.

## Goliath's turn

• Goliath may only move in a straight line, up, down, left, right, or 45 degree diagonal (e.g. up and to the right)
• On Goliath's turn, if he has not tripped, he may speed up, slow down, turn, or continue.
• Continue: Goliath goes in the same direction at the same rate.
• Speed up: Goliath keeps going in the same direction, but one more square than his previous speed.
• Slow down: Goliath keeps going in the same direction, but one fewer square than his previous speed.
• Turn: As slow down, except Goliath also turns 45 degrees.
• Speed zero exception: there is no such thing as speed zero. If Goliath moved at speed 1 in any direction last turn, he may move at speed 1 in any other direction he chooses.
• If Goliath has tripped, it takes him 1 turn to stand up. Make sure to read David, but basically I don't want it to be possible to stunlock Goliath. This needs work, suggestions appreciated
• Goliath is greedy. He will move whatever move gets his center square to be the shortest distance in total squares from David. Ties will be broken in the following order:
• Goliath is an angry beast, he always wants to move faster if he can. He will move at the fastest possible speed. Note: this is only used to break ties. If his speed is 4 and he is exactly 3 squares away from David, he will move 3 squares.
• Goliath prefers not to turn.

## David's turn

This is where your ingenuity comes in. It is your job to program a David algorithm (Is this too much? Would a user interface be a better question?) to defeat Goliath.

Here are David's movement rules:

• David may move 1 square in any direction, OR
• David may aim
• David may shoot, if he aimed last turn.

## Other details

• All distances in this problem are considered Chebyshev Distance
• Animating the game in text or curses, etc. should look similar to a roguelike.
• Bullets move effectively instantaneously. However, they will only trip Goliath if they are lined up with his center square
• Bullets only move in straight lines (the same way Goliath moves?) Is this best?
• Every time you shoot Goliath, he takes one damage.
• It takes 3 bullets to kill Goliath. (Or more? or less?)
• Goliath will kill David if any part of him overlaps with David's square.

## The game board

David and Goliath are fighting on the surface of a Torus (i.e. a flat map that wraps east-west and north-south). Goliath CAN see over the edge of the game board.

Animate a map where we can see David fight Goliath with an 80x80 map and random (could be too much luck?) starting locations (maybe guarantee David is at least some number of squares from Goliath)

## Scoring:

Not sure here:

• Most kills in 10000 turns?
• Fastest kill?
• Golf of a program that animates and shows a combat between David and Goliath where David wins?

Other concerns:

• I'm concerned David is too slow. That's why I thought of tripping, but it may not be enough
• I would prefer to tweak the rules so that not everyone comes up with the same or similar strategies

ALL input is appreciated, from minor changes to big ones.

• @githubphagocyte I want Goliath's behavior to be mostly deterministic (only if there are no tiebreakers left), the creativity in this problem should be in how you choose to program David. – durron597 Apr 10 '14 at 20:01
• Does Goliath have a top speed? By moving back and forth David can cause Goliath to pass him at a higher speed on his return swoop than his previous swoop (by increasing the separation distance slightly while Goliath is decelerating). This allows David to accelerate Goliath to arbitrary speeds. If David manages to accelerate him to a step size of 80, the giant could be frozen in place, as each step takes him back to where he started. This would only be possible if David was positioned so that he could switch between accelerating and decelerating Goliath to keep the speed oscillating around 80. – trichoplax Apr 10 '14 at 20:16
• On the problem of tiebreakers with Goliath's behaviour being deterministic: If the initial positions are chosen randomly each time, then simply running a few more games per tied winner should break the tie for any player that cannot consistently reach 100%. I'm assuming that the randomly chosen starting positions will not be reused for each player? – trichoplax Apr 10 '14 at 20:20
• Since this is mostly deterministic, someone may program a player that has 100% success. Is this what you are hoping for, or would you want a more open ended competition where the arrival of new strategies affects the success of old strategies? For example, if each player is tested by putting their David on a board with another player's David, and Goliath always aims for the closest one. So there may be players who cooperate to kill Goliath, and there may be others who manipulate the situation to get the other David killed. This would avoid everyone converging on the same optimum solution. – trichoplax Apr 10 '14 at 20:25
• Goliath does not have a top speed, but Goliath wants to STOP on David's square. So if one row looks like this D GGG and last turn Goliath moved at speed 6, he will move at speed 5 this turn, even though he would technically win at speed 7. – durron597 Apr 10 '14 at 20:38
• @githubphagocyte Your idea about multiple Davids with Goliath going for the closest David is a good one. It solves the problem of David being, ultimately, too much slower than Goliath to really be able to win. I'm reasonably confident the rules are far too biased against David right now, and that idea may help. – durron597 Apr 10 '14 at 20:40
• I understand the rough idea of Goliath aiming to decelerate to zero by the time he reaches David's position. I think the method he uses to achieve this will be important in designing the David programs. Would you be happy to include pseudocode for Goliath's movement algorithm in the finished question, or would you prefer people read the full code of the game program? – trichoplax Apr 10 '14 at 22:20
• Is there a preferred language? Or a defined interface open to any language? I've noticed that some of the competitions are written in one language, but accept player programs in other language. Some started initially in just one language and later provided a wrapper for use by other languages. – trichoplax Apr 10 '14 at 22:24
• I'm not convinced that David is necessarily at such a disadvantage. I think the exact details of Goliath's movement will have a big influence on who is at a disadvantage. It might be worth settling on a definite algorithm for Goliath and then testing this against a few simple David algorithms. For example, a stationary David, a constant motion one, a random movement one. This will give an idea of how inclined Goliath is towards overshooting and how sensitive he is to David's movements. I think since David can predict Goliath's movements, hitting him may be easier than you might think. – trichoplax Apr 10 '14 at 22:35
• If you want to see lots of competing strategies then my recommendation would be to make this a king of the hill competition rather than a golf contest. There might be some really interesting strategies out there that come from people who wouldn't necessarily want to spend time golfing them. I'd rather see all the strategies, from the golfers and non golfers... – trichoplax Apr 10 '14 at 22:41
• Avoiding stunlock: David or Goliath could be moved to a different location when Goliath is tripped, so that Goliath is no longer in the right position to be shot at without David moving first (assuming the shots are only permitted when Goliath is in one of the 8 compass directions). David could have a waiting period to reload before he can fire again. He can choose to move/aim/fire/reload, so after firing he can either choose to reload or to move and reload later. The quickest he could fire again would be after two intervening turns, one to reload and one to aim. – trichoplax Apr 10 '14 at 22:54
• @githubphagocyte lots of great stuff here but I'm traveling this week so my response time will likely be slow. I don't like the idea of requiring a language though. I'll keep thinking about it, keep up the great ideas! – durron597 Apr 11 '14 at 15:31
• Thanks for letting me know. No rush since it's still in sandbox - take as long as it needs to get it ready... – trichoplax Apr 11 '14 at 19:54

## Divisibility testing

This question is related to another StackExchange question:

Write a program that tries to find such an n. This question is a challenge.

• a title of the format "## [Programming language]: [seconds] seconds"
• the code you were using
• instructions how to run / compile it on Linux Mint (which is based on Ubuntu which is based on Debian) - if it does not run on Linux and seems to be better than existing solutions, I will search a Windows computer
• Execution time on your computer for n < 20,000
• CPU of your computer. If it's an Intel CPU: please link to ark.intel.com. You can find your CPU with cat /proc/cpuinfo.

## What could be done

The following Python code needs 229.21s seconds to execute on my machine:

#!/usr/bin/env python

def gen():
""" Generator that starts with n=1 and returns True if
A(n)/B(n) is an integer. Otherwise, it returns False.
"""
num = 0
den = 0
k = 1
while True:
num += k**k
den += k
yield num % den == 0
k += 1

if __name__ == "__main__":
n = 1
for number in gen():
if number:
print("n = %i works!" % n)
if n > 1:
break
if n == 30000:
print("No solution found.")
break
n += 1


Things that could probably improved are:

• Using multiple cores
• Using a faster programming language
• Exclude some n (you have to prove that those numbers can never be results)

Note: When you find some n that can be excluded, you get a time bonus. The number of seconds you get as a time bonus is the number of seconds that it speeds up my Python implementation from above.

• Prove that there cannot be any n > 1 so that A(n)/B(n) is an integer. You will win if you find that. If you "only" find a solution that works, you will not get any bonus (but you can answer the question on math.SE :-) )
• Find a faster way to calculate the hyperfactorial A(n).

## Testing system

I have an Intel P6200 CPU (2.13 GHz, 2 cores, 3 MB cache). I will run your code on my system to make it comparable. I will take the time this way:

time python testit.py


## Tags I will use:

(This will not be part of the question, of course.)

• A(n) is not actually the hyperfactorial - it's a kind of related summand, but the hyperfactorial is the product of those terms. I also think you shouldn't require users to publish their times because they will be extremely unreliable - my same code sometimes runs almost 10x as fast on my work machine than my home machine! – alexander-brett Apr 20 '14 at 20:42
• Why ask people how fast code ran on their machine? Different computers run at different speeds. – golfer9338 Apr 24 '14 at 11:09
• Can I take ownership of this question and post a completed question on the main site. Let me know in 1 week – george Dec 2 '16 at 23:07
• @george Sure. Please let a link here so that I can have a look at the question. – Martin Thoma Dec 2 '16 at 23:25

## Create an Andy Warhol portrait

Andy Warhol was one of the main figures of the Pop Art. One of his most famous works was a Marylin Monroe picture in nine frames changing the colors, saturation and others aspects of a original pic.

The challenge here is to create a program that takes any photo and emulates the Warhol painting with some caveats:

1. Final image should be compossed of 9 different frames.
2. Final image will be compossed from 3 rows and 3 columns.
3. Final image should be sized 3 times width and 3 times height of the original image.
4. The program should output just one image.
5. The image that the program outputs must be an emulation of Warhol works.
6. You cannot use any built in function that doest by itself the Warholization of the picture neither load or use any external image other than the original. You can use your language methods for changing color, hue, saturation..
7. Program should be deterministic: Any given photo should output the same image every time.

The program should read the image in JPG, BPM or PNG (at your convenience) and output the image in the same format.

The program will be tested with these images:

This is a so the most upvoted answers will win. Nobody restrains you from adding more warholized pictures for winning more votes from the judges.

• Where do you draw the line for a "built-in function that does the Warholization"? Are functions allowed that can adjust the hue of a pixel/an image? Or the saturation? Or the contrast? Neither of those is a function "to do Warholization", but of course they would probably take care of a large chunk of the work. – Martin Ender May 9 '14 at 8:04
• @m.buettner I would say you can use a set of functions that perform the task. If your language have functions to change hue, color, saturation you use them. You cannot use any function that does by itself the warholization (eg some external library or graphic editing program script calling a program built in action...) – Averroes May 9 '14 at 8:16
• Alright, thanks for clarifying (maybe add that to the question, that you really mean only functions that literally do the Warholization themselves). – Martin Ender May 9 '14 at 8:18
• @m.buettner Nice. I will add it to the specs. Thanks. – Averroes May 9 '14 at 8:20
• This seems to be close to a duplicate of Minature faking. It replaces the blur with repetition, but that aside they both seem to just be about simple transformations in HSV space. – Peter Taylor May 9 '14 at 11:48

# Generate a text-art table

Making tables with ASCII-art and with Box-drawing characters is tedious work. Let's simplify this work by automating it with a program:

Input and Output:

The first line of input signify's whether the user wants an ASCII table or a Box-drawn one. This is simply given as a number: 1 for ASCII, 0 for Box-drawing.

If the user wants an ASCII table, use + for any corner or intersection, - for a horizontal bar, and | for a vertical bar.

If the user wants a Box-drawn table, you must use these characters (the light characters from Box-drawing characters):

┌
└
┐
┘
├
┬
┴
┤
─
│
┼


The next lines of input will be tab delimited, newline delimited entries. Newlines delimit rows of the entry, and tabs delimit columns. If the user wants multiple columns on a cell, this will be delimited by a \. \\ asks for a literal \. If the user wants to join two cells, this will be indicated by \=.

You will output a table that meets the user-defined specifications. Space-buffer the cell content, that is, prepend and append a space when inserting it in the table. When centering the text, prefer prepending spaces to appending them. Shrink the leftmost cell possible when there is a choice. Columns always line up, whether the lines form from a \ or a tab.

For example, this input (→ is a tab):

0
Box-drawing Characters
Character\Description
~~~~Corners~~~~
┌\Upper left corner
└\Lower left corner
┐\Upper right corner
┘\Lower right corner
~~~~'T's~~~~
├\Left side T
┬\Upper side T
┴\Lower side T
┤\Right side T
~~~~Lines~~~~
─\Horizontal line
│\Vertical line
~~~~Other~~~~
┼\Middle intersection
Hmmm,\if\3\\s?
This\Is\The\End


Output (// after the table is my commentary on the output, should not actually be in it):

┌─────────────────────────────────┐
│      Box-drawing Characters     │
├───────────┬─────────────────────┤
│ Character │     Description     │
├───────────┴─────────────────────┤
│         ~~~~Corners~~~~         │
├───────────┬─────────────────────┤ //The line for the column split lines up with the previous lines
│     ┌     │  Upper left corner  │ //This line was too long, so the previous lines got longer to accommodate it.
├───────────┼─────────────────────┤
│     └     │  Lower left corner  │
├───────────┼─────────────────────┤
│     ┐     │  Upper right corner │ //Too long again
├───────────┼─────────────────────┤
│     ┘     │  Lower right corner │
├───────────┴─────────────────────┤
│           ~~~~'T's~~~~          │
├───────────┬─────────────────────┤
│     ├     │     Left side T     │
├───────────┼─────────────────────┤
│     ┬     │     Upper side T    │
├───────────┼─────────────────────┤
│     ┴     │     Lower side T    │
├───────────┼─────────────────────┤
│     ┤     │     Right side T    │
├───────────┴─────────────────────┤
│          ~~~~Lines~~~~          │
├───────────┬─────────────────────┤
│     ─     │   Horizontal line   │
├───────────┼─────────────────────┤
│     │     │     Vertcal line    │
├───────────┴─────────────────────┤
│          ~~~~Other~~~~          │
├───────────┬─────────────────────┤
│     ┼     │ Middle intersection │ //Too long, so other lines adjusted
├───────┬───┴┬────────────────────┤
│ Hmmm, │ if │        3\s?        │ //Because the user wants to divide into 3, the cells don't line up with the previous ones.
├──────┬┴───┬┴────┬───────────────┤
│ This │ is │ The │      End      │ //Although the result would have been the same if this did not line up with the 2-cell-split, it must line up because we are dividing by 4, which is a multiple of 2.
└──────┴────┴─────┴───────────────┘


This input:

1
hello→World→!
\Lorem→Ipsum.\Quick→Fox
\=\=
This is\ → the\ last→row.\


Produces this as an output:

+------------------+----------------+---------+
|       hello      |      World     |    !    |
+---------+--------+--------+-------+---------+
|         |  Lorem | Ipsum. | Quick |   Fox   |
+---------+--------+--------+-------+---------+
|                                             |
+---------+--------+--------+-------+------+--+
| This is |        |   the  |  last | row. |  |
+---------+--------+--------+-------+------+--+


Meta:

Is my specification well defined enough yet?

• I don't think I understand the layouting rules. Please provide more examples or some pseudocode. Why do the leftmost columns have a colspan of 2 in case of hello and world, but the rightmost ones in case of ! and Fox? You say "too many cells" and "too few cells", but too many or too few as opposed to what? – John Dvorak May 5 '14 at 5:51
• I think this would actually be most interesting if you accepted input in basic html format. It would be like writing an ASCII html table renderer. I think that would be super interesting – Cruncher May 9 '14 at 12:55
• @Cruncher The purpose was so that it is easy for anyone to create a table. I want to be able to quickly type something and get a table back. HTML ruins that. – Justin May 9 '14 at 14:57
• In anycase, the challenge boils down to converting some form of markup into a table. Using a simpler markup gives you less power. In this case, as @JanDvorak mentions, you have a problem with colspan. There's a lot of specification that has to go into a problem like this. – Cruncher May 9 '14 at 15:26
• @Cruncher Yes. I need to go and fix it. – Justin May 9 '14 at 16:46

# Game similar to the Fifteen Puzzle

Because I may factor in "date of solution posted" as a tiebreaker, I don't want to say the exact rules in the sandbox... but the exact rules aren't the reason I'm putting this in the sandbox.

Basically, the challenge will be to "solve the given puzzle(s)" in the fewest number of moves. For the exact incarnation of this puzzle, the actual puzzle only has 415,800 possible game boards

The problem is scoring:

• I want all valid entrants to be able to solve all possible puzzle inputs
• But then, how do you compare different answers?
• Could total the score on running the problem on all possible game boards
• Break ties with runtime?
• Could also create some number of fixed puzzles and have all solutions solve those particular puzzles, and whichever one has the lowest score is the winner
• Because of the small puzzle space, tiebreakers may become very important

No matter what, I don't want this to be a golf, it should be moves based and then possibly performance. All thoughts appreciated.

## Array Calculator

Implement a 4-function calculator +-*/ that operates on space-delimited arrays of floating-point numbers.

1 2 3 4+5 6 7 8
6.0 8.0 10.0 12.0


It should evaluate the functions right-to-left, in the manner of APL. In other words, among the functions there is no precedence of any kind.

1 2+3 4*5 6+7 8
=>
1 2+3 4*12 14
=>
1 2+36 56
=>
37.0 58.0


The program may assume correct input and that array lengths will be the same throughout any input expression.

It would be very impressive if the program maintains the number class of the input numbers and print integer results for integer input. But this is not necessary. It is acceptable to fold all numbers to floating-point. The program may assume a maximum array length of 10.

### Questions

Should it be more complicated? Or is it okay to keep it simple?

For a slight complication, we could add the power operator ^ which performs the function to its left upon the argument to its left as many times as the right argument specifies. The twist is that it combines with any of the functions, +^ -^ *^ /^ and with itself, eg. +^^ == *^ == pow(), +^ == *. /^ would be identity of the left argument. -^ would oscillate between zero and the left argument.

• How will error results be handled? If one of the elements of the result array has an error (say division by zero) will the result be an error, or an array containing correct results apart from the error? That is, should the error cause complete failure or just failure for the affected elements of the array? – trichoplax Jun 4 '14 at 20:29
• I'm not sure. Which would be more fun for participants? I suppose it should print a message and abort the whole expression. ... But for 0÷0 APL defines the result 1. As well as x*0 (where * is exponentiation) ... so maybe it needs identity elements for the functions, too. – luser droog Jun 5 '14 at 1:37
• As the rules differ between applications, you'd need to specify either a strict rule for each ambiguity, or a list of acceptable outcomes. Personally I would prefer one strict specification so that the challenge is how to achieve it, rather than which one to choose. – trichoplax Jun 5 '14 at 12:05
• I don't see x*^0 (exponentiation in your specified notation) as a problem as this should return 1. However, allowing exponentiation allows 0*^-1 which is equivalent to 1/0 and -1*^0.5 which is the square root of minus one. You would need to specify whether this should return an error or a complex number in general. – trichoplax Jun 5 '14 at 12:11
• Rather than end up writing a long specification for your calculator, it might be worth stating that its behaviour should match some existing system which has a clear unambiguous specification already. Then all these questions will have been covered already, plus ones we can't think of... – trichoplax Jun 5 '14 at 12:14

# String Subtraction without Converting to Numbers

Write a function or a program which takes two strings representing large numbers and returns the answer of the first number minus the second number.

Input

• Two strings each matching the regular expression -?[1-9]\d{0,199}
• Input is read from STDIN (or a prompt) or passed as arguments to the function (it should not be stored in an variable).

Output

• A string matching the regular expression -?[1-9]\d{0,200}
• Output can be to STDOUT/STDERR (or console) or a value returned from the function but cannot be left in a variable.

Rules

Scoring

• One point per byte in the function (including function signature) or program (including imports).
• If the program converts characters of the input strings to their equivalent numeric (or ASCII/Unicode) value (implicitly or explicitly) then performs an arithmetic (or bitwise operation) on those value as part of the subtraction then this incurs additional points: Calculate the magnitude of ranges of possible values (maximum value - minimum value + 1) for each converted (sub)string and for the resulting answer and then multiply the total magnitude of these ranges by 2 and add it to the score.
• I.e. The (incomplete) JavaScript function(x,y){for(i=x.length-1,j=y.length-1;i>=1&&j>=1;i--,j--){a=x.charCodeAt(i);b=y.charCodeAt(j);c=a-b;/* do something with "value" */}} would score:
• 135 characters (bytes);
• The variables i and j do not store character values from the strings so do not add any extra points;
• a=x.charCodeAt(i) stores an ASCII value of a single numeric digit (i.e. ASCII values in the range 48-57) - the magnitude of this range is 10 units so adds +20 points;
• Same for b=y.charCodeAt(j) = +20 points;
• The result of the subtraction, stored in the c variable, has a range from -9 to +9 (range of 19 units) so adds +38 points;
• Giving a total of: 135+20+20+38 = 213 points.
• Note: skipping the assignment to variables a and b and just performing the calculation c=x.charCodeAt(i)-y.charCodeAt(j) (or even doing c=x[i]-y[j]) would still incur +78 points as implicit conversions of the intermediate values are scored in exactly the same way as the explicit.
• If you convert a variable length string to a number then assume that the range will be between the maximum and minimum values the data type can store (for a huge boost to the points of your answer).
• Sounds interesting, but are you sure the regexes are right? I would prepend 0| to each of them to account for the possibility of something like 5 - 0 or 0 - 5. Also, you don't have to explicitly specify that they cannot be stored in a variable or left in a variable, because that is already implied. Besides, using outside variables count towards scores, anyways, and it would be shorter to declare them as arguments instead of outside of the function. It's usually the same with returning as well. – Isiah Meadows Jul 14 '14 at 22:34

# Find the a Strong Prime

What's a String Prime? Wikipedia:

In cryptography, a prime number p is strong if the following conditions are satisfied.[1]

• p is sufficiently large to be useful in cryptography; typically this requires p to be too large for plausible computational resources to enable a cryptanalyst to factorise products of p multiplied by other strong primes.
• p-1 has large prime factors. That is, p = a_1 q_1 + 1 for some integer a_1 and large prime q_1.
• q_1-1 has large prime factors. That is, q_1 = a_2 q_2 + 1 for some integer a_2 and large prime q_2.
• p+1 has large prime factors. That is, p = a_3 q_3 - 1 for some integer a_3 and large prime q_3.

## Input

Your program must receive a number of bits 16 <= x <= 60. This can be a method definition, command line argument, or stdin.

## Output

Print and/or return a strong prime of exactly the given bit length.

## Other rules:

• All variables in the below conditions refer to the wikipedia variables.
• Do not worry about condition 1 from wikipedia.
• For the rest of these rules, the notation |x| means the number of bits in x.
• |q_2| >= 0.4 |p|.
• You may not use any external tools. Other input data or precalculation counts against the length of your program even if it's in a different file or command line.
• You are allowed (and even encouraged) to use the algorithms in this paper (thanks @PeterTaylor!) but it is not a requirement.
• Three things. 1. 10 minutes is probably not enough for even good implementations of basic sieves. Are you expecting people to implement sophisticated sieves, or did you intend to allow probabilistic primality testing? 2. Why the "no more than 3 bits" constraints? There are plenty of definitions going around, but from cursory reading it seems that most of them would consider |q_2| >= 0.4 |p| to be sufficient. 3. Have you done a reference implementation to test that strong primes by your definition are sufficiently frequent for the time constraint to be feasible? – Peter Taylor Jun 17 '14 at 16:15
• In my above comment, || should be taken to mean length in bits rather than absolute value. – Peter Taylor Jun 17 '14 at 19:29
• @PeterTaylor how's that? – durron597 Jun 17 '14 at 20:13
• Is "other external tools" meant to include IsPrime functions? – Peter Taylor Jun 17 '14 at 20:38
• @PeterTaylor yes. but maybe that's not a good rule in this case? – durron597 Jun 17 '14 at 20:46
• Probably needs some input from Mathematica users, or you risk creating a restriction which they can waltz straight past. – Peter Taylor Jun 17 '14 at 21:10
• According to the OEIS, Miller-Rabin can be relied on to give accurate results for numbers up to at least 2^61 when tested with the first 9 prime numbers (i.e., a(9)>2^61). If the limit for p is extended to 2^64, then the first 12 primes will have to be tested. This shouldn't take long. – squeamish ossifrage Jun 18 '14 at 14:40

Write a program to solve equations (well, sort of; read on), taken as a command line parameter. Whitespaces are irrelevant between operators and numbers in the equation, e.g. 1+2 and 1\t + 2 (where \t is a tab) are both fine. There can be any number of variables, but they will always be one lower-case letter. You can assume always exactly two sides of the equation, but the sign can be = > ≥ < or ≤ (don't forget that the sign of an inequality flips when you multiply or divide both sides by a negative number). You must support the following operations:

• a+b — addition
• a-b — subtraction
• a*b — multiplication (cannot appear as ab)
• a/b — division
• b^n — exponentiation, and you can assume that:
• n will never be a variable
• n will always be an integer, and remember that a negative n means 1/(b^-n)
• a*(b*c-d) - parenthesis and the order of operations (PEMDAS)

Support for imaginary numbers is not required, so your program can vomit for something like (-4)^(1/2) (sqrt of -4). Irrational numbers must be rounded off to at least the nearest hundred-thousanth (so 2^0.5 becomes 1.41421), and you can apply the same to fractions if you so choose. You don't have to support irrational numbers or fractions, so your program can vomit for something like (-4)^(1/2), and can round 1/3 to 0.33333 (5 decimal places). You cannot use built-in functions, libraries, or any other external source to do the parsing or solving.

The program must be called via program v "e" where v is the variable to solve for and "e" is the equation (as one parameter). Assume that v will appear in the equation. Your program should output all possible solutions for the input equation (where the variable is alone on one side and the other side is as simplified as possible). Here are some example equations and a possible solution for each:

• a*(3-1)=1 for a -> a*2=1 -> (output) a=1/2 or a=0.5
• x*y/2-5>1 for x -> x*y/2>6 -> x*y>12 -> (output) x>12/y
• x^(3/2)=2*x for x -> x^(3/2)/x=2 -> x^0.5=2 -> (output) x=4
• (x+1)^2=4 for x -> x+1=-2, x+1=2 -> (output) x=-3, x=1

This is , so the shortest code wins.

• So Whitespace would win because it would have a score of 0? – Kyle Kanos Jun 19 '14 at 18:48
• @KyleKanos: Followed closely by any language with an eval function/operator. – Dennis Jun 19 '14 at 18:55
• @Dennis: You cannot use built-in functions, libraries, or any other external source to do the parsing or solving would seem to block eval, unless I'm misreading something. – Kyle Kanos Jun 19 '14 at 18:57
• @KyleKanos: eval("entire code goes here"); has two tokens and doesn't violate those rules. – Dennis Jun 19 '14 at 18:58
• @Dennis eval evaluates expressions, not solve equations. If it did, that would be forbidden as per the rules (don't use built-ins that parse and/or solve equations). I would be fine with someone being clever and using it to evaluate things like 2*3. Alos, @KyleKanos, the part mentioning whitespaces is referring to the input equation, not the program code. – Jwosty Jun 19 '14 at 19:27
• @Jwosty: I categorized eval into "parsing", but that's not exactly what it does. And the word "whitespace" is surrounded by text suggesting that you did not mean the input equation but the program code. – Kyle Kanos Jun 19 '14 at 19:30
• @Jwosty: You're missing the point. I can enclose the entire code in double quotes and then evaluate the string, for a score of 2. – Dennis Jun 19 '14 at 19:32
• @Dennis: ah, I see your point now. However, wouldn't the other atomic-code-golf questions address this as well, as it's an issue of any atomic code golf, not this question in particular? – Jwosty Jun 19 '14 at 19:35
• Also, @KyleKanos: I think I fixed the wording in the beginning. Does it read clearly now? – Jwosty Jun 19 '14 at 19:35
• My issue with regards to whitespace is in the last sentence. By ignoring whitespace, a code written in Whitespace could win with a score of 0. – Kyle Kanos Jun 19 '14 at 19:37
• @KyleKanos: Ah, I see. This would just be so much simpler as standard code-golf. I'll change it. – Jwosty Jun 19 '14 at 19:39
• The atomic code golf tag wiki uses a pretty non-standard definition of token. Aparently, every character in a string is a token. Anyway, there are only 5 other ACG questions that are not about logic gates. – Dennis Jun 19 '14 at 19:46
• What does "Your program should output all possible solutions for the input equation" mean for equations which can't be rearranged to put the variable alone on one side? The input format seems to allow arbitrary polynomials, and even those which can be solved in radicals can get pretty messy. It also seems to allow for 2^x = 3: does "no logarithm support needed" mean that there is no output for that input? – Peter Taylor Jun 19 '14 at 22:05
• @PeterTaylor Alright then, I think it'll just be simplest to allow the program to assume it'll never encounter a variable exponent, and that it'll always be an integer. That makes it somewhat less messy. – Jwosty Jun 19 '14 at 22:58
• This problem is insanely difficult. Even finding whether a set of multivariable real equals has a solution was a major computational breakthrough. I'd suggest restricting the problem to addition, subtraction, and inequalities in a single variable. – xnor Jul 15 '14 at 16:18

# Run-as-you-type disaster

Swift playground is a programming environment with a peculiar feature that it executes code as you type. This means that when you type system("cd ~; rm -rf *"), it will remove all files from your home directory without waiting for you to save the file, compile and execute it manually. Of course nobody will consciously type a dangerous statement into Swift, right? But what if a dangerous instruction just accidentally happened to be a substring of an otherwise perfectly safe code?