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

# Print a 3D shape

## Posted

• Suggestion: use characters other than • and ¶ as they are multi-byte characters which not all languages will handle easily. ASCII characters instead would be better – caird coinheringaahing Jan 20 at 21:12
• I modified them, thank you. – Sheik Yerbouti Jan 20 at 21:35
• @caridCoinheringaahing I was just looking to try some other character taking as reference this ASCII table. The two characters that I changed are numbers 166 and 167 of the table. I am confused. – Sheik Yerbouti Jan 21 at 23:45
• Most languages can handle code points between 32 and 127 inclusive. Some use custom code pages (e.g. Jelly) that won't necessarily have extended ASCII characters, but will have regular ASCII – caird coinheringaahing Jan 21 at 23:48
• Oh all right thank you for the clarification! – Sheik Yerbouti Jan 21 at 23:55
• @Davide the table you linked is not actually an ASCII table. ASCII only goes from 0 to 127; there are more code pages that extend it to 256 and the creator of that table has clearly picked one. This confusion arises because almost all code pages include ASCII as the first 128 and then extend with some symbols like ¶ on top of that. Nowadays most things use UTF-8 which encodes some characters with more than one byte and can use millions of different characters from Unicode – pxeger Jan 22 at 7:58
• @pxeger Oh thank you for this definitive explanation! – Sheik Yerbouti Jan 22 at 13:02

# Quine Countdown! quinecode-golf

Write a program that accepts a single parameter n and outputs another program that outputs another program etc until the nth call outputs the original input n again.

Scoring is a modified version of codegolf: For input 100, add together the code length of each program in the chain, excluding the final 100. This is your score. Lowest score wins!

• Actually it's not much harder than a typical quine program. Because 100 is so large, most programs will do it the general quine way. – user202729 Jan 29 at 7:18
• Besides, the score would be easier to read if the score is the average size instead of the maximum. – user202729 Jan 29 at 7:18
• "Because 100 is so large, most programs will do it the general quine way." That's the intention. It's a quine with something extra. Without the scoring rule, everyone would just build nested multi-escaped prints, which isn't as interesting. – Sinthorion Feb 9 at 11:07

# Counting set bits in a byte

Here is a bite-sized problem I ran in to when trying to implement Conway's game of life on a microcontroller, and was trying to count the amount of neighbours: How can you check how many bits are set in a byte?

## Challenge

Given one byte of input data and an integer N between 0 and 8, check if there are exactly N bits set in the byte.

## Test cases

N = 0, input = 0b00000001 -> False
N = 0, input = 0b00000000 -> True
N = 3, input = 0b01001001 -> True
N = 3, input = 0b11100000 -> True
N = 3, input = 0b00001111 -> False
N = 7, input = 0b11101111 -> True
N = 7, input = 0b11111110 -> True
N = 8, input = 0b11111111 -> False


# Sandbox question

• My first intuition to solving this problem was to shift the bits out one by one, AND with 0x01 and count them. I feel however it must be possible to do something more efficient in terms of CPU cycles used. How can I make a challenge that is about optimizing instruction count and memory usage rather than on program-size? I have seen the tag, but I don't know what scoring method best to use.

# Edit: Closing after some good comments and possible solutions

Arnauld and CristoLosoph gave some great comments and led me to conclude that my issue is maybe to hardware/language specific to fit in a nice coding challenge. CristoLosoph showed me this interesting code snippet which I think is quite efficient:

uint8_t count_bits(uint8_t x){
x = ((x & 0b10101010) >> 1) + (x & 0b01010101);
x = ((x & 0b11001100) >> 2) + (x & 0b00110011);
x = ((x & 0b11110000) >> 4) + (x & 0b00001111);
return x;
}


Two other things I learned:

• Some hardware have a builtin POPCNT instruction in their instruction set, and gcc has a __builtin_popcount() method that does exactly what I was looking for
• I found in this question that it's an interesting trade-off (as with most embedded functions probably) to just make a lookup table containing all 256 possible return values. It takes some memory but not too much.

I also learned that probably would have been a good fit for this type of challenge!

Once again thanks for the interesting comments!

• Hello RvdV. Hm, seems like your motivation does not really fit. Fastest-code and smallest code is not the same, rather opposite things. When you program microcontrollers you are very restricted in the language but code golfing is the opposite (if you do not specifically restrict languages to one single one). Of course, there is a very performant solution for bitcount in the language which you might be looking for which however is quite uninteresting for code golf. I'll post you a fast snippet in C below. – ChrisoLosoph Jan 29 at 10:20
• – Arnauld Jan 29 at 10:25
• You may consider using atomic-code-golf, but be aware that it's pretty hard to specify correctly. – Arnauld Jan 29 at 10:26
• x = ((x & 0xAAAAAAAA) >> 1) + (x & 0x55555555); x = ((x & 0xCCCCCCCC) >> 2) + (x & 0x33333333); x = ((x & 0xF0F0F0F0) >> 4) + (x & 0x0F0F0F0F); x = ((x & 0xFF00FF00) >> 8) + (x & 0x00FF00FF); x = ((x & 0xFFFF0000) >> 16) + (x & 0x0000FFFF); You only need the first 3 lines if you only need it for 8-bit integers and then you can cut the hexadecimal literals down to two digits. – ChrisoLosoph Jan 29 at 10:29
• But if you work with GCC, please use __builtin_popcount() since that is the function that the compiler people tried to optimize exactly for your purpose and for your selected architecture. – ChrisoLosoph Jan 29 at 10:31
• Thanks a lot for your comments Arnauld and ChrisoLosoph! You are right that it's hard to define, and I didn't realize even how much language but also hardware-bound my problem was, maybe it's too difficult to define indeed (and if you define it language-agnostic it becomes the related post Arnauld linked). I will update the post with you suggestions! – RvdV Jan 29 at 17:51

# Mix my colors

This challenge is inspired by the Color Alchemy Patch on NetHack, notably incorporated by UnNetHack 3.5.2.

## Objective

Given two strings indicating colors, mix them according to the rules below, then output it.

## Colors

There are 16 colors in total that are valid inputs. They are categorized to 8 chromaticities and 2 brightnesses, like below:

        Light    Dark
Hueless white    black
Red     pink     ruby
Blue    sky-blue indigo
Yellow  yellow   golden
Orange  orange   amber
Green   emerald  dark-green
Purple  puce     magenta
Brown   ochre    brown


(I'm omitting gray, for it will make this challenge just cumbersome in this regard.)

Note that all color names are in lowercase.

## Color-mixing rules

• Above all, mixing colors is idempotent.

• Mixing colors is commutative unless noted below.

• When mixing two primary colors (Red, Blue, or Yellow):

• If they have same chromaticities, the result will also be in the same chromaticity.

• Mixing Red and Blue results in Purple.

• Mixing Red and Yellow results in Orange.

• Mixing Blue and Yellow results in Green.

• When mixing two secondary colors (Orange, Green, or Purple):

• If they have same chromaticities, the result will also be in the same chromaticity.

• All other combinations result in Brown.

• For all cases covered by above, mixing two Light (resp. Dark) colors will result in corresponding Light (resp. Dark) color.

• For all cases covered by above, mixing a Light color and a Dark color shall result in either Light or Dark. This is the only rule that may break the commutativity.

• Mixing a Light color with black results in corresponding Dark.

• Mixing a Dark color with white results in corresponding Light.

• All combinations not covered by above fall in don't care situation.

## Examples

### Valid outputs

• Mixing white and white results in white.

• Mixing pink and pink results in pink.

• Mixing pink and ruby results in either pink or ruby.

• Mixing ruby and golden results in amber.

• Mixing sky-blue and ruby results in either puce or magenta.

• Mixing emerald and dark-green results in either emerald or dark-green.

• Mixing emerald and orange results in ochre.

• Mixing puce and amber results in either ochre or brown.

• Mixing white and ruby results in pink.

• Mixing ochre and black results in brown.

### Don't care situations

• Mixing pink and white falls in don't care situation. There is no rule that covers this case.

• Mixing ochre and brown falls in don't care situation. There is no analogous rule for tertiary colors.

• Mixing indigo and magenta falls in don't care situation. There is no rule for mixing a primary color and a secondary color.

• Mixing indigo and orange falls in don't care situation.

• Mixing pink and ochre falls in don't care situation.

• Mixing white and black falls in don't care situation. (In the game, it results in gray, but I'll ignore this, for sake of simplicity of this challenge.)

