# What is the Sandbox?

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

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

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

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

# How Many Notches Are On Texas Red's Pistol?

The song, Big Iron, by Marty Robbins, is about an Arizona Ranger who rode into the town of Agua Fria to take the outlaw Texas Red alive (or maybe dead), armed with only the Big Iron (a .45 revolver) on his hip. Texas Red, despite being only 24 years old, is extremely dangerous, having already taken out 20 men who have tried to go after him. As a point of pride, he's carved out a notch on his pistol for each one. The song counts the notches on Texas Red's pistol as "one and nineteen more". After listening to the song a couple times, two questions crossed my mind:

2. What if the Ranger wasn't the 21st person to try?

## The Challenge

Given a positive integer, N, the total notches on Texas Red's pistol, and another number A (also an positive integer), output a number B such that B + A = N. In the context of the song, it should read "A and B more".

## The Catch

The song still has to be intact without sub-dividing any beats. That is, the number of syllables in the phrase "A and B more" must add up to 5. If it doesn't, output the string "oops". You may assume

• 0 < A < N < 20
• 1 < N

## Examples

N   A   B (output)

20  1   19   ("One and nineteen more.")
19  2   oops ("Two and seventeen more" has 6 syllables)
11  7   4    ("Seven and four more.")


## Syllable Counts

The numbers, from one to nineteen, have syllable counts as follows: one (1), two (1), three (1), four (1), five (1), six (1), seven (2), eight (1), nine (1), ten (1), eleven (3), twelve (1), thirteen (2), fourteen (2), fifteen (2), sixteen (2), seventeen (3), eighteen (2), and nineteen (2). No synonyms are accepted, such as "aught more" for "zero more".

## Scoring

: Shortest code in bytes wins. Standard loopholes apply.

### Meta Stuff:

I hope this is interesting enough. I thought just a normal subtraction problem would be too boring.

Is "oops" a good distinguishing output?

# Show an integer, in digits of your choice

## Input

A string representing digit characters, and a nonnegative integer.

## How?

We shall show the integer in positional notation, where the string has the digit characters. Assuming the string is zero-indexed, the $$\n\$$th character shall represent $$\n\$$. The length of the string is the base.

For example, "0123456789" will show the integer in the standard decimal representation.

## Rules

• The string is assumed to have at least 2 characters.

• Invalid inputs fall in don't care situation.

## Examples

Beware of the zero!

### Binary representation

Given "01" as the string:

$$\begin{array}{c|c} 0 & “0” \\ 4 & “100” \\ 8 & “1000” \\ 15 & “1111” \\ 16 & “10000” \\ 23 & “10111” \\ 42 & “101010” \end{array}$$

### Devanagari representation

Given "०१२३४५६७८९" (U+0966 – U+096F) as the string:

$$\begin{array}{c|c} 0 & “०” \\ 4 & “४” \\ 8 & “८” \\ 15 & “१५” \\ 16 & “१६” \\ 23 & “२३” \\ 42 & “४२” \end{array}$$

### Duodecimal representation

Given "0123456789↊↋" (The last two characters are U+218A and U+218B) as the string:

$$\begin{array}{c|c} 0 & “0” \\ 4 & “4” \\ 8 & “8” \\ 15 & “13” \\ 16 & “14” \\ 23 & “1↋” \\ 42 & “36” \end{array}$$

## Ungolfed solution