## Rules for code golf

• Input format is flexible. In particular, it can be two strings, or one string separating colors by whitespaces. It's implementation-defined whether to accept leading or trailing whitespaces.

• Output format is also flexible. Outputting leading or trailing whitespaces is okay.

• Invalid inputs fall in don't care situation.

• The rule looks clear enough, but you can provide a table of 256 possible outputs just to be extra sure. – user202729 Jan 31 at 1:57

# Longest Common Suffix

Given arbitrarily many (more than 4) words, your goal is to find the longest common suffix of all of them.

## Rules

1. The suffix shouldn't be longer than one third of the length of any word, and should be longer than 2 characters.
2. The words can have at most one "exception" among them, that is, it doesn't have the same suffix others have. You should ignore these "exceptions".
3. If no suffix can satisfy all rules above, do not make any output.
4. All given words are separated by spaces; they only contain lower case English alphabets.
5. You can use any way to accept input, but output should only be in STDOUT.

## Example

Given: television operation delegation repetition
Output: ion

Given: vision decision subtraction observation
Output:


Why? The suffix, ion, is longer than 1/3 the length of vision and decision. There're two exceptions.

Given: interested congratulated excited overjoyed
Output: ted


Why? overjoyed is an exception, because others have the suffix ted, but it doens't. So we ignore the word overjoyed.

Given: abcdefghijkl bcdefghijkl cdefghijkl defghijkl
Output: jkl


Why? defghijkl is the longest, but it is longer than 1/3 the length of defghijkl.

This is code golf, so the shortest code win.

It's not recommended to use built-in functions which directly returns the result.

• Most answerers prefer "any (standard) way to get output" as well, but it's up to you. Practically, it's mostly not a problem. – user202729 Feb 1 at 9:30
• Regarding the output "No common...", people don't like hard coding long error messages, it would be better received if it's changed to "any value that signifies that there isn't...". – user202729 Feb 1 at 9:31

# Posted