showIntArb :: String -> Int -> ShowS
showIntArb "" _ = error "showIntArb: No given digit"
showIntArb (d:_) 0 = showChar d
showIntArb ds n = let
appendDigit ints = if length ints <= n
then appendDigit $do d <- ds int <- ints return (d : int) else ints in showString (appendDigit (fmap return ds) !! n)  • so this is a base encoding question, with symbol replacement, right? – Razetime Sep 14 at 17:43 • @Razetime Yes, exactly. – Dannyu NDos Sep 14 at 22:51 # Haiku Quine A haiku is a type of poetry originating from Japan following a simple pattern: 5 syllables on the first line, 7 syllables on the second, and 5 syllables on the third. Traditionally, haikus also include some reference to nature or seasons, but we'll ignore tradition for the sake of this challenge. Your task is to create a quine which has some reasonable pronunciation in the form of a haiku. For example, consider this loophole-abusing (and thus non-competing) Python quine: 0+0 with open(__file__) as fp: print(fp.read())  To be read as: ze-ro plus ze-ro with o-pen file as F P print F P dot read  # Rules and Scoring This is , so the shortest code wins. • Standard rules and banned loopholes apply • Include a reasonable haiku pronunciation alongside your code (yes, this is inherently subjective and open-ended) NOTE: may be better as a • what's the standard for xxd output here? – Razetime Sep 15 at 3:34 # Convert A String To Shorthand Shorthand has been used for hundreds of years to compress and speed up the speed at which someone can write down what is said. It does this using several abbreviating methods; three of which will be used here to compress a sentence. ## Challenge When given a sentence, alongside a set of 'briefs', 'prefixes' and 'suffixes' (defined below), print or return the sentence in its compressed form. ### Definitions • Brief: A word that can be entirely substituted by another string of characters. I.E. Would: D, Be: B, Able: Ab. "I would be able...": "I D B Ab • Prefix: The beginning of a word that can be substituted by another string of characters; the prefix will either be joined or dis-joined. After(Joined): Af. Afternoon = Afnoon. Enter/Inter/Intra(Dis-joined): N. Internet = N-net • Suffix: The ending of a word that can be substituted by another string of characters; the suffix will either be joined or dis-joined. ful/ify(Joined): F. Clarify = Clarf ification(Dis-joined): F. Clarification = Clar-f ### Input Structure 1. The first input will be the sentence to be converted 2. The second input is a collection of the briefs. Each brief is a collection itself, in which the first element represents the shortened form of that brief, while the rest of the elements are all strings that map to the brief. Example: [ [d, would], [m, much, more], [a, at, an] ] 3. The third and fourth inputs are collections of prefixes and suffixes. The first element of each prefix/suffix is the shortened form, the second element is a flag (of your choosing) that represents whether it is joined or dis-joined. Everything else are the strings that match the prefix/suffix. Prefix: [ [af, true, after], [n, false, enter, inter, intra] ] Suffix: [ [f, true, ful, ify], [f, false, ification] ] Sample Input: "a shipment of letters was delivered to the postshop", [["of", "o"], ["t", "to"], ["was", "os"], ["the", "th"]], [["sh", false, "ship"], ["d", true, "de"], ["po", false, "post"]], [["rs", true, "ers"], ["m", true, "ment"], ["d", true, "ed"]]  ## Rules, Assumptions and Freedoms • You may assume all input is lowercase letters. • A brief will always take priority over prefixes and suffixes. • you can indicate a dis-joined suffix/prefix however you wish, as long as you mention how you are indicating it. • The input may be rearranged however you like, as long as you specify how your input is structured • Output may be returned, printed or the nearest equivalent. ## Test Cases "a shipment of letters was delivered to the postshop", [["of", "o"], ["t", "to"], ["was", "os"], ["the", "th"]], [["sh", false, "ship"], ["d", true, "de"], ["po", false, "post"]], [["rs", true, "ers"], ["m", true, "ment"], ["d", true, "ed"]]  a sh-m o lettrs os dliverd t th po-shop "shorthand was once a common skill among woman", [["was", "os"]], [["sh", false, "ship", "short"], ["cm", true, "com"]], [["mn", true, "mon", "man"]]  sh-hand os once a cmmn skill among womn" "the electrician will be able to fix it", [["th", "the"], ["l", "will"], ["b", "be"], ["ab", "able"], "t", "to", "it"]], [["el", false, "electr"]], [["sh", true, "cian", "sion"]]  th el-ish l b ab t fix t • Looks like a nice challenge, I don't think there's much that needs to B clar-f-ed – Redwolf Programs Sep 7 at 14:12 # Keep the symmetry SANDBOX: I am aware that the language in this challenge, as it stands, is quite... fluffy. If anyone could help me firm it up, I would be grateful. Also, would this be better as a cops-and-robbers style challenge, where the cops are trying to make the output more symmetrical, and the robbers make it less symmetrical? Given a 2D array of 1s and 0s, flip a 1 to a 0 and output the resulting array. The output array must be "closer to being symmetrical" than the input. In the case where the array is already symmetrical, it must still flip a 1 to a 0, breaking as little symmetry as possible - e.g for 1,0,1 1,0,1 1,0,1  In the above case, changing the top-left 1 to a 0 will break symmetry in both directions, whereas changing the middle-left 1 will only break symmetry one way. The output must be in the same form as the input (so that your program or function could take it in again). ### What is symmetry? I am talking about reflectional symmetry along both the horizontal and vertical axes. Where the array has an even number of entries in a row/column, the axis is between the two central rows/columns: 1,0,|,0,1 1,0,|,0,1 -,-,-,-,- 1,0,|,0,1 1,0,|,0,1  otherwise it's down the middle of the middle row/column (and the numbers in that row/column count on both sides).  | 1,0,1 -1,0,1- 1,0,1 |  ### Some Examples Each pair of grids below is input .. output, which then becomes the next input, etc. iteratively: 1,0,0,1 1,0,0,1 1,0,0,1 1,0,0,1 1,0,0,0 0,0,0,0 0,0,0,0 0,0,1,0 .. 0,0,0,0 .. 0,0,0,0 .. 0,0,0,0 .. 0,0,0,0 .. 0,0,0,0 .. 0,0,0,0 1,0,0,1 1,0,0,1 0,0,0,1 0,0,0,0 0,0,0,0 0,0,0,0 0,0,0,0  1,1,1 1,0,1 1,0,1 1,0,1 1,0,1 1,1,1 .. 1,1,1 .. 1,0,1 .. 0,0,1 .. 0,0,0 1,0,1 1,0,1 1,0,1 1,0,1 1,0,1  • Is the program supposed to find the shortest path, or any path? Are we supposed to display each step? Should the choice of flipping a 1 to a 0 be random, or can it be calculated? A reference implementation would be very useful in this question. – Razetime Aug 26 at 13:03 • The program is only supposed to flip one, calculated, bit from 1 to 0 and return the new grid. so iterative calls to the program would ultimately lead to all 0s. I guess I'm unclear exactly how I want the concept to be translated into a challenge, which is why I put the sandbox text at the top – simonalexander2005 Aug 26 at 13:38 • The program must be trying to make the array symmetrical This needs to be defined precisely. What does it mean that the program "tries" to make it symmetrical? That repeated application of the program eventaully gives a symmetrical array? That it does it in a "small" (to be defined) number of steps? Same with as easy as possible: this needs to be defined precisely. I'm afraid I don't get the main idea of the challenge, actually – Luis Mendo Aug 26 at 17:21 # Balanced Beams Here are some examples of beams that balance: X Y A | X Y B Y --+-----+---+---+ | | | X X Y Y Y X X --+---- ----+-- + A X X Y | A B Y Y +---+---+-+-----+ | | | | B A | A AAB B A + --+-- --+-- + X Y X X | Y B X +-+-+---+---+---- | | | | Y A X Y Y X X X X + + + ------+----  The diagram will always be 17 characters wide and the top beam always balances in its centre. The other +s on the top beam indicate the point from which a lower beam hangs and the + on the lower beam indicates the point at which it balances. Your input does not need to include the |s if you don't need them. Lower beams with a width of 1 balance by default of course. The balancing of the top beam has to take the total weight of each lower beam into account. As you can see, for each example, there are two positions marked A and B where I have forgotten whether they should be an X or a Y. Please write a program a function which will accept the above diagram as input and output which of X and Y belong in each of the two positions A and B. Your output should be something along the lines of A=X, B=X although any unambiguous output suffices e.g. you could output the diagram with the A and B substituted accordingly or you could modify the input in-place. You do not have to output values for X or Y, although for each diagram they always have a fixed ratio which will allow all beams to balance. Other input formats could be acceptable but they need to get suggested as comments to the sandbox post. This is , so the shortest program or function that breaks no standard loopholes wins! ### Sandbox Question Do people think this is worth posting, given it only really requires a prime check along with getting digit prefixes? There are multiple implementations (possibly including hard-coding in some languages) to consider which might be enough. Please vote! Produce all 83 base-ten right-truncatable primes in as few bytes as possible in the language of your choice. • Order is irrelevant, but the production must terminate. • You may produce a list, a set, or an equivalent object. • You may print them (e.g. space-separated, each on a line, or formatted as a list or set (e.g. {2; 3; 293; 5; ...}) • You may give the numbers themselves as strings. • You may produce an iterator (but evaluating it must terminate). ### Right truncatable primes A right truncatable prime is a prime for which removing any number of trailing decimal digits is also prime. For example, $$\7193\$$ is a right truncatable prime since $$\719\$$, $$\71\$$, and $$\7\$$ are all prime. There are only 83 such numbers in base-ten, when sorted they are: [2, 3, 5, 7, 23, 29, 31, 37, 53, 59, 71, 73, 79, 233, 239, 293, 311, 313, 317, 373, 379, 593, 599, 719, 733, 739, 797, 2333, 2339, 2393, 2399, 2939, 3119, 3137, 3733, 3739, 3793, 3797, 5939, 7193, 7331, 7333, 7393, 23333, 23339, 23399, 23993, 29399, 31193, 31379, 37337, 37339, 37397, 59393, 59399, 71933, 73331, 73939, 233993, 239933, 293999, 373379, 373393, 593933, 593993, 719333, 739391, 739393, 739397, 739399, 2339933, 2399333, 2939999, 3733799, 5939333, 7393913, 7393931, 7393933, 23399339, 29399999, 37337999, 59393339, 73939133]  This is A024770 in the Online Encyclopedia of Integer Sequences. For some mathematician-written* Python see https://youtu.be/f2lEB4nMmyI. * Fair warning, it might well make you cringe. • I don't really mind prime challenges, just that most people who have been here a while have a stigma against it. Related. – Razetime Sep 5 at 14:26 • The code in the link contains what appears to be a partially censored racial slur, so I think you should probably drop the youtube reference. – FryAmTheEggman Sep 9 at 21:32 • Otherwise I think this is probably interesting enough, as these primes have several other non-prime features. It might be problematic if too many answers are just primality checks wrapped in terminating loops, though? – FryAmTheEggman Sep 9 at 21:35 • @FryAmTheEggman Oh wow, I didn't notice; that's pretty sad. – Jonathan Allan Sep 9 at 22:15 # Move the Knight! Your knight is on (0, 0) on an infinite (to all of the four edges, not just two) chessboard, and you need to move it to (a, b). You can use arbitrary (but finite) number of moves to do that. Since the chessboard is infinite, you can use squares with negative coordinates. Since you only have 2 knights (if no promotion occured) to type the program, your program needs to be as short as possible. ## Input The input is two integers, a and b. ## Output You output a sequence of characters, each represents a move. There are eight directions to move, so your output should contain eight distinct characters, each represents one direction. They can be any eight characters, as long as they are all unique. ## Test Cases The characters used here is:  A B C D N E F G H  0 0 -> "" 1 1 -> "GD" or "DEGD" or "DG" etc. 3 3 -> "DDDGGG" (one possible version) 2 3 -> "FGD"  ## Rules • Standard Loopholes are forbidden. • This is , so shortest code wins. • @Razetime I did... "They can be any eight characters, as long as they are all unique." – null Sep 15 at 12:30 • oh, sorry about that. – Razetime Sep 15 at 12:31 • @Razetime I intend to make this challenge have many different, unique, interesting approach, and which one is shorter highly depends on the language. – null Sep 15 at 12:33 # Do my data follow Benford's law or a uniform distibution? ## Background Benford's law, also known as the law of anomalous numbers, describes the distribution of the leading digit in many numerical data sets. Let $$\X\$$ be the leading digit of an observation (in base 10). According to Benford's law, $$\P[X=i]=\log_{10}(1+\frac1i)\$$ for $$\i=1\ldots 9\$$. For instance take the yearly reputation change of the top 1000 users on CGCC. For a user with reputation change 3522, keep only the leading digit, 3. Repeat this for all users, and you get this distribution, which is far from uniform: This has been shown to apply to vary different data sets, from town populations to stock prices, and is used to detect tax and election fraud. On the other hand, for some other data sets, the distribution of the leading digit is a uniform distribution: $$\P[X=i] = \frac19\$$ for $$\i=1\ldots 9\$$. Given some observed frequencies $$\(f_i)_{i=1\ldots 9}\$$, we shall measure the distance to these two distributions using the sum of the errors in absolute value: $$\\sum_i \left|f_i-\log_{10}(1+\frac1i)\right|\$$ and $$\\sum_i\left|f_i-\frac19\right|\$$, respectively. ## Task Take as input a list of non-zero numbers. For each number, keep only the leading digit, which is defined as the first non-zero digit. Compute the observed frequencies of leading digits, and output one of two values, depending on whether the observed frequencies are closer to Benford's law or to a uniform distribution. ## Input Input format is flexible. Note that input may include negative values, as well as non-integers. ## Output Either two consistent values, one for Benford's law and one for the uniform, or a truthy/falsey value. ## Test cases To be added This is , so shortest answer in bytes wins. # Finding the densest crossword puzzles I love crosswords, and nothing beats a super densely packed puzzle. But how dense can the puzzles get? Here's a sample puzzle I made a few years ago: Certainly not great, but can we do better? Given any list of characters, a crosswordification of that list is a crossword puzzle consisting of characters from that list. For example, given the list ['b','a','d','a','d'], the following is a valid crosswordification: but this isn't Clearly, the order of the list is irrelevant. Given a valid crossword, the area of the crossword is the area of the smallest rectangle containing the crossword. In the above examples, the smallest rectangle containing the crosswords are 3x3 squares, which have area 9. # Challenge In this challenge, you must write a function which takes two arguments • A list-like structure containing english characters • A list-like of valid words consisting of english characters and outputs an integer, representing the minimal area of a crosswordification of the list of english characters, where the second input defines the set of valid words. I will be using this english dictionary for my test cases. Any code that is used to import/parse the dictionary into a list-like structure won't be counted in the byte-count, just the function. # Test Cases More to be added: ['d','a','a','a','t','n','m'] -> 7 (adamant is a word) ['k','a','s','a'] -> 6  • Here's what I understand: Our programs need to calculate the smallest possible corssword from the given characters, display the size alone. correct? – Razetime Sep 17 at 5:04 • @Razetime correct – Don Thousand Sep 17 at 13:51 • Do you suspect there is any other way to do this apart from brute forcing all possible arrangements and picking the minimal area one that meets the requirements? – Sisyphus Sep 18 at 4:40 • @Sisyphus yes, but not revealing, as thats part of the challenge – Don Thousand Sep 18 at 11:17 • "one or more of the options for the longest palindromic run of digits in its binary representation can be removed" Does this mean I can remove several runs? For example, 945770 = 11100110111001101010_2 has 110011 as the longest palindromic run, it occurs twice and if I remove both occurrences, the result is 10101010. On the other hand, 944522 = 11100110100110001010_2 has 110011 and 001100 as longest palindromic runs, and removing both gives 10101010. – Zgarb Sep 12 at 10:25 • Don't forget Dennis, Dennis 2.0 or Calvin numbers :P – caird coinheringaahing Sep 12 at 15:37 • @Zgarb No; you should only remove a single run before splitting the remaining digits. I've clarified this in the challenge text. – sporeball Sep 13 at 0:50 • I think the notation is fine, you could let people use any 4 distinct characters instead. You should mention that gravity is tward the center of the pattern. – Razetime Sep 18 at 2:33 • left/right/up/down is more suitable for dominoes, I think. I don't know how walls and splits would change this, but go for it if you're fine with lesser answers. finding if a target domino falls is a different question altogether. – Razetime Sep 18 at 2:35 • @Razetime There's no gravity, the example just happened to go towards the center. The direction relies solely on the pieces (I'll clarify that) – user Sep 18 at 17:09 • You mix a lot of terminology about the directions, i.e. using "north" and "below" in the same description. I think you would be better off editing the descriptions to all use the same convention. Separately, truthy and falsy aren't really good terms to use, since some languages don't have a concept of truth. I'd recommend saying something like "one consistent value for true and anything else for false or the reverse", or something similar. – FryAmTheEggman Sep 18 at 18:10 • Related, outputting the result after dominoes fall in 1D. – xnor Sep 18 at 20:56 • @FryAmTheEggman I started out with just north/south/east/west, and then changed it after Razetime's comment. I guess I left out some parts. I will change the falsy/truthy part too – user Sep 18 at 23:39 ## The ASCII character countdown! answer-chainingrestricted-source Your task is simple: Choose any printable ASCII character that's not chosen in the previous answers. And then, you need to print your chosen character in your program to standard output. (You can ONLY print your chosen character, without printing other garbage to STDOUT) ## The catch Let's say you picked x as your chosen character, and your answer is the answer numbered y. You have to insert y x's into the previous source code, at any position you like. For the first answer, the previous answer is the empty program. ## An example Answers have to start with the number 1. So for example, I chose the character #, and I posted a 1 byte answer in /// that prints the # mark. #  And then, the second answer (numbered 2) has to insert 2 of their picked x character into the previous source code, such that the modified code will print their x character. So assume this is written in Keg: x#x  And then, the third answer has to do the same, and so on, until 95 is reached. ## The winning criterion & other rules • The first user whose answer stays without a succeeding answer for a month wins the challenge. If that's not satisfied, the first person who reaches the number 95 wins the challenge. • You are not allowed to put any other character in your code other than printable ASCII characters. • You need to wait for an hour before posting a chaining answer. • You need to wait 2 answers before you post a new answer after your submission. • Please make sure your answer is valid. If yours is not valid, chaining answers aren't allowed to be posted. • The answers are allowed to be in different languages. • Each submission doesn't have to be in a unique language. • You could only insert y x's into the source code. • Can the answers be in different langauges? – fireflame241 Jul 20 at 4:03 • What is the motivation for the number 95? – fireflame241 Jul 20 at 4:03 • This isn't a radiation hardening challenge, as those require programs to still work / do something different if any single character is removed. – Lyxal Jul 21 at 9:15 • @fireflame241 Because there are 95 ASCII characters of course... – user202729 Jul 21 at 12:50 • Must we only insert y xs, or may we also insert other (printable ASCII) characters apart from our chosen character? If the latter, are the additional characters limited to those not already used in previous answers? – Dingus Jul 21 at 15:02 • "I chose the character ?" -> "I chose the character #"? – user202729 Jul 22 at 6:10 • "has to insert their picked x character into the previous source code," -> edit this part too. – user202729 Jul 22 at 6:11 • @Dingus Now you may only insert y xs. – user92069 Jul 23 at 0:56 • "I chose the character ?" has crept back in. Other than that it's clear now. (Seems difficult too, but maybe not in the golfing langs - I don't know.) – Dingus Jul 23 at 2:18 # Bit delivery in Bin Citycode-golfbinary posted • It could help a lot to add an illustration for small test cases (how to move each bit in the input to the output), and some test cases with more bytes (both even and odd). Other than that, looks good to me. – Bubbler Mar 31 at 1:57 • @Bubbler Thanks for the feedback. How's it now? – Noodle9 Mar 31 at 14:32 • Perfect, and +1 for reference implementation. – Bubbler Mar 31 at 23:00 ### I have abandoned this challenge. If you would like to take it over, feel free to take the idea, and maybe leave a comment so people know you've taken over. # Will it rain? image-processingpopularity-contest (See revision history) • If you have to ask if pop-con is appropriate here I think this challenge is already doomed as a pop-con. But why don't you use it as a test-battery-challenge and use the percentage of correct ones as a criterion? – flawr Aug 8 '17 at 21:40 • This challenge rests on the test cases, if the skies have distinct features in them when it rains to when it won't i.e. darker it should be fine. If they all look similar it will never work. – TheLethalCoder Aug 9 '17 at 10:44 ### I have abandoned this challenge. If you would like to take it over, feel free to take the idea, and maybe leave a comment so people know you've taken over. # Make a program run infinitely code-golf (See revision history) • I don't really understand what 'push' and 'pop' mean thus the operator section is a little confusing to me. Also I think you need to include ; in the list of characters that one can make a bijection from. Also, would it make sense to swap the \  and / commands? If you do the characters would represent mirror planes (or plain mirrors) but now they seem a little counterintuitive to me. – dylnan Nov 16 '17 at 19:45 • @dylnan 1. push and pop are stack operations meaning put a value onto the top of the stack and remove the top of the stack and return its value, respectively. So for example, push pop + pop means pop a value off the top, pop another value off, add them, and push it onto the top of the stack. Also, yes, I missed ;, thanks for noticing. Also, I got confused by my own wording so yes, \/ should be swapped. Thanks for the comments! – HyperNeutrino Nov 16 '17 at 20:07 • So, if I understand, the submissions will take code in the 2D language as input, and the output will be values that, when fed into the input code, would cause it to run infinitely? – Kamil Drakari Nov 16 '17 at 20:30 • @KamilDrakari Yep. – HyperNeutrino Nov 16 '17 at 20:43 • How would the conditionals ! and ? deal with the stack? In your second test case, if the stack is 01 (say the right is the top) and the first ? sees the 1, wouldn't the stack have to be popped in order for the second ? to see the 0 and move into the infinite loop? – dylnan Nov 17 '17 at 1:21 • Also, I think is too hard due to the halting problem. Even with the busy beaver Turing machines it becomes very difficult to determine whether a machine will halt with machines of only a few states. Maybe if you somehow restrict the possible modes of running infinitely (e.g. program will only run infinitely if it gets into <^>v or <v>^ loops) and restrict the length of the program but even then I think it might be too hard but I'm not sure – dylnan Nov 17 '17 at 1:44 • @dylnan It theoretically shouldn't be too impossible because you can just go through all possible states and if it ends up in the same state as before, it will loop infinitely (because there are no non-deterministic commands). It will be horribly inefficient, but eh, it's code-golf, efficiency is not the priority :P – HyperNeutrino Nov 17 '17 at 1:59 # C Code Compressor (WIP) Your task is to create a lossless compression scheme that is optimized for ASCII-only C code. Whitespace and indentation should be preserved. Your score is the total compressed size of various samples from well known open source C projects. A sample of the largest few files will be taken from one specific commit. Both header files and source files will be included from the following projects: • The CPython Interpreter • The Linux Kernel • Git Comments will be stripped from the source files for the set of scoring, therefore you do not need to optimize for comments, however you still need to handle them. An additional file will exist in the corpus that ensures this is handled by your code. • Once you reveal the test cases, couldn’t I just create an “encoding” where 1 represents the Linux kernel, 2 represents the Git source, etc? And if the test cases aren’t fixed but can change if an answer overfits some, then is there really an objective winning criterion? – water_ghosts Oct 10 at 7:26 • @water_ghosts Optimizing exclusively for the test cases given is one of the standard loopholes – Sara J Oct 10 at 13:02 • Are you planning on scoring based entirely on compression amount, or also on code size? Seems like it will be a fun challenge, especially is code size is part of it. – Redwolf Programs Oct 10 at 22:05 # dimensional flipper maze test-battery (need a better name) You're stuck in a maze in one corner, and you want to get to the other corner. However, this maze is unfortunately one dimension higher than you (for simplicity of explanation, you are 1D and it is 2D). Thus, you can only see along one hyperplane of the maze. However, you were granted the magic ability to rotate yourself to see along a different axis (for the 1D-2D explanation, you are on a grid only able to see one row/col, but you can switch which you see). You want to figure out how to get to your destination as fast as possible, but it's hard to devise an optimal strategy when you can't see the whole room, so you'll have to do your best. ## Challenge Requirements Your program needs to be in one of two forms. In the first form, it needs to be interactive; that is, you will be given what you can see, and then you output your move, and your program remains running until the simulation completes. In the second form, it needs to be stateful; that is, you will be given what you see and a memory object, and you output your move and a new memory state, and your program will be run once per step. This is a challenge, so the score will be determined by the number of moves total on the official test data, and a lower score is better, no tie-breaker as I will not accept any solution. ## Input Each step, if you are interactive, you need to read one line of input, and if you are stateful, you need to read two lines of input. The first line of input will be two space-separated integers representing the distance along your row/col to the closest barrier/wall on either side. Note that when you start, at least one of these values will always be 0 because you start in a corner. The second line of input in the second case will be the string representation of a JSON object. This is your memory object. ## Output After receiving input, you must output either one line if you are interactive and two lines if you are stateful. The first line of output represents your move. You may output any distinct values for "move towards right" (this will increase the first gap value and decrease the second gap value both by one), "move towards left" (same, but opposite), "rotate clockwise", and "rotate counterclockwise" (technically, you only need to be able to rotate one way, but for quality of life I'll allow rotating both ways even though you could just invert your moves). By default, these are R, L, C, A, but you can change these in the interactor, just specify what you're using (I recommend just using the defaults; this isn't code-golf anyway). The second line of input, if applicable, represents your memory object. It must be a valid JSON object; if not, your memory object will be discarded and you will be given an empty object the next time. If you are interactive, remember to flush after outputting all necessary information, otherwise the interactor may never receive your output and just wait indefinitely. If you output a move that puts you on square (64, 64), your program will be killed / not called again. ## Scoring A total of 10 random maps have been selected. Note that every map is 64x64. Your score is the number of moves you output to get from square (1, 1) to square (64, 64), totaled across each map. If anyone doubts my selection, you may request me to publicly release the data, or if anyone suspects any solution of specific optimization, you may request me to regenerate test data. The lowest score wins. # Meta • I think this is my first time doing ; is this appropriate? • does this challenge really have any solution/strategy, or is a random brute force always going to be considerably competitive? • is it a duplicate? I will generate sample inputs and the test data and post a checksum if this challenge seems well-received, as well as create an interactor. # Three points on Poincaré disk ## What is Poincaré disk? Poincaré disk is a projection of 2-dimensional hyperbolic geometry to the 2-dimensional Euclidean plane, or more precisely, onto the open disk $$\\{(x,y): x^2 + y^2 < 1^2\}\$$. ## Objective It is well-known that three distinct points on the Euclidean plane are either on a unique line or on a unique circle. Let $$\S\$$ be that line/circle. The inverse image of $$\S\$$ is one of line, circle, horocycle, or hypercycle. Determine which. ## Classification The points are assumed to be on the disk. • If $$\S\$$ is a circle that lies on the disk, the inverse image is a circle. • Otherwise, if $$\S\$$ is a circle that shares a tangent with the boundary of the disk, the inverse image is a horocycle. • Otherwise, if $$\S\$$ crosses the boundary of the disk orthogonally, the inverse image is a line. • Otherwise, the inverse image is a hypercycle. ## Input The cartesian 2-dimensional coordinates of the points. A coordinate can be given as either two real numbers or one complex number. Other than that, the input type and format doesn't matter. This includes: • A tuple of size 3 • A list of size 3 • A set of size 3 Invalid inputs fall in don't care situation. This includes: • Not exactly 3 points • Non-distinct points • A point not on the disk ## Output Output type and format doesn't matter either. This includes: • Enumeration type of 4 possible values • Bit field of size 2 ## Example Assuming there were no floating-point errors: • $$\\{(-½,0),(0,½),(½,0)\}\$$ must give a circle. • $$\\{(-½,½),(0,0),(½,½)\}\$$ must give a horocycle. • $$\\{(-½,0),(0,0),(½,0)\}\$$ must give a line. • $$\\{(1-\sqrt{¾},½),(1-\sqrt{½},1-\sqrt{½}),(½,1-\sqrt{¾})\}\$$ must also give a line. • $$\\{(0,½),(¼,¼),(½,0)\}\$$ must give a hypercycle. • $$\\{(0,0),(¾,0),(0,¾)\}\$$ must also give a hypercycle. • Can the coordinates $(x,y)$ be represented as a complex number $x+yi$? – caird coinheringaahing Oct 11 at 16:43 • @cairdcoinheringaahing Yes. – Dannyu NDos Oct 11 at 21:02 • It looks like solutions might have trouble with the line and horocycle cases due to float precision, if either they take values like sqrt(2) to finite precision or introduce imprecisions in the calculations. Can some allowance be made for this? I'm not sure how though. – xnor Oct 12 at 2:09 • @xnor If the input is IEEE floating-point numbers, they are in $\mathbb{Z}[½]$ anyway and must be regarded as such. If your language is able to do symbolic computation, you may go ahead. – Dannyu NDos Oct 12 at 3:15 # Compactify the real numbers to a group (WIP) ## Objective Let $$\X = \mathbb{R} \cup \{\infty\}\$$. The $$\\infty\$$ is the point at infinity and doesn't have a signature. Let $$\Y = \{\exp(i\theta) : \theta \in [0,2\pi)\}\$$, which is the unit circle on the complex plane. Make $$\X\$$ a group by giving $$\X\$$ a binary operation, so there will exist a function $$\f : X → Y\$$ that is both an isomorphism and a homeomorphism. Your code shall implement the binary operation. $$\f\$$ doesn't need to be implemented to a code. ## Group A set $$\G\$$ endowed with a binary operation $$\*\$$ is a group iff: • For every $$\a,b,c \in G\$$, $$\(a * b) * c = a * (b * c)\$$ • There exists the identity element $$\e \in G\$$ such that for every $$\a \in G\$$, $$\e * a = a * e = a\$$ • For every $$\a \in G\$$, there exists $$\b \in G\$$ such that $$\b * a = a * b = e\$$ $$\Y\$$ is a group, where the binary operation is the multiplication. ## Isomorphism Let $$\*\$$ denote the binary operation given to $$\X\$$. A function $$\f : X → Y\$$ is an isomorphism iff: • $$\f\$$ is bijective • For every $$\x,y \in X\$$, $$\f(x*y) = f(x) × f(y)\$$ Note that once appropriate $$\f\$$ is identified, $$\*\$$ can be automatically defined as $$\x * y = f^{-1}(f(x) × f(y))\$$. ## Topology A subset $$\A \subset X\$$ is open iff, for every $$\x \in A\$$: • If $$\x \in \mathbb{R}\$$, there exists $$\P \subset A\$$ such that $$\x \in P\$$ and $$\P\$$ is an open interval • If $$\x = \infty\$$, there exists a subset $$\P \subset A\$$ such that $$\x \in P\$$ and $$\P\$$ is the union of two open rays to the opposite directions A subset $$\B \subset Y\$$ is open iff, for every $$\y \in B\$$, there exists a subset $$\Q \subset B\$$ such that $$\y \in Q\$$ and $$\Q\$$ is an open arc. ## Homeomorphism A function $$\f : X → Y\$$ is a homeomorphism iff: • $$\f\$$ is bijective • For every open subset $$\A \subset X\$$, its image $$\f[A]\$$ is open in $$\Y\$$. • For every open subset $$\B \subset Y\$$, its inverse image $$\f^{-1}[B]\$$ is open in $$\X\$$. ## Rule You may represent $$\\mathbb{R}\$$ as a floating-point number. Every floating-point error will be tolerated in this regard. ## Example An example of $$\f\$$ is: $$f(x) = \exp(i × 2 \arctan \frac{x}{2})$$ where $$\\arctan \infty = \frac{\pi}{2}\$$, and we identify $$\*\$$ as: $$x * y = 2 × \tan (\arctan \frac{x}{2} + \arctan \frac{y}{2})$$ where the identity element is $$\0\$$, and the inverse element of $$\x\$$ is $$\-x\$$ when $$\x \in \mathbb{R}\$$, or $$\\infty\$$ if $$\x = \infty\$$. ## Ungolfed solution ### Haskell This implementation abuses the fact that IEEE floating-point numbers can encode infinities. Both positive infinity and negative infinity will be treated the same in this regard. import Data.Semigroup import Data.Monoid import Data.Group newtype CompactR = CompactR Double deriving (Eq, Show, Read) instance Semigroup CompactR where CompactR x <> CompactR y = CompactR$ 2 * tan (atan (x/2) + atan (y/2))

instance Monoid CompactR where
mempty = CompactR 0

instance Group CompactR where
invert (CompactR x) = CompactR (negate x)


You implement only <>. The others are just details.

# Sandbox questions

This challange turned out to be too easy.

What if I asked about one-point compactification of $$\\mathbb{C}\$$ instead of $$\\mathbb{R}\$$?

• I think even just f(x,y)=(x+y)/(1+xy) works for the real case – xnor Oct 14 at 8:01

# How many buckets of paint do I need?

Consider a grid of positive integers, like so:

2  2  2  2  4

5  5  5  3  3

2  2  5  5  3


Consider the "paint bucket" operation on this grid. We target a certain cell, and consider the region of contiguous, orthogonally connected cells starting from that region. We then replace all elements in that region with another number. For example, if we targeted the cell at $$\(0,0)\$$, we would have this region:

2--2--2--2  4

5  5  5  3  3

2  2  5  5  3


Let's say we replace all elements in the region with a 0. The grid looks like this after the transformation:

0  0  0  0  4

5  5  5  3  3

2  2  5  5  3


If we were to repeat this process until the grid consisted only of 0s, we would have something like the following. (The particular order in which the regions are filled is arbitrary.)

Step 1:
0< 0< 0< 0< 4
5  5  5  3  3
2  2  5  5  3
--------------------
Step 2:
0  0  0  0  0<
5  5  5  3  3
2  2  5  5  3
--------------------
Step 3:
0  0  0  0  0
0< 0< 0< 3  3
2  2  0< 0< 3
--------------------
Step 4:
0  0  0  0  0
0  0  0  0< 0<
2  2  0  0  0<
--------------------
Step 5:
0  0  0  0  0
0  0  0  0  0
0< 0< 0  0  0