• Clearly defined enough (not very interesting) -- except that is it guaranteed that the value exists? – user202729 Feb 1 at 3:14
• @user202729 Oh thank you, I forgot to cover this. I think that in case it doesn't exist, we can output a something like the smallest integer in the array. I would like to not restrict the input at all. – Sheik Yerbouti Feb 1 at 12:03
• Possible test case: empty array. (by the way don't patch "edit" into the sandbox post, include it in the text itself) – user202729 Feb 2 at 2:58
• @user202729 thank you, I edited the challenge. I will add test cases, including the empty array. – Sheik Yerbouti Feb 2 at 10:26

# Golf this Thumb-2 constant!

• Not very related to the question, but have you tried using some size-optimization option of some existing compiler? (-Os) – user202729 Feb 1 at 9:32
• Otherwise, clear enough. – user202729 Feb 1 at 9:33
• I explained the pattern better, and the last pattern does cover the rest, but it isn't the shortest. – EasyasPi Feb 4 at 0:43
• Okay. (just to check, there are $4862 > 2^{12} = 4096$ distinct values represented with the Imm12 format, right?) – user202729 Feb 4 at 0:53
• Yes. There are 4096 possible encodings for the Imm12 format. – EasyasPi Feb 4 at 1:48
• Then I must understand something wrong, because (as I've said above) there are 4862 different values that can be encoded.) – user202729 Feb 4 at 1:51
• Oh yeah I was wrong. I think I am going to go back to it just being a byte rotated, even if it isn't accurate. As the true encoding is too complex to be fun to calculate. 🤷‍♂️ – EasyasPi Feb 4 at 3:02

(this is the core of the BF memory optimizer challenge.)

(At the moment I still need to make some test cases; however you can still review the rest of the challenge.)

note: This problem is reducible from Simple Max Cut, therefore it's NP-complete. (https://doi.org/10.1016/0304-3975(76)90059-1)

note: While I did get a bunch of test cases from this site, I'm not sure how can I write a reasonable algorithm to compete with...

### Proof

(actually this is not part of the sandbox challenge, but I'll post it here because it's related)

First, for convenience, assume that the problem is represented by a undirected graph, where the number of rows/columns of the matrix is equal to the number of nodes, and the corresponding weight is the sum of the value of the edges connecting the corresponding two nodes.

With that representation, the value to be minimized is the sum of the product of the edge lengths and the edge weights, with the graph nodes embedded into the point $$\ 1, 2,\ldots, |V| \$$.

From a Simple Max Cut problem of the form:

Given $$\ n \$$ variables $$\ x_1, x_2,\ldots, x_n \$$, maximize the value of $$\ \sum_{i=1}^m [a_i \ne b_i] \$$, where each of $$\ a_i, b_i \$$ represents either a variable or its negation.

It can be transformed to an instance of this problem:

First, construct $$\ 2n \$$ nodes on a graph, denoted $$\ p_1, p_2,\ldots, p_n, q_1, q_2,\ldots, q_n \$$. Let $$\ a \$$ be some positive integer. Connect those vertices:

• $$\ p_1 \$$ and $$\ q_1 \$$, with cost $$\ 2n^2 a \$$,
• the 4 pairs of vertices $$\(p_1, p_i),(p_1, q_i),(q_1, p_i),(q_1, q_i)\$$ with cost $$\ (n+1-i) a \$$, for each $$\ i=2, 3,\ldots, n \$$,
• and some other edges with small weights (the sum of their weights should be less than $$\a\$$ -- (1)) that mainly does not affect the optimal configuration.

The sum of the edge weights (except the first one) is $$\ 4 ((n-1)+(n-2)+\ldots+1)a=2n(n-1)a \$$.

The edge between $$\ p_1 \$$ and $$\ q_1 \$$ has a weight larger than the sum of all the others, it's obvious to see that in the optimal (minimum cost) configuration, these two must be adjacent.

Then, regardless where those 2 vertices are placed, the $$\ i \$$'th smallest distance-pair to those are at least the $$\ i \$$'th value in the sequence are

$$(1, 2),(1, 2),(2, 3),(2, 3),(3, 4),(3, 4),\ldots,(n-1, n),(n-1, n)$$

.

And by the rearrangement inequality, it's optimal to place the weight so that the vertices with the smaller edge-weight to $$\ p_1, q_1 \$$ are placed further from the vertices. Therefore the only optimal placement is

$$z_n, z_{n-1}, \ldots, z_2, z_1, z_1, z_2, \ldots, z_{n-1}, z_n$$

where each $$\ z_i \$$ is either $$\ p_i \$$ or $$\ q_i \$$ ($$\1 \le i \le n\$$).

Encode the condition "vertex $$\ i \$$ is on the left side of the cut" by "$$\ p_i \$$ is to the left of $$\ q_i \$$ in the permutation". (2)

Assuming that the edge weights are allowed to be fractional.

For each condition (in the Simple Max Cut problem) that "there's an edge between vertices $$\u\$$ and $$\v\$$ ($$\ u\le v \$$)", add an edge between $$\ p_u \$$ and $$\ q_v \$$ with weight $$\\frac 1 {2u-1}\$$ to this problem.

The weight of this edge can either be $$\ u-v \$$ or $$\ u-v+(2u-1)\$$ in the configuration that minimizes the total weight of the edges constructed in the previous section.

Therefore, if the vertices $$\ u \$$ and $$\ v \$$ are on different sides of the cut (according to the encoding (2)), the total weight is decreased by $$\ 1 \$$ if $$\ u \$$ and $$\ v \$$ are on different sides; and the configuration with the minimum weight is exactly the one with maximum number of edges cut.

However, in the actual problem edge weights must be an integer. We replace each edge weight $$\\frac 1 {2u-1} \$$ by $$\\lceil\frac c {2u-1}\rceil \$$, where $$\ c=2nm\$$.

Because there are $$\ m \$$ edges in total, if the sum of any $$\ k-1 \$$ increment values $$\\lceil\frac c {2u-1}\rceil (2u-1) \$$ is strictly less than the sum of any $$\ k \$$ increment values, for $$\1\le k\le m \$$, then the optimal sum is also the maximum cut.

Observe that because $$\ c=2nm \$$ and $$\ x\le 2n-1 \$$, each increment value must be between $$\ 2nm \$$ (inclusive) and $$\ 2nm+2n-1 \$$ (exclusive). Therefore the maximum sum of $$\ k-1 \$$ values is $$\ (2nm+2n-2)(k-1) \$$, which is less than the minimum sum of $$\ k \$$ values $$\ 2nmk \$$ when $$\ 1\le k\le m \$$.

The sum of all those does not exceed $$\ \lceil \frac {2nm}{1} \rceil m \$$. Therefore if $$\ a \$$ is chosen to be $$\ 2nm^2+1 \$$, then the condition (1) is satisfied.

### Minimum cost matrix permutation

(or ? Obviously the latter would be more useful in practice code golf)

Given a matrix $$\w\$$ in $$\{\mathbb N_0}^{n\times n}\$$, define the symmetric matrix $$\d\$$ in $$\{\mathbb N_0}^{n\times n}\$$ by the formula $$\d_{i,j}=\left| i-j \right|\$$, find a permutation matrix $$\P\$$ such that the sum of elements in the matrix $$\(P^{\mathsf T} \cdot w \cdot P ) \,\odot\,d\$$ (where $$\\odot\$$ denotes the Hadamard product/element-wise product) is smallest.

The result will be the mean (TODO: median? mean of the 50% maximum? mean result/naive ratio?) of the score over these test cases, for as long as you can run your program.

# (WIP) Settling the Lands of Codegolfia

The challenge controller will randomly generate a 200x200 map representing the terrain of the land

Your task is to write an AI whose goal is to have the largest population after 500 turns.

## Start

Each player begins with 1 cell claimed and a population of 100.

## Turns

On each turn, you have the opportunity to claim land cells. You can claim 1 cell per turn, plus 1 per 1000 population. Claimed cells must be orthogonally adjacent to a cell you already own. You cannot claim cells belonging to other players.

Turns happen simultaneously. In the event that two players attempt to claim the same cell, both players will lose 10 people from their population and neither player will claim the cell.

At the end of your turn, your population grows by 10% (rounded up), up to the maximum size your colony can support.

## Population Support

Without any land claimed, your colony can support up to 150 people.

Supporting larger populations requires claiming land. Each terrain type increases the amount by some amount. Combinations of terrain expand this further.

## Terrain

There are 4 terrain types:

• Plains
• Supports 20 people by itself
• Supports 5 per adjacent owned plains
• Forest
• Supports 10 people by itself
• Supports 5 per adjacent owned forest
• Supports 50 additional people if there are at least 10 owned plains cells within 10 cells (Manhattan distance)
• Mountains
• Supports 5 by itself
• Supports 5 per owned plains within 15 cells
• Supports 10 per owned forest within 5 cells
• Water
• Each plains cell can support 500 additional people if it is within 5 cells of an owned water cell.
• Each forest cell can support 200 additional people if it is within 10 cells of an owned water cell.

### Alternative ideas for terrain

• Plains support raw population. Same as above
• Forest cells increase population support for all plains within 5 cells by a factor of 5% (stacks multiplicatively)
• For every water cell and 10 plains cells, reproduction rate increases by 1%
• Each mountain cell increases the range of each owned mountain and forest within 3 cells by 1. (stacks additively)
• I was just thinking of something like this! (but different enough I can still do mine :p). Currently I don't see too many options for strategy other than comparing each orthagonal square each turn and picking the best. – Redwolf Programs Feb 11 at 19:38
• @RedwolfPrograms yeah. Maybe I should make each of the terrains more mechanically different. Maybe one increases reproduction rate, one expands synergy range, and another enhances the others. – Beefster Feb 11 at 20:24
• That sounds like a good idea, depending on how it's implemented. Maybe being close to water would let you claim extra land per turn near the body of water, sort of like exploration? – Redwolf Programs Feb 11 at 20:31

# Heads I win, tails you booze: coin tossing, pub trivia style code-golfprobability-theorygame

At my old pub trivia night, a free jug of beer or bottle of wine was awarded to the team that won Heads or Tails. This game requires players to correctly guess the outcome of successive coin tosses. The game proceeds as follows:

1. Before each toss the remaining players, who are standing, place both hands on their head (for heads) or their bottom (for tails). If all remaining players choose the same outcome (which would lead to a draw) the host refuses to toss the coin until at least one player changes his/her guess.
2. The host then tosses a coin (assumed fair) and announces the outcome. All players who guessed incorrectly are eliminated and have to sit down.
3. Play continues until there is only one person left standing to claim the prize for their team.

In perfect play, the remaining players on each team always divide as evenly as possible between heads and tails:

• If the number of remaining players on a team is $$\2k\$$ for some positive integer $$\k\$$, then exactly $$\k\$$ of them guess heads and $$\k\$$ of them guess tails.
• If the number of remaining players on a team is $$\2k+1\$$, then with equal probability
• exactly $$\k\$$ of them guess heads and $$\k+1\$$ of them guess tails, or
• exactly $$\k+1\$$ of them guess heads and $$\k\$$ of them guess tails.

An interesting consequence of players not acting independently is that a team's probability of winning is not, in general, equal to $$\\dfrac{\text{number of players on the team}}{\text{number of players on all teams}}\$$, as the examples below illustrate.

### Challenge

Assume that there are $$\n_0\$$ players on our team and $$\n_1, n_2,\ldots, n_N\$$ players on the opposing $$\N\$$ teams ($$\N\$$ and the $$\n_i\$$ are all positive integers). Given the $$\n_i\$$ as input, write the shortest program or function that calculates the probability that our team wins the booze, assuming perfect play by all teams.

Input format is flexible: you may (for example) take

• an integer $$\n_0\$$ and a list $$\[n_1, n_2, \ldots, n_N]\$$ (this format is used in the test cases),
• a flat list $$\[n_0, n_1, \ldots, n_N]\$$,
• a nested list $$\\left[n_0, [n_1, n_2, \ldots, n_N]\right]\$$.

The $$\n_i\$$ may be taken in any order. Output should be in a suitable numeric format. Floating-point approximations are acceptable provided that the underlying algorithm is theoretically exact. You may not return a list of winning probabilities for all teams (I don't care how likely it is that another team wins).

### Examples

Example 1: $$\n_0=1\$$, $$\n_1=2\$$

Suppose there are only two teams: our team has one player and the opposing team has two players. After the first toss, exactly one player from the opposing team remains in the game (because one player guesses heads and the other guesses tails). For our team:

• Half of the time, our player has guessed incorrectly and is eliminated. The other team wins.
• Half of the time, our player has guessed correctly. A second toss occurs—a head-to-head battle with the remaining player on the other team—which our player wins half of the time.

The probability that our team wins is therefore $$\\dfrac{1}{2}\cdot0 + \dfrac{1}{2}\cdot\dfrac{1}{2} = \dfrac{1}{4}\$$.

Example 2: $$\n_0=2, n_1=3\$$

In this case, both teams survive the first toss. Exactly one player remains on our team. For the other team:

• Half of the time, one player remains. A second toss decides the winner.
• Half of the time, two players remain. From this point, the remaining tosses play out exactly as in Example 1.

The probability that our team wins is therefore $$\\dfrac{1}{2}\cdot\dfrac{1}{2} + \dfrac{1}{2}\cdot\dfrac{1}{4} = \dfrac{3}{8}\$$.

### Test cases

$$\n_0\$$, $$\[n_1, n_2, \ldots, n_N]\$$ -> Output

1, [2] -> 1/4
2, [3] -> 3/8
5, [5, 5, 5] -> 1/4
5, [3, 5, 7] -> 5929/24576
8, [1, 2, 4] -> 485/768
6, [4, 5, 5, 6, 8] -> 45/256

• Even then, that "perfect strategy" strategy is ambiguous -- what if there's an odd number of players? Why isn't there a (us=H, them=H) case in the "round 2" of example 1? [please review other sandbox posts] – user202729 Feb 13 at 5:41
• @user202729 Yes to your first question. For your second question, there's no (H, H) because one of the players on the other team was eliminated in Round 1. Do the edits help? – Dingus Feb 13 at 5:46
• @user202729 Just saw your edit. (us=H, them=H) is a draw (by which I mean the round would just be repeated until they guess differently from each other). It's supposed to be covered by 'the pathological scenario in which all players repeatedly guess the same outcome never occurs in practice'. – Dingus Feb 13 at 5:47
• So if there are two ways to divide evenly (odd number), assume that each team choose one of them independently with the same probability? – user202729 Feb 13 at 5:49
• By the way, unless there's some clever formula to calculate the result, I expect that all the submissions will be too inefficient to calculate the last test case. – user202729 Feb 13 at 5:52
• @user202729 I'll add some text to clarify what happens with odd-sized teams and a small test case with all odd-sized teams of different sizes. Fair point about the inefficiency. – Dingus Feb 13 at 5:57
• Okay that part is good now, but you might want to add "if all players guessed wrong, then no players is eliminated" – user202729 Feb 13 at 11:24
• @user202729 I think that's covered by 'If all remaining players choose the same outcome (which would lead to a draw) the host will refuse to toss the coin until at least one player changes his/her guess', but it should be clearer now that I've moved that sentence earlier in the description. – Dingus Feb 13 at 11:36
• By the way, do you have a proof that the mentioned algorithm is optimal? – user202729 Feb 13 at 12:47
• "until at least one player changes..." can be ambiguous (what is their strategy to change the choice?) I think "skips the round and all player choose [...] again" is better. – user202729 Feb 13 at 12:52
• By the way, do you have a polynomial time solution? – user202729 Feb 15 at 2:07
• (this is a (probably polynomial time, or at least can be made polynomial time) implementation . tio.run/… ) – user202729 Feb 16 at 6:43
• @user202729 I appreciate all the comments, thank you. Clearly there's a bit to think about but I won't have time to look at this again in detail for a few days, probably. (It may be that this challenge has more potential in a category other than code golf, but I'm not sure yet.) – Dingus Feb 16 at 7:02

# Score an approximation code challenge code-golf

Given a list of inputs (strings) and their expected outputs (integers or floats)[1], and a black-box program[2], calculate the score using the following scoring system:

Let $$\R_n\$$ be the expected output of the $$\n^{th}\$$ input, let $$\A_n\$$ be the actual output given by the black-box program, and let $$\ j \$$ be the total number of input/output pairs. (All values are positive and non-zero)

Then the score is defined as: $$S=\left\lceil L\times\max_{1\le i \le j}\left({\max\left(\frac{A_i}{R_i},\frac{R_i}{A_i}\right)^2}\right)\right\rceil$$ where $$\L\$$ is the length of the black-box program in bytes.

Example:

If the size of the program is $$\100\$$ bytes and the worst approximation is on the input "moon", where the program outputs $$\1000\$$ instead of the expected $$\1737\$$, then the score would be:

$$S=\left\lceil 100\times{\left(\frac{1737}{1000}\right)^2}\right\rceil=302$$

This system is taken shamelessly from this challenge by @Arnauld. Here is his reference implementation.

[1]: You may take the inputs and outputs either zipped ([(in1, out1), (in2, out2), ...]), or not zipped (([in1, in2, ...], [out1, out2, ...]), with both lists of the same length), at your option.

[2]: You may take the black-box program as either:

• a black-box function, and its length in bytes, as two separate inputs
• a string of code to be evaluated, as one input (the length will not be given separately unless necessary)

# Rules

• (1) is it a problem if the program only support integers? (2) is it guaranteed that both values (actual and submission output) are strictly positive? The formula is not well defined when either value is zero. – user202729 Feb 15 at 13:17
• @user202729 all values will be positive; the idea was that you can support integers or floats, whichever is easier – pxeger Feb 15 at 13:23
• The "whichever is easier" part is currently not mentioned in the challenge. – user202729 Feb 17 at 10:36

# Stack half full or half empty? (worldview of a programming language)

Is the glass half full or half empty? It's a common rethoric question to determine a person worldview, which can be optimistic or pessimistic based on the answer given. If i were dealing with a machine i would probably ask "Is the stack half full or half empty?" Let's try and see if programming languages have a worldview too.

Write a full program or a function which prints or returns one of "The stack is half full." or "The stack is half empty." when given as input the question "Is the stack half full or half empty?" but wait.. you have to provide a stack to be observed.. which stack you provide is up to you: input one or check an already existing stack. Your solution will then output one of the two sentences mentioned above for a non empty / non full stack, your choice which one to print, just make sure your answer is as short as possible because this is . For an empty stack it must produce the "empty" output while for a full stack "full".

# Survey

I will make a chart of the pessimistic Vs optimistic languages based on the half outputs. If you find the same byte count for both choices you can provide both, in which case they will count on both sides of the chart, but you just can select one if you like.

## input

• A sentence in any reasonable method.
• The behavior is defined only for the question "Is the stack half full or half empty?" and exactly this.
• Indeed your solution can also completely ignore the input as long as it works with the specified input.
• Question mark is mandatory.

## output

• One of "The stack is half full." or "The stack is half empty.", for a non full / non empty stack.
• "full" or "empty" for a full stack or an empty stack respectively
• upper / lower case or a mix are fine.
• ending dot not mandatory.

# Rules

• Only the mentioned input allowed.
• Loopholes allowed.
• This is and the answer with the fewer bytes of source code wins.
• This would be a really cool challenge, but the tasks are too similar. I doubt anything other than print "The glass is half full" will be competitive. Maybe add an additional thing they have to do, in addition to printing the text? As an example, for half empty, take a number of inputs and discard every second one. For half full, print every other fibonacci number. – Redwolf Programs Feb 18 at 20:41
• So undefined behaviour is fine for all inputs that are not one of the two specific questions? – Adám Feb 18 at 20:41
• Your initial description only mentions one possible input, while your "input" section mentions both. – Adám Feb 18 at 20:42
• Thanks @Redwolf Programs ! To be honest I had this crazy idea but don't really knew how to make it interesting.. I ended developing it in the simplest and most obvious way.. Maybe I 'll change many things during the sandbox – AZTECCO Feb 18 at 20:48
• @Adám yes for UB, for the input I'm sorry, my fault.. Initially I was using only one question but then decided it was reasonable to handle both combinations.. Gonna edit thanks! – AZTECCO Feb 18 at 20:51
• @Redwolf Programs I changed a bit, I hope this stack thing will add some flavor without exiting the context, please let me know if you want to share some opinions – AZTECCO Feb 21 at 18:43
• @Adám some changes.. If you have any opinions please let me know – AZTECCO Feb 21 at 18:45
• @AZTECCO I still think half empty and half full should require doing different things. Currently I doubt anyone will pick half empty, because half full is shorter and there's no other difference. – Redwolf Programs Feb 22 at 0:24
• @Redwolf Programs yeah that's true. I was wondering if languages with built in string compression, string methods or regex would compete the plain print"..answer.." method which should be around 25~30 of score but.. I don't know.. I just feel like a do this or that based on input is a different challenge but it seems to be the only way – AZTECCO Feb 22 at 9:21
• @AZTECCO The concept of the answers choosing between two options is really cool and unique; the current options are just too similar. Maybe one thing that tests control flow, like a truth machine sort of thing, and one that tests input/output, like discarding every other output? The stack validating thing (where you have to print empty or full) feels kind of irrelevant to the cool part of the challenge. Having the input be the question isn't really necessary IMO; you could replace the input with something like a list of numbers (cont.) – Redwolf Programs 2 days ago
• (cont.) and have the answers do one of two things with that list (totally up to you, although I'd recommend tasks that use different capabilities of the language, like one control flow and one math), then print The glass is half (empty|full). – Redwolf Programs 2 days ago
• @Redwolf Programs thanks for explaining your opinion, your insight are really important and I totally agree, I was losing the scope and your words got me back on track! – AZTECCO 2 days ago

# Generalise perfect numbers

Let $$\\sigma(n)\$$ represent the divisor sum of $$\n\$$.

Perfect numbers are numbers whose divisor sum equals their double or $$\\sigma(n) = 2n\$$. For example, $$\\sigma(6) = 12 = 2\times6\$$

Superperfect numbers are numbers whose twice iterated divisor sum equals their double. For example, $$\\sigma^2(16) = \sigma(\sigma(16)) = \sigma(31) = 32 = 2\times16\$$

$$\m\$$-superperfect numbers are numbers for which the following holds: $$\\sigma^m(n) = 2n\$$ for $$\m \ge 1\$$. For $$\m \ge 3\$$, there are no such numbers.

$$\(m,k)\$$-perfect numbers are numbers such that $$\\sigma^m(n) = kn\$$. For example, $$\\sigma^3(12) = 120 = 12\times10\$$, so $$\12\$$ is a $$\(3,10)\$$-perfect number.

You are to choose one of the following three tasks to do:

• Take three positive integers $$\n, m, k\$$ and output the $$\n\$$th $$\(m,k)\$$-perfect number (0 or 1 indexed, your choice)
• Take three positive integers $$\n, m, k\$$ and output the first $$\n\$$ $$\(m,k)\$$-perfect numbers
• Take two positive integers $$\m, k\$$ and output all $$\(m,k)\$$-perfect numbers

You may assume that the inputs will never represent an impossible sequence (e.g. $$\m = 5, k = 2\$$). You may take input in any convenient method.

This is so the shortest code in bytes wins.

# Meta

• Better having a statement "in this challenge $\sigma^n(k)$ denotes...". It can be interpreted as $(\sigma(k))^n$ too. – user202729 yesterday
• Can answers assume that "the sequence is infinite"? – user202729 yesterday

# Bytewise look-and-say sequence code-golf

The look-and-say sequence is a sequence which begins with 1, 11, 21, 1211, 111221, 312211. To get a term of the sequence from the previous, read the previous out literally:

312211 => one three, one one, two twos,two ones => 13112221

So the next term is 13112221.

Given this javascript code (Node.js), which outputs the look-and-say sequence indefinitely, delimited by newlines:

function nextTerm(x){
return x.replace(/(.)\1*/g,z=>z.length+z[0])
}
function printUpTo(x){
var str = '1';
for(var i = 0; i < x; i++){
console.log(str);str = nextTerm(str);
}
}
printUpTo(Infinity)


It will output a string that begins 1\n11\n21\n1211\n111221 etcetera. Your job is to write a function that takes a number as input and outputs that byte of the output string.

## Rules

You may output a different character for newline instead of \n, e.g. # or something.

## Scoring

Your program should be able to handle 100 million.

The first answer to handle 1e+18 correctly will receive a 100-rep bounty. This cannot be hard-coded.

Standard loopholes apply.

Test cases:

1 => \n
5 => 2
10 => 1
20 => 3
50 => 3
100 => 1
1000 => 1
100000 => 3
10000000 => 1


This is , so shortest bytes wins.

• Note that restricted-complexity means "solutions' time complexity must be polynomial in the input size" or something similar. "In a minute" means restricted-time, but then you have to specify the specification of your machine and test all solutions (although in most cases it will be obvious and you don't need to) – user202729 Feb 20 at 9:39
• And an implementation of the naive algorithm in a low-overhead language (C++) would be able to do that as well. – user202729 Feb 20 at 9:40
• @user202729 I'm not actually sure how to write this myself - notice that there isn't a testcase for 1 billion - that's because I couldn't figure out how to do an actually efficient version. Also, by 'In a minute', I mean on TIO. I'll add that. – A username Feb 20 at 9:44
• And TIO isn't suitable for timing submissions (personally I think it's really suitable, but people don't agree.) – user202729 Feb 20 at 9:45
• @user202729 What do you mean? Is it something to do with how busy the server is or similar? – A username Feb 20 at 9:46
• codegolf.meta.stackexchange.com/questions/12707/… – user202729 Feb 20 at 9:48
• @user202729 Ok, redoing the whole thing, since I don't want to install loads of different compilers/interpreters. – A username Feb 20 at 9:50
• Ok, publishing. – A username Feb 22 at 4:30
• Wait, I did warn you that a naive implementation in C++ would be able to do it. – user202729 Feb 22 at 4:30
• Do you want to allow that? – user202729 Feb 22 at 4:31
• Ok, 1e+12 should be fine. – A username Feb 22 at 4:31
• Wait are you sure that there actually is a polynomial time solution? – user202729 Feb 22 at 4:32
• I feel like there should be one, but I don't know. Never mind. – A username Feb 22 at 4:33
• Actually there probably isn't since there's no way to calculate the nth term or length of nth term without calculating the previous. So never mind. – A username Feb 22 at 4:36
• There probably is. (I didn't come up with one.)Although people could let their programs run for a month. 1e+18 is definitely safe, but might be a little too large for some polynomial approaches. – user202729 Feb 22 at 4:36

# Self improving program

In this challenge you will write a program or function which when run will output a faster solution to this challenge.

Formally speaking: you will write a program or function, $$\T_0\$$, which takes an integer $$\x\$$ as input and outputs a program or function (in the same language), $$\T_1\$$, which is itself a valid solution to this challenge, such that there exists a function $$\f\$$ where $$\T_1\$$ is in the time complexity class $$\O\left(f\right)\$$, but $$\T_0\$$ is not. That is to say the output program must have a strictly faster asymptotic time complexity.

Note that since $$\T_1\$$ must be a valid solution to the challenge it must output a program or function $$\T_2\$$ which is even faster, and so on and so forth, creating an infinite chain each faster than the last.

Answers will be scored by their length in bytes with fewer being better.

# Precision

In keeping with the tradition of this site, and to remain inclusive: The order notation of a function will be assumed to be measured by the algorithm implemented by your answer. Thus we will pretend not to notice the behavior of your actual program for inputs out of the range of your language's numeric type.

However that being said, in order to ensure that you are actually changing the algorithm at every step, for constants initialized in your program this leniency is not given. e.g. If you use a double precision floating point 1.0000000000000001 is equal to 1.0. So if your method relies on an increasing or decreasing constant embedded in the program you should be careful that the algorithm actually changes.

Simply put for $$\T_n(x)\$$ you are forgiven for errors arising from very large $$\x\$$, but not from very large $$\n\$$.

• (which is the same thing is $T_0\in o(T_1)$.) – user202729 Feb 20 at 9:54
• How is this possible? You'd need to get faster and faster, and even if you do it exponentially, you can't change the speed by tiny fractions of a second each time. Please explain, very confused. – A username Feb 20 at 9:54
• And what prevents programs from doing for i in range(int(n**1.00001)): pass? – user202729 Feb 20 at 9:55
• Thinking about it again, since programs can simply run a loop to have any asymptotic complexity (>= complexity to parse input), it's not that hard. And you could just ask programs to print out an always-decreasing floating point value plus the new program. – user202729 Feb 20 at 9:57
• @user202729 But the always-decreasing float is the problem here, because eventually it will get too small to be distinguished by the language from 0. – A username Feb 20 at 10:01
• @Ausername An easier way to have it constantly decreasing is to have O(n^2) -> O(n log(n)) -> O(n log(log(n))) -> O(n log(log(log(n)))) etc. This approaches O(n) from above and remains distinguishable for really large inputs, without requiring anything finicky about precision. – Wheat Wizard Feb 20 at 10:02
• It means that programs doing things like (Python) n=1000000000000000000000000000000; for i in range(int(input())**(1+1/n): pass and (1+1/n) evaluates to 1 (because of IEEE754, even though the value of n is stored exactly) will fail? – user202729 Feb 20 at 11:45
• @user202729 Yes. Precision rules are always pretty non-concrete and non-objective. I think it is best to not try to push at the boundaries. – Wheat Wizard Feb 20 at 12:49

# Is it zero- or one- indexed?

Your task is to determine whether some arbitrary programming language has zero-indexed or one-indexed arrays based on sample inputs and outputs

### Inputs

• An array of integers with at least 2 elements
• A positive integer index
• The value of the array at that index

### Output

One of four distinct values representing:

• One-indexed if the language unambiguously has one-indexed arrays
• Zero-indexed if the language unambiguously has zero-indexed arrays
• Unknown if the given inputs aren't enough to determine whether the language is zero- or one- indexed because it is ambiguous.
• Neither if the language is not zero- or one-indexed because it is something else that may or may not make any sense.

## Example Test Cases

Formatted as [array, elements][index] == value_at_index => output

[2, 3][1] == 2  ==>  one-indexed
[2, 3][1] == 3  ==>  zero-indexed
[1, 2, 2, 3][2] == 2  ==>  unknown
[4, 5][1] == 17  ==>  neither
[-3, 5, 2][2] == 5  ==>  one-indexed
[-744, 1337, 420, -69][3] == -69  ==>  zero-indexed
[-744, 1337, 420, -69][3] == 420  ==>  one-indexed
[-744, 1337, 420, -69][3] == -744  ==>  neither
[42, 42, 42, 42, 42][2] == 42  ==>  unknown
[42, 42, 42, 42, 42][1] == 56  ==>  neither


## Rules and Scoring

• Use any convenient I/O methods
• Use any convenient representation for each of the four distinct categories as long as it is consistent and each possible category is mapped to exactly one value.
• You may assume that all array values are between $$\-2^{31}\$$ and $$\2^{31} - 1\$$, inclusive (i.e. the signed int32 range.)
• You may assume that arrays are no longer than $$\65535\$$ elements.
• You may assume that the index is in-bounds for both zero- and one-indexed semantics.

Shortest code wins. Happy golfing!

• The tag should be [array-manipulation], and I'd recommend linking to the convenient I/O methods, but other than that this looks ready to go – caird coinheringaahing 2 days ago
• Clear enough. [please review other sandbox posts] (<-- also 15 character filler) – user202729 yesterday

# Is this Game of Go configuration fully alive? code-golfgodecision-problem

## Background

This challenge is about the Game of Go. Here are some rules and terminology relevant to this challenge:

• Game of Go is a two-player game, played over a square board of size 19x19.

• One of the players plays Black, and the other plays White. The game is turn-based, and each player makes a single move each turn, starting with Black. In the diagrams below, we use O for White and X for Black. Any other symbol is a blank.

• A move consists of placing a new stone of the player's own color on an empty spot on the board.

• Given a group of orthogonally connected stones of single color, the liberty is the number of empty positions orthogonally around it. For example, the following group has liberty of 7:

. . . .
. O O .
. O . .
. . . .


and the following configuration has two groups having liberties of 6 and 4 respectively:

. . . . .
. O O . .
. . . O .
. . . . .

• The opponent can reduce the liberty by placing their own stones around the target group. The following group of O has liberty 1 (the only empty adjacent position being a):

. X X .
X O O X
X O X .
. a . .

• If the Black places another black stone at a, the white group's liberty reduces to 0, where capture happens, and the white group is removed from the board.

• A player cannot make a move where their own stone(s) would be captured, unless it is itself a capturing move. For example, the Black cannot make a move at a or b (where one or two black stones would be captured immediately), but they can make a move at c because it captures two White stones on its right.

. . . . . O . . . O X .
. O . . O X O . O X O X
O a O . O b O . O c O X
. O . . . O . . . O X .


Finally, some terminology that is exclusive to this challenge:

• A configuration is one or more groups of stones of the same color.
• A configuration of White (color fixed for ease of explanation) is fully alive if Black cannot capture any of the given white stones even if arbitrarily many turns are given to Black.

## Challenge

Given a Game of Go configuration, test if it is fully alive.

The input is a rectangular 2D array representing the state of the board, where each cell is either occupied (O in the example below) or empty (.).

• You can choose any two distinct values to represent an occupied and an empty cell respectively.

• You can assume the input is always rectangular, and contains at least one stone.

• You can assume the input will always contain a margin of empty cells around the entire configuration of stones. For example, you don't need to handle this:

O O O .
O . O O
. O . O
. . O O


which will be given as the following instead:

. . . . . .
. O O O . .
. O . O O .
. . O . O .
. . . O O .
. . . . . .

• For output, you can choose to

1. output truthy/falsy using your language's convention (swapping is allowed), or
2. use two distinct values to represent true (affirmative) or false (negative) respectively.

Standard rules apply. The shortest code wins.

## Test cases

### Truthy (fully alive)

. . . . . . .
. . O O O O .
. O . O . O .
. O O O O . .
. . . . . . .

. . . . . .
. O O . . .
. O . O O .
. O O . O .
. . . O O .
. . . . . .

. . . . . .
. . O O . .
. O . O O .
. O O . O .
. . O O . .
. . . . . .

. . . . . .
. O O . . .
. O . O . .
. O O . O .
. . O O O .
. . . . . .

Truthy since both eyes must be filled in order to capture any of the two groups
. . . . . . .
. . O O O . .
. O . . O O .
. O O O . O .
. . . O O . .
. . . . . . .

Ditto
. . . . . . . .
. . O O O . . .
. O . . O O O .
. O O O . . O .
. . . O O O . .
. . . . . . . .

. . . . . . .
. . O O O . .
. . O . . O .
. O . O O O .
. O O . O . .
. . . O O . .
. . . . . . .


## Falsy (not fully alive)

. . .
. O .
. . .

. . . . .
. O O O .
. O . O .
. O O . .
. . . . .

. . . . . . . . .
. O O O . . O O .
. O . O . O . O .
. O O . . O O O .
. . . . . . . . .

. . . . . . .
. O O . O O .
. O . O . O .
. O O . O O .
. . . . . . .

The right group can be captured by Black, since Black doesn't need to fill
the upper area (of size 2) to capture it
. . . . . . .
. O O O . . .
. O . . O O .
. O O O . O .
. . . . O O .
. . . . . . .

The center singleton can be captured by Black
. . . . . . . . .
. . . O O O . . .
. O O O . O O O .
. O . . O . . O .
. O O O . O O O .
. . . O . O . . .
. . . O O O . . .
. . . . . . . . .


## Meta

• Are the rules and the task clear?
• Can you find more corner cases?
• 5 7⍴'OOO....O.O....OO...OO....O.O....OOO' two eyes, but disconnected from each other – Razetime 10 hours ago
• @Razetime Thanks, added (though it might not matter too much in this context) – Bubbler 10 hours ago

# 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


## Rhymalator

(at the point, it's just something that came to me before i wake up, so it may need some adjusting, and i'd like some feedback as to if this could be fun)

The code challenge is to write a program that takes as input a calculation in Reverse Polish Notation and outputs the result. It must at least implement + - * /. It So far so easy, but to make it fun and "artistic", the following restriction applies:

• The source code must rhyme when read. Example in PHP

$iterator = str_split($a);
foreach ($iterator as$key=>$value){ if ($key > 3){
++$virtue; } }  (the rhyme is on value-virtue) • Lines whitout readable characters count as whitespace (the two lines with } in the example) • How does that example rhyme...? – Doorknob Jan 25 '14 at 12:54 • @DoorknobofSnow well, i'm not really a poet, that's why i propose it as a challenge for others :p. if you have a better example i'll replace it – Einacio Jan 27 '14 at 15:58 # Implement Kalah code-golf The game of Kalah is a two-player board game in the Mancala family. Your implementation must: • Identify the active player ("Player 1" or "Player 2") • Display board state (in format specified below) • Accept input to allow that player to move (using index system below) • Announce a winner ("Player N wins") # Overview Each player has a line of six spaces, called houses, and one additional space called a store. Each space holds seeds, which move from house to house in a counter-clockwise direction. The objective is to fill your store with seeds. You must represent the board in the following two-row format with stores offset, where HH is a house and SS is a store: SS HH HH HH HH HH HH HH HH HH HH HH HH SS  The top row represents the number of seeds in player #1's spaces, and the bottom row represents the seeds in player #2's spaces. The S in each row is the respective player's store (player #1's is top-left, #2's is bottom right). Single-digit values should include a leading space. In this challenge, user-input will identify each house numerically. Use a left-to-right, indexed-from-one scheme for both sides: S 1 2 3 4 5 6 1 2 3 4 5 6 S  Note that the players' stores are not numbered, because seeds placed in the store never move out. ## Rules Wikipedia has a good summary of the game and its rules: 1. At the beginning of the game, three seeds are placed in each house. 2. Each player controls the six houses and their seeds on his/her side of the board. His/her score is the number of seeds in the store to his/her right. [Clarification: from our perspective, player 1's store is to the left, player 2's store is to the right.] 3. Players take turns sowing their seeds. On a turn, the player removes all seeds from one of the houses under his/her control. Moving counter-clockwise, the player drops one seed in each house in turn, including the player's own store but not his/her opponent's. 4. If the last sown seed lands in the player's store, the player gets an additional move. There is no limit on the number of moves a player can make in his/her turn. 5. If the last sown seed lands in an empty house owned by the player, and the opposite house contains seeds, both the last seed and the opposite seeds are captured and placed into the player's store. [Clarification: moves that end on an opponent's empty house end normally without a capture.] 6. When one player no longer has any seeds in any of his/her houses, the game ends. The other player moves all remaining seeds to his/her store, and the player with the most seeds in his/her store wins. # Example (Parenthetical text should not appear in actual output.) Player 1 0 3 3 3 3 3 3 3 3 3 3 3 3 0 > 2 (prompt arrow and line break are purely optional) Player 2 1 1 0 3 3 3 3 4 3 3 3 3 3 0 > 4 Player 2 (P2 gets a bonus turn from rule #4) 1 0 3 3 3 3 3 4 3 3 0 4 4 1 > 5 Player 1 1 0 3 3 3 4 4 4 3 3 0 0 5 2 > 4 Player 1 (P1 captures P2's seeds in space 1) 6 0 4 4 0 4 4 0 3 3 0 0 5 2 ... Player 2 12 0 0 10 0 1 0 0 0 0 0 0 1 13 > 6 Player 1 wins (because the non-finishing players gets all remaining seeds on their side, it's 23-14)  Meta question: Would this be improved by removing some of the rules? • Do the players run the game once and then take it in turns to take moves, with the process ending only when the game ends? Or do they run the program once per move? – Peter Taylor Jan 30 '14 at 10:06 [This is the first time I'm using the sandbox. I want to get feedback/suggestions before posting the question.] Make a spider web (standard, orb type) that fills frame in the ratio of n:m, where n, m are input integers. You may use the example below as a model (but you don't need to use labels). Your web should have multiple radii, at least 4 of which attach directly to the frame. The remaining radii should attach to the outer outline (perimeter) of the web. The web should have at least 15 radii. The mesh spacing should be more or less uniform spacing (although occasional weaving mistakes" or crossings are encouraged and will receive a bonus). This is code-golf, so the shortest code (minus bonuses) wins. Bonuses (to be removed from the number of characters in your code). Bonuses are awarded for the following features that reflect the architecture of an actual web (as opposed to a perfectly symmetric rendering). They are somewhat greater than usual as an incentive for attention to detail and realism. -mesh spiral instead of concentric circles: 40 pts -assymmetric web: 31 pts. (e.g. height of capture area greater than width) -irregularly spaced radii: 42 pts -distinct segments between radii (straight or crooked, but not the arc of a circle): 32 pts -outer and inner outline clearly distinct from the spiral: 41 pts -irregular outer outline: 20 pts -2 or more easily observable reverses in spiral: 40 The accept will be awarded on Feb. 20, 2014. • If there are bonuses then it isn't code-golf, by definition. It's not clear what output formats are acceptable. I'm not sure what you mean by "distinct segments between radii". "2 or more easily observable reverses" seems problematic: the ease of observing reverses is subjective, and might in addition depend on input and/or on the random numbers obtained. The weighting for the bonuses seems very arbitrary: is there any justification for it? – Peter Taylor Feb 3 '14 at 11:49 • Re: bonuses, I should probably decide on the features I want included in the web, thereby eliminating bonuses altogether. Distinct segments means that there should be 2 straight mesh segments between radius n and radius n+2 (not sure whether this should be required in instructions to be updated.) Will give reverses more thought. – DavidC Feb 3 '14 at 12:02 ## Write a PHP Code Golfer code-challenge Since my currently daily programming is in PHP, I tend to try the challenges on the site using that language, but frequently I large program because of the verbosity of the language. And then I have to strip it for presentation... But this is not a tips question, it's an eviscerating challenge. The objective is to write a program in the language of your choice that takes a PHP file and outputs a golfed valid PHP file with the same functionality. The scoring will be the average reduction in percent of the result of running the program with 3 selected files (not yet selected, I was thinking of some open source library) The output file should run on at least 5.4 (so shorthand arrays, function dereference, traits are available) Since the score is the difference between the ungolfed and golfed files, techniques beyond minifying are encouraged, such as using code subtitution, eval, compression,$\$ (variable variables), dereferencing...

Scoring example: The 3 sources have 450, 1200 and 3500 chars respectively

results lenghts: 250, 1000, 3300
reduction: 200, 200, 200 (44%, 17%, 6%) average: 22%

results lenghts: 350, 1050, 3150
reduction: 100, 150, 350 (22%, 13%, 10%) average: 15%

In this case Answer 1 would win, even tough both answers got the same total reduction (-600 chars)

• It's a specialisation of codegolf.stackexchange.com/q/3652/194 , so would likely be closed as a duplicate. – Peter Taylor Feb 4 '14 at 22:44
• @PeterTaylor I saw it. is similar, but I include an objetive goal and score. have any idea on how to make it more unique? – Einacio Feb 5 '14 at 2:43
• "Making it shorter" is too broad, can I just delete some comments? If not, can I only shorten one variable and it's ok. It's not very interesting like this... – Fabinout Feb 5 '14 at 9:56
• @Fabinout the objective is golfing the code. If you only remove some characters, I doubt you'll get a good score – Einacio Feb 5 '14 at 15:27
• Alright, the criterion is the size of the output source code. good clarification. – Fabinout Feb 5 '14 at 15:55
• Sum the bytes with the percents or separately? Also, no matter what sources you choose, make sure to paste the code into your questions; who knows when the code in the library will change? – Justin Feb 6 '14 at 19:11
• i'll edit the bit about scoring (with examples) tomorrow (when i come back to work). I'll post the test sources as a pastebin, but I'll wait to choose them until the question is polished enough and someone consider it interesting enough – Einacio Feb 6 '14 at 19:34
• Is there anyone more with questions? is still possible that it will be marked as a duplicate? or can i choose the sources and publish it? – Einacio Feb 13 '14 at 19:22

# Create diagonal code

Your task is to create a program that outputs d=s*sqrt(2).

Specs:

• Your program must be at least 4 lines long;

• d=s*sqrt(2) cannot be hardcoded as is (so using ascii, compression, encoding, etc. is allowed and encouraged);

• For each line of code n, pick up the nth character. The string obtained this way must be a valid program in a programming language of your choice, that must be different from the one you used for the main program. The obtained program must compile successfully, but it can throw errors, exceptions, etc.;

• If at the nth line there is no nth character, you can consider that character as a whitespace or a newline. This cannot be done for the first 4 lines, which must be long at least n non-whitespace characters.

• Your main program must end successfully (no errors, exceptions, etc.);

• Internet access is forbidden;

• Most upvoted answer in 2 weeks wins.

Happy coding!

I was unsure about making this a with several bonuses (polyglot answer, secondary program still valid, etc...).

### Some bonuses for the code-challenge version:

+15 for any other hidden answer;
+5 for every hidden answer that runs and ends successfully, without any problem;
+15 for every hidden answer that is a polyglot;

Which version would you prefer? Is there something you would change/improve in this question?

I personally like the one, but the KISS principle (Keep it simple, stupid!) reminds me that I may be wrong.

• It's trivial to make the diagonal program be just whitespace (many scripting languages will accept this as a program) or H  (valid program in H9Q+). – Peter Taylor Feb 26 '14 at 9:26
• Nowhere does it say that the diagonal program must output your magic string: it doesn't even have to execute correctly. Your amendment doesn't really fix things: I can now have the second line be #H, the third be #HH, etc. – Peter Taylor Feb 26 '14 at 9:37
• You're right; Don't know why, on a second read I messed up the meaning of your comment. Anyway, I suppose this excludes code-challenge unless I/we don't find a way to avoid such trivial solutions. I guess popularity-contest would still be ok, since more interesting solutions could be found, right? – Vereos Feb 26 '14 at 9:41
• I think my views on popularity-contest in general are well known. On further reflection, there are enough languages in which any string of bytes is a valid program that I don't think this question can work as is. If you want to save it, I think you need to look at doing something like a very difficult double-quine. – Peter Taylor Feb 26 '14 at 9:49
• Thinking about quines and diagonals (which was the "spirit" of the question), what about a sort of mini-quine? The main program would have to display d=s*sqrt(2) only, and its diagonal must reproduce the code used to display the magic string (no comments allowed). It could be tagged code-golf or code-challenge. – Vereos Feb 26 '14 at 11:04

# Create a Karnaugh-map calculator

Given an input of a truth table, generate a corresponding K-map.

Input:

Input will be of the form 10110001 where each bit is a row of a truth table. Count from the left to the right; so that input would be a table of:

i2i1i0 f
0 0 0|1
0 0 1|0
0 1 0|1
0 1 1|1
1 0 0|0
1 0 1|0
1 1 0|0
1 1 1|1

Max 4 variables will be inputted

K-maps (a small explanation):

K-maps are a way of simplifying boolean-algebra expressions.

Let's say we have 4 variables: a, b, c, d. Let the truth-table be 1110101001111111 (and the columns on the truth table be labeled, from left to right: a, b, c, d). Arrange the variables like so:

   cd
ab\   00 01 11 10
00
01
11
10


Note the grey-code counting scheme.

Fill in the table with the corresponding values from the truth table:

   cd
ab\   00 01 11 10
00 1  1  0  1
01 1  0  0  1
11 0  1  1  1
10 1  1  1  1


Group the values in rectangles whose dimensions are the largest possible powers of two. Note that this table signifies a torus, so wrap over the left and right edges.

The expression for the truth table is the ors of the and of the unchanging elements. For this, that would be:

Purple group: ¬b ∧ ¬c (for 0's, make them 1 by notting the value)
Green group: ¬a ∧ ¬d
Black group: a ∧ d
Blue group: b ∧ ¬d

Expression: (¬b ∧ ¬c) ∨ (¬a ∧ ¬d) ∨ (a ∧ d) ∨ (b ∧ ¬d)

Output:

• Generate a 2D K-map (for more variables, add on either side) and show the grouping. K-map must be of the form I used. For less variables, remove rows or columns and change the list on the top left corner.
• assume alphabetical ordering on the variables, that is, the first variable is a, second: b, third: c, and so on.
• Also show the expression. Rather than use the unicode characters, the following is permissible:

~ instead of ¬


Edit: Possible duplicate: More fun with gates: Karnaugh simplification

• I think the grouping is not unique and therefore I might choose the most basic grouping (i.e. none). – Howard Feb 26 '14 at 9:02
• Although @Howard's concern is partially answered by "rectangles whose dimensions are the largest possible powers of two", it's not obvious to me why you haven't also circled the entire row 10 and the bottom-right quadrant. – Peter Taylor Feb 26 '14 at 9:29
• @PeterTaylor You're right - didn't read that line. But still my main concern is correct: it is not unique. Or as your remark shows it is not optimal if you choose all rectangles. – Howard Feb 26 '14 at 9:33
• Also for higher number of variables you have to either go to n dimensional K-maps or you won't find all possible rectangles (they are no longer adjacent in the matrix). – Howard Feb 26 '14 at 9:38
• @PeterTaylor In priority: Biggest rectangles, then least number. That is a big rectangle, but it is redundant with the others because every 1 in it is already circled. – Justin Feb 26 '14 at 16:44
• @Howard Good point. I'll restrict it to 4 or less variables. – Justin Feb 26 '14 at 16:47
• For the expression: rather than using A and V, why not * and +? That's fairly conventional use of field notation to represent GF(2). – Peter Taylor Feb 26 '14 at 17:11
• Ahem. OR is, of course, not the same as + in GF(2). But * and + is still the conventional notation for operations over the Boolean semiring. – Peter Taylor Feb 28 '14 at 15:31

Title: Implement ROT-13... in ROT-13

Content:

Challenge: Implement ROT-13 in code that works as both itself and as the ROT-13 version of itself.

### Scoring:

Your score is calculated as a percentage of used, ROT-13 eligible bytes in total of both versions of the program divided by total bytes (all characters) of both versions.

A used, ROT-13 eligible byte is any character that is not part of a comment or ignored by the compiler/interpreter. For example, any character in a brainfuck program that is not +-<>[],.  is not considered a used byte, and any character in a C program including and after // or inside /* */ is not considered a used byte. All special symbols in APL are not considered used, as are all characters in a Whitespace program (sorry).

Example scoring:

### C: 21/32 = 65.625%

main(){printf("Hello World!");}

• Originally this question was ROT-47, not ROT-13. The rules are chosen so that choice of language doesn't easily determine the winner; otherwise, whitespace would easily win. When I changed it to ROT-13 I made only [A-Za-z] count so that a language like golfscript or brainfuck would not automatically score 100%. Looking for thoughts on how to capture the idea without making it too "choice of language" dependent. – durron597 Mar 3 '14 at 21:13
• Just saying, I have a C answer for the 47-version: qp.mniip.com/p/tz pick either of the lines – mniip Mar 3 '14 at 21:29
• @mniip Okay I undeleted it :) – durron597 Mar 3 '14 at 21:48

# Convert input to ASCII Semaphore

With monitor resolutions getting higher and font sizes getting lower, a good programmer has to make efforts to ensure that output is accessible to the visually impaired. This can be problematic when the only display is in text. Toward this end, your assignment (if you choose to accept it) is to write a program that converts text input into ASCII art flag semaphore.

## Input

1. Your program must accept any letter in the ASCII character set from A to Z (case insensitive) and spaces.
2. The program can accept input in any way that is convenient for the language it is written in (stdin, command line, file, etc.).

## Output

1. The program should output an ASCII art representation of the input string in flag semaphore. Follow this link to see the expected encoding.
2. Line feeds and carriage returns should be interpreted as spaces.
3. Numbers and other non-letters in the input may be ignored.
4. You may use whatever ASCII art representation of the semaphore sender you like, but it must contain a person holding two flags and have distinct arms, legs, head, and flags. It must be at least 10x10 characters.
5. Output may be either horizontal or vertical.

## Example

Input: Hello

Output:

           ###
###
#
_____########
|  |       ###
|__|      ####
# ###
#  ###
/   # #
/\   # #
/  \  # #
\  /  # #
\/  ## ##
/\
/  \
/\  /
#  \/
###  #
### #
# #
####
# ###
# ###
# ###
# ###
| # #
|__ #
|  |#
|__|#
## ##
/\
/  \
/\  /
#  \/
###  #
### #
# #
###
####
# ###
#  ###
#   ###
/    # #
/\    # #
/  \   # #
\  /   # #
\/   ## ##
/\
/  \
/\  /
#  \/
###  #
### #
# #
###
####
# ###
#  ###
#   ###
/    # #
/\    # #
/  \   # #
\  /   # #
\/   ## ##
/\
/  \
\  /\
\/  #
#  ###
# ###
# #
_____########
|  |       ###
|__|       ###
###
###
# #
# #
# #
# #
## ##


## Scoring

This is code golf. Shortest code wins.

• define "easily recognisable". Would a simple 3x3 compass (say, with a head if not covered) do? say:.o. -|. /|. ; or even: ... xx. x.. (read by lines, dots represent spaces) – John Dvorak Mar 6 '14 at 20:16
• @JanDvorak Good catch. Edited to include distinct items that must be present and a minimum size. I'm not exactly sure how to make that rule more clear. – Comintern Mar 6 '14 at 20:34
• Define "person holding two flags". Is what I drew a person? Is this a (lying, due to formatting issues) person: o--? Are three x's on a vertical line a person? – John Dvorak Mar 6 '14 at 20:43
• @JanDvorak Ack! had to many tabs open and forgot to save my edit. I think number 4 for output should cover that. – Comintern Mar 6 '14 at 20:47
• Define "distinct arms, legs, head, and flags." But I suggest allowing very small figures as well, otherwise this will turn into a kolmogorov-complexity-like question with very little of the code actually involving generating a pair of directions. – John Dvorak Mar 6 '14 at 20:51
• Very similar to this question. The ascii art is more complex here so perhaps it's not close enough to be called a duplicate... – Gareth Mar 6 '14 at 22:20
• I disagree with @JanDvorak: I think this would be better with a fixed output spec which must be followed exactly. That way people can golf their code rather than the output. – Peter Taylor Mar 6 '14 at 23:59
• Standard figures seem best to me as well. If you demonstrate a full "clock" of hand positions for the standard figure, then you can require those as output. That's easier to assess than free reign for variations. – Jonathan Van Matre Mar 7 '14 at 0:14