Need examples? Try it online!

Challenge: Given a grid, what is the number of paint bucket operations do we need to fill this grid with 0s, assuming we fill a new region with each operation?

## Rules

• You can take input and receive output in any reasonably method (see: Default for Code Golf: Input/Output methods)
• Your input is a grid, and your output is a number.
• You can assume the input will be a regular (non-jagged) grid.
• You do not have to use 0 as your intermediate for filling the grid; it just must be an integer different from all other integers in the input grid. Since the input grid is of strictly positive integers, it is guaranteed that 0 does not appear in the input, but this does not mean you must use 0.
• Further, you do not even have to interface with integers. A grid of objects which contain an equivalent amount of information as a grid of integers would suffice just as well. You may, for example, take input as a 2D string of characters. You must be able to support at least 31 distinct input values (with the 32nd value being the intermediate for filling the grid), so something like a grid of boolean values would not be sufficient for this challenge.

## Test cases

input
output

[[2, 2, 2, 2, 4],
[5, 5, 5, 3, 3],
[2, 2, 5, 5, 3]]
5

[[1, 1, 1, 1, 2, 2],
[2, 2, 2, 2, 2, 2],
[3, 5, 5, 5, 4, 5],
[3, 5, 4, 5, 4, 5],
[3, 3, 3, 3, 4, 4]]
7

[[1, 1, 1, 1, 2, 1],
[1, 2, 2, 2, 2, 1],
[1, 2, 2, 3, 2, 1],
[1, 2, 3, 3, 2, 1],
[1, 1, 3, 1, 1, 1],
[1, 1, 1, 1, 1, 1]]
3

[[1]]
1

[[1, 2],
[3, 4]]
4

• Hmm ... this feels familiar; think we might've had it before but with a different backstory. – Shaggy Oct 15 at 21:05
• @Shaggy I can't find any related challenges under "paint", so if it's a dupe, it would seem to have a very different backstory – Conor O'Brien Oct 16 at 0:45

Inspired by this challenge, which got closed.

Cops will provide a program/function and a flag. Robbers will guess a password. When the password is given to the cop's program, the flag should be outputted.

## Cop rules

• The flag, the program, and the language of the program should be provided.
• The flag can be an integer, string, or value of any other type
• The flag may be printed to STDOUT, returned from a function, or using any of the other standard output methods.
• The program/function should can take the password through STDIN, as a function argument, or using any of the other standard input methods.
• There must be at least one valid password that causes your program to return the flag, and you should know at least one of those passwords when posting your answer.

## Robber rules

• When the cop's program is given the password you guess, it should output the flag.

Cops's score will be the number of bytes their code takes up.

Cop answers will be safe if they haven't been cracked for two weeks.

Cop:

## Scala, 4 bytes

x=>x


Flag: "Yay, you cracked it!" (the type is String)

Robber:

## Questions for Meta:

• I tried to make this as simple and clear as possible, but am I making the same mistakes as the other challenge?
• Should I limit how many possible passwords there can be, so that cops don't make robbers brute-force RSA or something?
• For function submissions, should I require the rest of the program to be added separately, so there's some context? Or should I require all submissions to be full programs (I think that would be a disadvantage to some)?
• Should I change the scoring of cops to take into account the number of possible passwords?
• Is this a duplicate? This is similar, but with only numbers, and I think this question is different enough.
• I'd be very surprised if this hasn't been done before. – Shaggy 2 days ago
• Well, this is similar, but it's only about numbers and encourages cryptographic functions – user 2 days ago
• This is also similar, but I tend not to mind similar cops-and-robbers challenges because it's really hard to come up with something completely novel. – Sisyphus 2 days ago
• As the author of the original, I think this is much clearer than mine :p. Using crypto functions in cops is now a standard loophole, so that shouldn't be an issue. The only thing I think is slightly unclear is the passwords; would they be a specific type chosen by the cop, or is any type in the language allowed as a password? – Redwolf Programs yesterday
• @RedwolfPrograms If the language has muliple data types, then the cop must specify which it is. And I'm thinking that if a cop submits a function, they should also give a full program separately using that function, so that people using Java and other languages have an idea of what type they're supposed to give that function. – user yesterday

## Write a compiler/interpreter for ...

Inspired by the lisp challenge here.
It is a series of puzzles.

I don't like to see a simple eval solution, so:

• interpreting the language is fine
• translating the language to a different language is fine.

I think this is specific for each language.

Only the syntax and the basic commands.
Also specific.

Winning criteria should not be code golf.
The goal should be that you can "learn" an other language by looking at the code.

Languages that might be good candidates:

• Lisp
• APL
• J
• Whitespace
• Forth
• This only works for languages which are small and well defined. BF fits those criteria. Whitespace does too. The others may not. Lisp and Forth have so many dialects that you would have to specify exactly which dialect to support; Lisp, Forth, APL and J might have too many built-ins to fit in an answer: there are character limits. – Peter Taylor May 12 '13 at 15:16
• You don't have to provide all the built-ins, but that is why it is here. – Johannes Kuhn May 12 '13 at 15:38
• What defines the "basic commands"? – ASCIIThenANSI Aug 31 '15 at 17:54
• I don't know? Maybe that you can do the basic stuff with it like +,-,print,... – Johannes Kuhn Aug 31 '15 at 18:22
• I suggest a programmer can implement the tiniest subset of those languages in order to be Turing-complete, as these are non-trivial subsets that can theoretically simulate the rest of the language... – user85052 Jun 28 '19 at 4:17
• Which human is learning the programming language by looking at the code? – MilkyWay90 Aug 26 '19 at 3:23

# Find Maximum number of 4+ letter words from Scabble Tiles

The challenge is to find the most words with 4 or more letters you can make with one set of scrabble tiles.

The tile distribution is as follows:

2 Blank Tiles
A 9  N 6    +====+===========+
B 2  O 8    | 01 | K J X Q Z |
C 2  P 2    | 02 | B C M P F |
D 4  Q 1    | 02 | H V W Y * |
E 12 R 6    | 03 | G         |
F 2  S 4    | 04 | L S U D   |
G 3  T 6    | 06 | N R T     |
H 2  U 4    | 08 | O         |
I 9  V 2    | 09 | A I       |
J 1  W 2    | 12 | E         |
K 1  X 1    +====+===========+
L 4  Y 2
M 2  Z 1


Valid words are any words that are 4+ that are available in this file, the official scrabble dictionary.

Tiles cannot be used twice. This means you can only have 1 word with a K, J, X, Q, and/or Z unless you use a blank tile to represent one of these letters.

I'm not sure how I'd do scoring on this. I want shorter code to score better, but I don't want a short piece of code that finds a lot less words to score better than a longer piece that finds many more words.

• Meh. I don't like dependency on external files; are we allowed to load it, or even embed it into the source code? – John Dvorak Dec 17 '13 at 20:00
• as for finding more vs. shorter code, you could demand all words be found – John Dvorak Dec 17 '13 at 20:19
• @JanDvorak Any way to use it. It's a text version of the official scrabble dictionary, it seemed to be the most fitting word list for the task. "All words being found" might be hard, considering there are probably many combinations of words that would deplete all the tiles. It's a maximum of 25 words, (25 words, 4 letters each, 100 tiles), but I don't know if it's possible to use all tiles with just 4 letter words. After so many words, you might not have enough tiles to make an actual word, which means you'd either have to go back or accept that you're not using all the tiles. – Rob Dec 17 '13 at 20:23
• As currently described, this is a no-input task, which means that the answer can be precomputed and then the program only needs to decompress it. Consider rewriting it to take input (either of the word list or of the tiles available). – Peter Taylor Dec 18 '13 at 8:01
• I suggest taking a list of tiles as input, loading the list of words from a predefined file and requiring all combinations / best combination to be found. Of course, if the input is the full list of tiles, the computation is going to take ages. I might allow preprocessing the word list outside the program itself (up to a certain point; a linearithmic growth?) – John Dvorak Dec 18 '13 at 8:32
• I suggest modifying this so that input is a list of tiles, limited to a full rack or less (therefore 4-7 tiles, since our minimum word length is 4). Input should be assumed to be valid based on the standard set of tiles (e.g.: it wont' have something like 3 J's or 4 G's). This would have some practical use for a player in a scrabble game to figure out their next move (though it does not take into account tiles available to them which are already on the board). – Iszi Dec 18 '13 at 21:14
• Alternative mode: Input is a list of tiles, maximum 96 (so that at least 4 are remaining in the set). Output only includes words (minimum 4 letters) which can be created without those tiles. This would be interesting as it provides words that may yet be created (though, again, not taking into account usable tiles on the board) at a given point in the game. – Iszi Dec 18 '13 at 21:15
• Output needs to be decided as either a list of all possible words, or only the highest-scoring word(s). Another enhancement may be to require that the list be sorted descending in order of score (if output is all words), then ascending alphabetically. There's no reason to take each program's output into account for scoring. Since everyone is expected to use the same dictionary, all programs' outputs should be identical (except perhaps in sorting, if that's left out of the spec). So, this should be Code Golf. – Iszi Dec 18 '13 at 21:15
• It's also worth noting that, as currently written, the task could just be to filter the given dictionary down to words which have 4 or more letters. By its very nature, the Scrabble dictionary should already exclude any words that cannot be made with a Scrabble set. – Iszi Dec 18 '13 at 21:18
• @Iszi it's not "what are all the words you can make", it's "what are all the words you can make, where every letter used depletes a tile". There's a max of 25 words if you can use all 100 tiles. – Rob Dec 19 '13 at 16:40
• I think I misunderstood the problem, then. I thought it was "all the words possible using a set of tiles" not "all the words possible, using only one set of tiles". Still, my point about code golf remains. There is an absolute maximum to the number of words (each with 4 or more letters) you can make with a single Scrabble set, and a finite number of permutations which can be used to hit that maximum. Every program written with this goal should end up with the same (or nominally similar) output. – Iszi Dec 19 '13 at 16:56

# Test for Irreducible Complexity (Check for Redundant Characters)

I may need some additional help coming up with the full spec for this competition. As of right now, this is just a concept.

Many interesting questions, such as the "42" question in this sandbox, involve finding the longest program which is not reducible. This means that no set of characters can be removed and still allow the program to function as desired.

The basic idea is that your program will test a Base Program to make sure that it contains no redundant characters. The input will consist of:

• Expected Output

Your program will simply evaluate all possible subsequences of the Base Program and verify that none of them give the Expected Output.

This challenge actually has a utility value to several other challenges. For example, it verifies the results of a "longest non-reducible"-type challenge. In addition, it could make sure that a golfed solution cannot be golfed further.

I assume that the winning criteria will be fastest program, as cycling through all the possibilities takes a long time.

## Problems

A sequence of length N has 2^N subsequences. Even if each evaluation is done very quickly, it might be unfeasible to test any program with more than 20 or so characters in a reasonable amount of time.

• Problem: some subsequences of legitimate answers may be pretty dangerous to the environment. You don't want to eval just everything. – John Dvorak Dec 23 '13 at 16:59
• @JanDvorak Yes that actually is a serious problem. To what extent is it possible to fix that? – PhiNotPi Dec 23 '13 at 17:04
• Forbidding any program with dangerous subsequences? :-) – John Dvorak Dec 23 '13 at 17:05
• A more reasonable (but very difficult) solution would be the requirement to implement a sandbox. – John Dvorak Dec 23 '13 at 17:07
• Even without dangerous behavior, the halting problem will be an issue: it's hard to tell whether a shortened program will terminate at all, especially for every conceivable input. – MvG Jan 7 '14 at 23:49

# Popularity Contest: Implementation of a Hash Table

Create a class in some OOP language for a hash table that supports getting, setting, and removing values. You can't use the built in hash table/dictionary/map implementation. Highest votes in one week wins.

A key is any valid string. A value is any valid string, number, or boolean.

Example functionality:

hash.set("key","value");
hash.get("key"); // returns "value"
hash.set("key", 1234);
hash.get("key"); // returns 1234
hash.set("key2",hash.get("key"));
hash.get("key2"); // returns 1234
hash.delete("key");
hash.get("key"); // returns null/undefined/none/etc. or throws an error
hash.get("key2"); // still returns 1234


Definition of a hash table (from Wikipedia):

In computing, a hash table (also hash map) is a data structure used to implement an associative array, a structure that can map keys to values. A hash table uses a hash function to compute an index into an array of buckets or slots, from which the correct value can be found.

The hash table cannot be simply an array that is searched in linear time. It must be an actual hash table that uses a hash function to map the keys to the value.

• Popularity contest and shortest don't mix. That aside, the spec is too vague. What is a "value"? What assumptions can be made about hashcodes? If the language makes all types nullable, should null be permitted as a key? What should the type be in languages which have co- and contravariance? And for that matter, what qualifies as a "hash table", bearing in mind that people will try to exploit any loophole? – Peter Taylor Jan 2 '14 at 23:16
• @PeterTaylor Thank you for the feedback! Please see my edits, and let me know what you think. Could you meant about co/contravaraince? I looked at the wikipedia article about it but I'm not really sure how that has anything to do with this question. – hkk Jan 2 '14 at 23:37
• I think it's still vulnerable to the loophole of "I have a hashtable with one bucket" (i.e. it's really a list of (key, value) pairs which I traverse in linear time). The thing about variance is to do with static typing of the elements of the map. E.g. in Java Map<String, Integer>'s get method has signature public Integer get(Object); in C#, a Dictionary<string, int>'s Get method has signature public int Get(string). The edited version makes it clear enough that the hashtable isn't expected to be genericised. – Peter Taylor Jan 3 '14 at 0:08

# Wordlist detector

You are to write a program which, given a list of words, constructs a regular expression to match all these words but nothing else. Both your program and the constructed regular expressions are to be as short as possible.

## Input and Output

Input comes on standard input and consists of one line giving n, the total number of words, followed by n lines with one word each. The number of words will be less than 1000, the length of each word less than 30. Words will consist only of lower case ASCII letters, i.e. a-z. You may choose to ignore the first line and use EOF instead to end the list.

Output shall be written to standard output. It consists of a single line, giving a POSIX extended regular expression to match these words and no others. Since input for this regex is not restricted to letters only, elements like . or [^…] won't make too much sense, which limits the language in a natural way. You may choose whether you want to terminate the line with a newline or not. Programs may choose to print multiple lines of output, in which case only the last one will be used for scoring. So you might print intermediate results and continue searching for improvements.

## Test cases

Each submission may be accompanied by one regular expression. When scoring the submissions, I'll use this regular expression to reconstruct a word list from it. The code to do this reconstruction can be found at the end of this post. The reconstructed word list must fit the input specification above in terms of word count and length. It would be nice if your own program would be able to regenerate that regular expression from the word list, but that is not a strict requirement. But please don't paste bogus programs just to submit a challenging regular expression, though.

These test cases will be collected and fed to all programs for scoring.

## Scoring

The final score of each program will be the program size plus the size of all its generated regular expressions for the inputs collected from submitted answers, including the example from this question. So short code which produces too long results might get beaten by longer code which generates shorter expressions.

Does this still qualify as ?

Submissions which generate an incorrect regular expression for one of the test cases will be disqualified, as will those which don't terminate in the allotted time. You can use the input reconstruction program below to check whether a produced regular expression does encode the correct word list.

## Requirements

All submissions are welcome, but in order to include your submission in the tournament, it must be executable with reasonable effort on my Linux machine. It shouldn't depend on any exotic libraries, or any specialized ones which take too much work away from your own program. It must operate in reasonable time, say no more than five minutes per input. Your output must be reproducible, so if you use randomization at some point, please seed the randomizer, and please don't terminate an improove loop by a timer measuring execution time or some such.

## Tournament times

I'll run the first major tournament two weeks after posting this question. I'll include a table of the results in this question. I'll try to run tournaments repeatedly as late submissions arrive, but I'll not promise any regular schedule.

## Example

An very simple example application would be in Python 3 (53 chars):

print('|'.join(input() for i in range(int(input()))))


And here is a test case which could be posted along with the program, although this program obviously doesn't generate exactly this concise output:

bann?ana|ap(fel|ple)|s[ou]n|[hs](a|ou)nd


The expansion of that expression could be turned into the following example input, which need not be posted as part of an answer since it can be deduced from the regular expression:

10
banana
bannana
apfel
apple
son
sun
hand
hound
sand
sound


## Regex expander program

And here is a program to turn regular expressions into word lists, again written in Python 3.

#!/bin/env python3
concat = set(('',))
altin = set(('',))
altout = set()
prev = None
stack = []
regex = iter(input())
for ch in regex:
if ch == '(':
stack.append((concat, altin, altout))
altin = concat
altout = set()
prev = None
elif ch == ')':
concat.update(altout)
prev, altin, altout = stack.pop()
elif ch == '|':
altout.update(concat)
concat = altin
elif ch == '[':
ch = regex.__next__()
cls = []
while ch != ']':
if ch == '-':
crange = range(ord(cls[-1]), ord(regex.__next__()) + 1)
cls.extend(map(chr, crange))
else:
cls.append(ch)
ch = regex.__next__()
prev = concat
concat = set(w + c for w in prev for c in cls)
elif ch == '?':
concat.update(prev)
prev = None
elif ch >= 'a' and ch <= 'z':
prev = concat
concat = set(w + ch for w in prev)
else:
raise Exception("Illegal input")
if stack:
raise Exception("Unclosed group")
concat.update(altout)
words = sorted(concat)
print(len(words))
print('\n'.join(words))


This is restricted to the part of regular expression syntax which I expect for this answer. If you have good reason to use something I did not consider, feel free to do so although I will likely have to update this code to cope with it. If you find a bug, please let me know.

• This is just Meta regex golf under the constraint that the two lists between them cover all possible words. Given that some people are tackling that existing question on that basis, this would qualify for closing as a duplicate. – Peter Taylor Jan 8 '14 at 8:45

## Code-Golf: Write a number as an expression that's as short as possible

The goal of this code-golf is to create a program that takes a number as input (using STDIN, command line arguments, or prompting for input), and outputs that number, but written as an expression that's as short as possible. So, 10000 should become 10^4. If there is no way to write an expression that's shorter than the number, then output just the number.

### Other rules

1. No network access.
2. You're not allowed to execute an external program.
3. Only use the operators +, -, *, / and ^ (that's raising power, not XOR).
4. Order of operations must be taken in account. Use parentheses if necessary.
5. This is a code golf, so the code with the smallest amount of characters wins.
6. The input will always be smaller than 2^32.

### Test cases

500000000   -->    5*10^8     or    10^9/2
999999      -->    10^6-1
10          -->    10
4294967295  -->    2^32-1
16384       -->    2^14