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

Sandbox FAQ


To post to the sandbox, scroll to the bottom of this page and click "Answer This Question". Click "OK" when it asks if you really want to add another answer.

Write your challenge just as you would when actually posting it, though you can optionally add a title at the top. You may also add some notes about specific things you would like to clarify before posting it. Other users will help you improve your challenge by rating and discussing it.

When you think your challenge is ready for the public, go ahead and post it, and replace the post here with a link to the challenge and delete the sandbox post.


The purpose of the sandbox is to give and receive feedback on posts. If you want to, feel free to give feedback to any posts you see here. Important things to comment about can include:

  • Parts of the challenge you found unclear
  • Comments addressing specific points mentioned in the proposal
  • Problems that could make the challenge uninteresting or unfit for the site

You don't need any qualifications to review sandbox posts. The target audience of most of these challenges is code golfers like you, so anything you find unclear will probably be unclear to others.

If you think one of your posts requires more feedback, but it's been ignored, you can ask for feedback in The Nineteenth Byte. It's not only allowed, but highly recommended! Be patient and try not to nag people though, you might have to ask multiple times.

It is recommended to leave your posts in the sandbox for at least several days, and until it receives upvotes and any feedback has been addressed.


Search the sandbox / Browse your pending proposals

The sandbox works best if you sort posts by active.

To add an inline tag to a proposal, use shortcut link syntax with a prefix: [tag:king-of-the-hill]. To search for posts with a certain tag, include the name in quotes: "king-of-the-hill".

  • \$\begingroup\$ What if I posted on the sandbox a long time ago and get no response? \$\endgroup\$
    – None1
    Commented May 15 at 14:05
  • \$\begingroup\$ @None1 If you don't get feedback for a while you can ask in the nineteenth byte \$\endgroup\$
    – mousetail
    Commented May 29 at 13:27

4704 Answers 4704

121 122
124 125

How long should this song last?

Enter the world of sheet music. A composition (the musical piece, which may or may not be a song) is divided into bars. The length of a bar is defined by the time signature. The time signature states how the bar is divided into beats, and what length of note carries the beat.

Note lengths are always powers of 2. 4 means a quarter note, 2 a half note, 8 an eighth note (or a quaver if you're a snob), etcetera. A half note (2) is twice the length of a quarter note (4), which is itself twice the length of a quaver (8), and so on.

A time signature may look like this: 3/4. The 4 means that the quarter note carries the beat, and the 3 means that there are 3 of them in one bar. 3/2 means there are three half-notes in a beat, 7/8 means there are seven quavers, and so on.

Now, the actual speed at which a piece is to be performed depends on the tempo. That is usually expressed in beats per minute (bpm). The tempo also defines the note carrying the beat (usually the same as the one in the time signature but not always). So, you can have the time signature be 8=150, meaning there are 150 quavers in a minute (in the sheet music it would be notated ♪=150).

Both tempo and time signature can change throughout the composition.


Use the following format for your input (or something very similar). It is a list of events:


This is the simplest form. It is a list of integer-string pairs (you're obviously free to go with string-string pairs if it makes your program simpler). The integer defines at which bar the event happens (starting from 1), and the string defines what happens there. If it is in the form of x/y, then it is a new time signature. If it is in the form of x=y, you have a new tempo. Lastly, an empty string designates the end of the score (exclusive, so the above example has 520 bars).

With changes, the format may look like this:

[46, "4=155"],
[67, "5/4"],
[68, "4/4"],

The output of the program should be the duration of the entire piece in "xm ys" (where x is the number of minutes and y is the number of seconds. You can leave out the "ys" part if there's no spare seconds, but it is not necessary).

This is , so shortest code wins!

Important note!

Real artists do not follow the tempo exactly. Only beginners use a metronome to match the exact number of seconds as notated; more experienced musicians know to dynamically speed up or slow down depending on the mood, their personal preference, etcetera. Therefore, it is perfectly acceptable for your answer to be up to 34% higher or lower than the "correct" answer. Also, the minimum length of a composition is 2 minutes and 30 seconds.

Test cases



The time signature has 4 quarter notes a bar, and 520 bars, so 4*520=2080 quarter notes. There's 120 quarter notes per minute, so 2080/120=17.333 minutes, or 17m 20s.


[46, "4=155"],
[66, "5/4"],
[76, "6/8"],

For the first 45 bars, there's 4 quarter notes a bar, so that's 45*4=180 quarter notes. Now the tempo is 120 8th notes per minute, which is 60 quarter notes per minute, meaning the first bit lasts 180/60=3 minutes.

Then a tempo change: from bar 46 to 67 there's 20 bars of 4/4 (thus 4*20=80 quarter notes), and at 155 quarter notes per minute you add 155/80=1.94 minutes = 1m 56s. Total is 4m 56s.

Then a time signature change: 10 bars of 5 quarter notes per bar = 50 quarter notes. 155/50 = 3.1 minutes = 3m 6s. Total is 8m 2s.

Then another time signature change. 6 eighth notes per bar for 76 bars is 76*6=456 eighth notes. Tempo is still 155 quarter notes per minute, which is 310 eighth notes per minute. 456/310=1.471 minutes = 1m 28s. Total comes down to 9m 39s.

3. (The third movement of Shostakovich's second piano concerto, you get 5 bytes off if you listen to this while programming (not really but more people need to listen to Shosty dammit))

[1, "2/4"],
[1, "4=176"],
[75, "7/8"],
[102, "6/8"],
[103, "7/8"],
[106, "3/8"],
[107, "7/8"],
[109, "2/4"],
[112, "3/4"],
[113, "2/4"],
[116, "3/4"],
[117, "2/4"],
[120, "3/4"],
[121, "2/4"],
[124, "3/4"],
[125, "2/4"],
[155, "7/8"],
[160, "2/4"],
[175, "7/8"],
[180, "2/4"],
[181, "6/8"],
[182, "2/4"],
[186, "7/8"],
[188, "2/4"],
[222, "7/8"],
[225, "2/4"],
[286, "7/8"],
[308, "9/8"],
[309, "7/8"],
[314, "2/4"],
[317, "3/4"],
[318, "2/4"],
[321, "3/4"],
[322, "2/4"],
[325, "3/4"],
[326, "2/4"],
[329, "3/4"],
[330, "2/4"],
[356, ""]

Calculation is too long to show here, but it comes down to 4m 47s. The video is 5m 24s, proving my point that this is not an exact rule but rather a guideline.



Does this look like an interesting puzzle? Any tags I miss? Is the +/-34% allowance large enough to matter, or should it be more?

  • \$\begingroup\$ The "+- 34%" and "at least 2:30 min" are unneccessary for the challenge. They may be relevant for music, but not for programming. I doubt that this allowance will allow you to shave bytes off the task, given that it's straightforward parsing + arithmetic otherwise. \$\endgroup\$ Commented Nov 21, 2019 at 11:31
  • 1
    \$\begingroup\$ @AlienAtSystem I want to make the allowance relevant, both because it is musically appropriate, and because it would elicit different kinds of answers that approximate the solution. I suppose the arithmetic needs to be more complex before approximate solutions can be made with shorter programs? How about adding accelerando events that change the tempo over time? \$\endgroup\$
    – KeizerHarm
    Commented Nov 21, 2019 at 11:41
  • \$\begingroup\$ Or maybe I should make a hilariously long list of possible events (e.g. fermata changing the length of a single note, all the different types of ritardando with slightly different slowing down behaviours, etc.) and make it part of the challenge to sort out which ones are relevant to get close enough to the solution? \$\endgroup\$
    – KeizerHarm
    Commented Nov 21, 2019 at 11:44
  • 2
    \$\begingroup\$ I'm not an expert golfer, so I can't say at what level of complexity an approximation gets shorter than just the straightforward calculation. I think the site consensus is for approximative approaches to use precision scoring (How many out of this long list of test cases do you get accurately), because otherwise there is the hidden condition of "for all possible valid inputs", which is hard to prove for approximation algorithms. \$\endgroup\$ Commented Nov 21, 2019 at 11:51
  • \$\begingroup\$ @AlienAtSystem Very well, I could generate a list of 100 "compositions" and make the % of properly solved cases part of the score. I guess that would mean adding a different tag? I couldn't find one for "approximation" or direct synonyms of that. \$\endgroup\$
    – KeizerHarm
    Commented Nov 21, 2019 at 11:55
  • 1
    \$\begingroup\$ If you go for the fraction of cases correct method, the tag you want is test-battery. \$\endgroup\$ Commented Nov 21, 2019 at 19:46
  • \$\begingroup\$ So, we wont include 𝄆 repeat sign 𝄇 in this challenge. Am I right? \$\endgroup\$
    – tsh
    Commented Nov 27, 2019 at 3:35
  • \$\begingroup\$ @tsh Not at this stage. And if I do, it definitely won't be using the unicode token. \$\endgroup\$
    – KeizerHarm
    Commented Nov 27, 2019 at 10:38

Deathmatch Football (Soccer)


2 Teams each of 11 Players and 3 Bank Players compete in a match of 90 minutes to find out who's the best. But... it wouldn't be deathmatch with no casualties, so after scoring, there is a chance to die. Better think twice before you shoot...


Each Team is represanted as a String of 14 chars (11 + 3). Every char az-AZ is unique to the whole match. So 2 teams could look like this

Team1: {"a","c","f","g","j","k","A","D","E","H","I","k","n","o"} //bank: k, n, o
Team2: {"b","d","e","h","i","l","B","C","F","G","J","l","m","P"} //bank: l, m, P

The Game:

The game lasts for 90 (+3) minutes. Every minute each team has one chance to score a goal. The player who's shooting gets randomly selected. The chance of a player to score a goal is the byte value of the char.

Example: "z" has a value of 122, so he has a chance of 122% (>=100%) means he will definetely score

If he scores he will die with a chance of his byte value / 2

Example: "z" has a value of 122, so he has a chance of 61% to die.

Special Events:

  • At minute 45, 60 and 75 a random player from the bank comes into the team (teams are not limited to 11 players, if no one has died yet)
  • If there is a draw at minute 90 OR both teams have less than 5 players, the game lasts for additional 3 minutes (90 + 3)
  • If a team has 0 players the game is over

Result and Rating:

Once a match is over. Display both teams, the final score, and the top scorer including goals.

Team1: {"a","f","A","D","p"}
Team2: {"b","e","h","P"}
Score: 20:18 // So Team1 won
Top Scorer: A=>5

The code with less bytes is the winner.

Extra Notes:

You are free to choose the form of the output as long as you can clearly see the remianing teams, who won and the top scorer. No loopholes, do i need to say that?


Multiplicative Digital Root

The Digital root of a number is found by iteratively summing its digits until you end up with a single number (e.g. 99 -> 18 -> 9)

The multiplicative digital root is found by iteratively multiplying the digits (e.g. 99 -> 81 -> 8)

The Challenge

Print out the digital root of all numbers 0..99 inclusive. Note that this is based on https://oeis.org/A031347, and the first 10 numbers (0-9) are treated without leading 0s.




In any sensible format:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 
0, 2, 4, 6, 8, 0, 2, 4, 6, 8, 
0, 3, 6, 9, 2, 5, 8, 2, 8, 4, 
0, 4, 8, 2, 6, 0, 8, 6, 6, 8, 
0, 5, 0, 5, 0, 0, 0, 5, 0, 0, 
0, 6, 2, 8, 8, 0, 8, 8, 6, 0, 
0, 7, 4, 2, 6, 5, 8, 8, 0, 8, 
0, 8, 6, 8, 6, 0, 6, 0, 8, 4,
0, 9, 8, 4, 8, 0, 0, 8, 4, 8,

Sandbox comments

  • this is the only related challenge I could find, but it doesn't ask the same thing.

  • Would this be better/more interesting as a "calculate the multiplicative digital root of the input" challenge?

  • 1
    \$\begingroup\$ no, because 0,1..9 are single-digit numbers. 00, 01..09 would make the first row zero, but based on the OEIS sequence (oeis.org/A031347) I want to treat them as shown \$\endgroup\$ Commented Nov 25, 2019 at 11:14
  • \$\begingroup\$ Ah ok, I misread it as a multiplication table instead of just a sequence of 0..n. Ignore my now deleted comment. So we just output the first 100 numbers in the (0-based) sequence? Would outputting the 1-based sequence be allowed (1..100 instead of 0..99)? If not np, but I could save a byte in my prepared solution if it would be allowed. :) \$\endgroup\$ Commented Nov 25, 2019 at 11:48
  • \$\begingroup\$ Sorry yeah, I've just formatted it that way for clarity. No, 0-99 was the challenge I had in mind. Alternatively would this be a better challenge if you had to calculate the multiplicative digital root given an input (arbitrary-length integer)? Or should I just propose both challenges? \$\endgroup\$ Commented Nov 25, 2019 at 12:52
  • \$\begingroup\$ Either is fine by me, but not both. If the single input would already exist as challenge, this ranged one would simply use those answers with a 0..99 map around it (which is also what I do in my current answer in my language of choice: calculating the multiplicative digital root of an input is 3 bytes; adding a range 0..99 map around it is 4 more bytes). \$\endgroup\$ Commented Nov 25, 2019 at 12:58
  • \$\begingroup\$ The challenge you linked to is the same except that it doesn't require wrapping the thing in a for loop. I believe this is a duplicate. \$\endgroup\$ Commented Nov 25, 2019 at 13:40
  • \$\begingroup\$ @mypronounismonicareinstate it wouldn't be a for loop, but rather recursion (or a while), right? Anyway, the challenge as written here currently asks for the whole set - so I'd say that's substantially different to the linked challenge \$\endgroup\$ Commented Nov 25, 2019 at 13:47
  • \$\begingroup\$ I personally see it as closely related instead of a dupe @mypronounismonicareinstate, although I agree parts of the answers could be reused. That other challenge asks: remove all zeroes, and take the product of the remaining digits. Whereas this challenge asks: for the numbers in the range 0..99; reduce by taking the product of its digits until a single digit remains. In 05AB1E for example, that other challenge is 0KSP and this challenge is т<ÝεΔSP. The SP part (split to digits, take product) is similar. Both challenges are rather trivial in most languages, though - even non-golf langs \$\endgroup\$ Commented Nov 25, 2019 at 14:35

Double an infinitely long number

You are given a non-negative real number strictly less than 0.5 as an endless stream of digits. Output twice of it in an endless stream of digits.

The exact format is flexible. You may separate digits by any reasonable separator, or don't use separators. You may prepend something representing "0" or "0.", or just omit the integral part. The input and output don't have to be in the same format. But everything must be in base 10, from the most significant digit to less significant digits.

Your code doesn't have to print anything immediately. But if each digit in the input would be given in a finite amount of time, and it is in a state allowing output in your chosen I/O method (so that if you are using a generator, you may assume some code is repeatedly accessing the generator), each digit in the output should also be printed or returned in a finite amount of time.

Shortest code wins.

  • 1
    \$\begingroup\$ I presume the stream of digits is given from largest to smaller place? I think this would be cleaner if we didn't have to deal with a decimal point, say by saying the input starts after the decimal point and is less than 0.5. \$\endgroup\$
    – xnor
    Commented Nov 25, 2019 at 10:10
  • \$\begingroup\$ Would it be a valid submission to give a stateful function that takes in a digit, and outputs some a string of digits, so that repeatedly calling it with digits from the stream gives the desired output if concatenated? Or does our code have to handle the read-and-output loop itself? \$\endgroup\$
    – xnor
    Commented Nov 27, 2019 at 1:30
  • \$\begingroup\$ @xnor Not sure. I'll accept it if it becomes a standard I/O method for reading/writing lists. \$\endgroup\$
    – jimmy23013
    Commented Nov 27, 2019 at 10:52

Product of Shuffle Algebra

Compute the shuffle product of two elements of a Shuffle Algebra.


  1. An Alphabet is a set of symbols. For this challenge it is \$A = \{a,b,c,\ldots,z\}\$. Let us use bold letters for variables that denote elements of the alphabet.
  2. A Word is a tuple of of arbitrary size where each entry is an element of our alhpabet. Let \$W\$ be the set of words. Instead of writing a word as \$(p,p,c,g)\$ we just omit the unnecessary symbols and write it as \$ppcg\$. We write the empty word as \$\varepsilon = ()\$. Let us use lower case greek letters (\$\alpha, \beta, \gamma, \ldots\$) for variables that denote words.
  3. The shuffle algebra \$S\$ (simplified for the purpose of this challenge) is a set of \$\mathbb Z\$-linear combinations of words. This means that each element consists of a few words which each have an integer associated with them (the coefficients), which are then formally summed up. Here are some examples: $$\begin{array}[l] \\ a \\ b \\ 5\varepsilon = 5\\ a + (-5)b = a-5b \\ a + 2a = 3a \\xy - 3code +5golf +5se \end{array}$$ Note that terms (that is a word with it's coefficient) where the coefficient is zero are considered as \$0\$ and are not listed. Let us use uppercase letters form the greek alphabet (\$ \Gamma, \Delta, \Phi, \Psi, \ldots \$) letters for variables denoting an element of the shuffle algebra.
  4. We can add elements of the shuffle algebra just as you'd expect: The coefficients of equal words are just summed. for instance let $$\begin{align*} A &:= aq + 3bccd + 5cg \\B &:= -3bccd + 6cg + 5qq .\end{align*}$$ Then $$\begin{align*} A+B &= aq + 0bbcd + 11cg + 5qq \\&= aq + 11cg + 5qq.\end{align*}$$
  5. We multiply elements of the shuffle algebra using the shuffle product denoted by the symbol \$⧢\$. We can recursively define it as follows:

    A. First we define the shuffle product for words: if one of the words is empty (=\$\varepsilon\$) we have $$\alpha ⧢ \varepsilon = \varepsilon ⧢ \alpha = \alpha.$$ If both are nonempty, we split them up into a one letter suffix and a leading word. So let us write the two words \$\alpha\$ and \$\beta\$ as $$\alpha = \varphi \mathbf{a} \qquad \beta = \psi \mathbf{b}$$ Then the product is defined via the recursion $$\alpha ⧢ \beta = (\varphi ⧢ \beta)\mathbf{a} +(\alpha ⧢ \psi)\mathbf{b}.$$ This is where the "shuffle" in the name is coming from: The shuffle product results in all possible riffle shuffles of the two words. Consider the following examples: $$\begin{align*}ab ⧢ xy = abxy + axby + xaby + axyb + xayb + xyab\end{align*}$$

    B. Two shuffle algebra elements \$\Phi = \sum_i f_i \varphi_i \$ and \$\Psi = \sum_j g_j \psi_j \$ (where \$f_i, g_j \in \mathbb Z, \varphi_i, \psi_j \in W\$) are multiplied as follows: $$\Phi ⧢ \Psi = \sum_i \sum_j \underbrace{(f_i \cdot g_j)}_{\in \mathbb Z} \underbrace{(\varphi_i ⧢ \psi_j)}_{\in S}$$


  • The inputs can each be taken as a string or as a list of pairs where each pair is represents one term (coefficient and word) of the element, or alternatively as two lists of the same length or other similar formats.
  • The output format must match the input format.
  • The output must be reduced: No two terms should share the same word.


Haskell script for generating Examples

  • \$\begingroup\$ Might you consider just having the challenge be to multiply two words? When thinking about how I'd do this challenge, I'm imagining implementing the shuffle product, than iterating over pairs of monomials and multiplying them and their coefficients, then reducing by combining like terms. I don't know anything about the shuffle algebra, so I don't know if there's something that lets you work with elements in some more special way. \$\endgroup\$
    – xnor
    Commented Sep 14, 2019 at 20:10
  • \$\begingroup\$ @xnor My thought was that if we just take two words for the input, the output will still be a general element (e.g. aa ⧢ ab = 3*aaab +2*aaba +1*abaa), so you would already have to implement the simplification (collecting the the terms with the same words), so the additionl step of multiplying two general elements wouldn't be a lot more compilcated. - Would you suggest also removing the simplification step, so that the output would just be a list? (e.g. aaab,aaab,aaba,aaab,aaba,abaa for the input from above) I think this would on the one hand be a lot easier, but also less of a challenge. \$\endgroup\$
    – flawr
    Commented Sep 14, 2019 at 20:31
  • \$\begingroup\$ Hmm, I hadn't considered that a riffle product of monomials would already produce repeats. I don't know what I'd suggest. For what it's worth, I tried searching for a duplicate of generating all possible riffles and didn't find one, though I have a memory of having done something like it on anarchy. \$\endgroup\$
    – xnor
    Commented Sep 14, 2019 at 20:37

Walk N Spaces on a Game Board

This challenge is inspired by Touhou Cannonball, a mobile game that includes a board game element similar to Mario Party, except for the fact that movement isn't restricted to one particular direction.

A Touhou Cannonball board.


On your turn, a six-sided dice is rolled to determine how many spaces to move. For each of those spaces, you can move to any adjacent space, as long as you do not backtrack to the space you were on in a previous move.

For example, if you roll a 2 and start from space [2] in the following graph, you can move left twice to space [0] or right twice to space [4], but you cannot move once left and once right to land on space [2] again, because you traveled across the same edge in two consecutive moves.


You can move to a previously visited space, as long as you aren't "backtracking" to that space -- if you roll a 4 on the following graph starting from space [0], you can land on [0] by going in a circle around the graph with the move [0]->[1]->[2]->[3]->[0].

^    ^
|    |
v    v

Some graphs may have some directed edges. If your graph is [0]-->[1], you can move from [0] to [1], but not the other way around.

The Challenge

Given any appropriate directed graph structure (incidence matrix, adjacency list, etc.), a starting position, and a number of spaces to move, output all possible positions you can move to.


Example inputs are zero-indexed in the format starting position, number of spaces, adjacency list. I will also have the visual graph included for better visualization. (More to be added later)

Input: 2, 5, [ [1,2], [0,3], [3,4], [1,6], [2,5], [4,6], [3,5] ]
^       ^
|       |
|       v
^       ^
|       |
v       v

Output: [1,2,5]

How fair are my dice?

(Inspired by a dream I recently had regarding Mario Party. This is not fully fleshed-out yet.)

Given a pair of dice, e.g., [[1,1,2,2,3,3], [1,2,3,4,5,6]], output how "closely" they resemble a pair of standard 1-6 dice (i.e., [[1,2,3,4,5,6], [1,2,3,4,5,6]]) in terms of distribution of numbers when rolled.

  • \$\begingroup\$ Is the input always a pair of six-sided dice or can they have a variety of face counts? Sorted? How would [[2,3,4,5,6,7],[2,3,4,5,6,7]] compare considering it'd have the same distribution curve? \$\endgroup\$
    – Veskah
    Commented Dec 2, 2019 at 16:20
  • \$\begingroup\$ You need to flesh out details on how this should be measured. Do I go by simulation? Do I base the distribution on the total of each pair of rolls? What is "closely"? Sum of squared error? \$\endgroup\$
    – Beefster
    Commented Dec 6, 2019 at 19:56

A game of putting lines through dots.


Rate your brevity

This challenge is to produce a script that will accept a string as input, and generate a score for it using the rules defined below. Your score is the return value of your program given its own source as input.

The first scoring system

Each additional unique character has an escalating penalty to your score.

The first unique character is worth -1
The second unique character is worth -2
The third unique character is worth -3

The second scoring system

Each repetition of a given character incurs a further escalating penalty to your score.

The first usage of a given character incurs no additional penalty
The second usage of a given character incurs an additional penalty of -1
The third usage of a given character incurs an additional penalty of -2
The fourth usage of a given character incurs an additional penalty of -3


  • The code abc would have a score of -6
  • The code aabc would have a score of -7
  • The code aaaabc would have a score of -12


  • Your score starts at 0
  • The highest score for a given language wins.


The below Stack snippet will parse a string according to the rules defined above and generate the score.

function testScore() {
  var score = 0,
      counter = 0,
      input = document.getElementById('code').value,
      instances = {},
  input = input.split('');

  for(x = 0; x < input.length; x++) {
    if(typeof instances[input[x]] == 'undefined') {
      instances[input[x]] = 0;
      score -= ++counter;

  keys = Object.keys(instances);
  for(x = 0; x < keys.length; x++) {
    for(y = 0; y < instances[keys[x]]; y++) {
      score -= y;

  alert('Your score is:\n' + String(score));
  return false;
<form onsubmit="return testScore(this);">
    <textarea id="code" style="width: 100%; height: 150px;"></textarea>
    <button type="submit">Generate score</button>

  • \$\begingroup\$ I'd appreciate some pointers on what tags to use for this one - it's similar to code golf but isn't quite code golf. \$\endgroup\$
    – Scoots
    Commented Dec 11, 2019 at 11:48
  • \$\begingroup\$ Similar but a slightly different scoring system \$\endgroup\$
    – Veskah
    Commented Dec 11, 2019 at 13:02
  • \$\begingroup\$ This is two challenges: First, reading your own source code. Second, creating the score for an input string. In addition, the condition of "Parse yourself" is a non-observable requirement. In this case, it's definetly bad because it forces the two separate challenges approach onto people. I understand why you want to exclude print -45, but right now, the whole quine-except-not-really thing doesn't seem helpful. \$\endgroup\$ Commented Dec 13, 2019 at 14:09
  • \$\begingroup\$ @AlienAtSystem Respectfully I disagree with your assertion that reading the source code is a challenge; I'm very explicit that any means of getting your source code in is acceptable, even copy/pasting it as a command line argument. The parsing of your own code - I thought it might encourage people to golf in a way they may not be used to due to the escalating penalties involved in the scoring system. \$\endgroup\$
    – Scoots
    Commented Dec 13, 2019 at 15:36
  • 1
    \$\begingroup\$ If you don't want the source code reading to be part of the challenge, then don't write things like it is. Really just say Takes a string as input and outputs the uniqueness score and Your score is the return value of your program when given its own source as input. \$\endgroup\$ Commented Dec 14, 2019 at 9:13
  • \$\begingroup\$ @AlienAtSystem I take your point, your phrasing is definitley better than what I originally had. \$\endgroup\$
    – Scoots
    Commented Dec 14, 2019 at 11:32

Nash equilibrium of 2-player 3-choice zero-sum game


In a 2-player single finite game, a Nash equilibrium (NE) is a pair of strategies chosen by both players where neither has an incentive to deviate from their own strategy. For example, here is a payoff matrix of two players \$ A,B \$ where each player has two possible pure strategies \$ X,Y \$:

$$ \matrix{ A \backslash B & X & Y \\ X & 3 \backslash 3 & 0 \backslash 0 \\ Y & 0 \backslash 0 & 2 \backslash 2 } $$

In this game, if \$ A \$ chooses \$ X \$, \$ B \$ should also choose \$ X \$ because it will give \$ B \$ the best outcome. Likewise, if \$ B \$ chooses \$ X \$, \$ A \$ should also choose \$ X \$. Therefore, \$ (X,X) \$ is a NE. We can observe \$ (Y,Y) \$ is also a NE; although it gives less outcome than \$ (X,X) \$ for both players, there is no reason to select \$ X \$ when the opponent selects \$ Y \$.

But a strategy can also be a mixed strategy, i.e. choosing one of the pure strategies with some chance. Let's take a mixed strategy \$ S = \frac25X+\frac35Y \$. If \$ A \$ takes \$ S \$, \$ B \$'s expected outcome is always \$ \frac65 \$, regardless of \$ B \$'s strategy (either pure or mixed). In this case, \$ B \$ has zero incentive to deviate from whatever strategy \$ B \$ is already taking. The same can be said for \$ B \$ taking \$ S \$, so \$ (S, S) \$ is also a NE.

Nash's existence theorem states that every game has at least one Nash equilibrium, either pure or mixed. Note that a game may have many (possibly infinitely many) NEs.


In this challenge, we consider 2-player 3-choice zero-sum games, where each player has three possible pure strategies, and the sum of the two players' outcomes is always zero. The payoff matrix of such a game might look like this:

$$ \matrix{ A \backslash B & R & P & S \\ R & 0 \backslash 0 & -1 \backslash 1 & 1 \backslash -1 \\ P & 1 \backslash -1 & 0 \backslash 0 & -1 \backslash 1 \\ S & -1 \backslash 1 & 1 \backslash -1 & 0 \backslash 0 } $$

Since it is a zero-sum game, we can omit the payoffs of \$ B \$:

$$ \matrix{ A & R & P & S \\ R & 0 & -1 & 1 \\ P & 1 & 0 & -1 \\ S & -1 & 1 & 0 } $$

This game is equivalent to Rock-Paper-Scissors, and the only NE is, as we all know, mixed \$ (\frac13R + \frac13P + \frac13S,\frac13R + \frac13P + \frac13S) \$.

The challenge is to find at least one of the Nash equilibria, given the payoff matrix for player \$ A \$. Remember that a Nash equilibrium is a pair of \$ (\text{strategy of } A,\text{strategy of } B) \$.

For an outline of finding a mixed-strategy NE, refer to this Math.SE question. Also related: why some games don't have mixed-strategy NE.

Input and output

The input is a 3-by-3 matrix of integers which represent the payoff matrix for player \$ A \$. You can assume the magnitude of each integer won't exceed 100, and you can take the numbers in any order of your choice.

The output is a pair of strategies in the form of \$ (a_XX+a_YY+a_ZZ, b_XX+b_YY+b_ZZ) \$ where \$ a_i \$ and \$ b_i \$ are the chances of selecting one of the strategies. You don't need to format the output; outputting the 6 numbers \$ a_X,a_Y,a_Z,b_X,b_Y,b_Z \$ is fine. If you want to output a pure strategy, you can do something like \$ (1, 0, 0) \$.

Scoring and winning criterion

Standard rules apply. The shortest code in bytes wins.

Test cases

Matrix: (classic RPS)
  0  -1   1
  1   0  -1
 -1   1   0
NE: A's strategy = (1/3, 1/3, 1/3), B's strategy = (1/3, 1/3, 1/3)
Matrix: (scored RPS)
  0  -5   1
  5   0  -2
 -1   2   0
NE: A's strategy = (2/8, 1/8, 5/8), B's strategy = (2/8, 1/8, 5/8)
Matrix: (dumb game, pure strategy NE example)
  0   1   2
 -1   0   0
 -2   0   0
NE: A's strategy = (1, 0, 0), B's strategy = (1, 0, 0)
Matrix: (asymmetric game example, infinitely many NEs)
  2  -1   3
  0   3  -1
 -2  -3   0
NE: A's strategy = (1/2, 1/2, 0),
    B's strategy = any triple (x, y, z) that satisfies
                   x + 2z = 2y, x + y + z = 1, 0 <= x,y,z <= 1
Matrix: (asymmetric game example, one mixed NE)
  2  -1   4
  0   3  -1
 -2  -3   0
NE: A's strategy = (1/2, 1/2, 0), B's strategy = (2/3, 1/3, 0)



This is a repost of the underspecified challenge.


Remove all duplicates from one list of integers. A list is simply a sequence of connected values that allows the same values to be stored at different positions in this sequence.

If an item was found to be the same value as another item in this list, keep the first occurence of the item and remove the second (third and so on...) occurence of the item.


You may write a function or full program that takes a list as an input and returns a remove-duplicated list as an output.


  • This is a challenge, so shortest answer wins!

Join two file paths

A file path consists of letters a-z separated by slashes /. Your task is to join two paths as follows:

  • If the second path doesn't start with /, concatenate them with exactly one / in between.
  • If the second path starts with /, just output it.

For example,

/User/Desktop   temp/file   ->  /User/Desktop/temp/file
/User/Desktop/  temp/file   ->  /User/Desktop/temp/file
/User/Desktop   /temp/file  ->  /temp/file
/User/Desktop/  /temp/file  ->  /temp/file
relative/path   more/path/  ->  relative/path/more/path

You may assume the inputs don't contain two consecutive slashes, but they may start or end with a slash. Each input with be nonempty and not just a slash. You may use backslash \ in places of slash /.

Sandbox: Is this too boring? Too likely a built-in?

  • \$\begingroup\$ (Replacing with a bit cleaner proof) Here's a neat way that I think works to show that anti-commutativity implies any product equals zero for \$S=\mathbb{Z}\$. We have \$ a * b = a * (b+0) = - (a * b) - (a * 0)\$, so \$ a * b \$ is half of \$-(a * 0)\$ in the standard integer sense. This implies that the product \$ a * b\$ doesn't depend in \$b\$ and so is just a function of \$a\$, say \$ a * b=A\$. Then, the anti-commutativity rule \$a * (b+c) = -(a*b + a*c) \$ gives \$A = - (A+A)\$ so \$A=0\$, and thus any product is \$0\$. \$\endgroup\$
    – xnor
    Commented Jun 16, 2021 at 9:01

String Blockify™ a Hexagon

an obvious rip-off of Hexagonify™ a String Block

What is Hexagonification?

Hexagonification is a transformation that creates a hexagon with 3 copies of a rectangle block™, each skewed to the right by 30 degrees and then rotated by 0, 120 and 240 degrees respectively, as shown in the following image. A triangle hole may appear in the middle, but that isn't a great deal.

diagram of hexagonification


Write a program or function that receives a hexagonified block of string™ as an input and outputs the original string block™. diagram of string blockification The input and output formats are flexible. You may receive a single string, a list of lines or a 2D array as input, and output a single string or a list of lines. You may have leading/trailing spaces on each line and leading/trailing newlines, provided that the block is properly formed. See Sample IO for how the blocks™ should be positioned.

Sample IO


   3 x 3
  e s q u
 u r a r e
3 q a a s 3
 x s r q x
  3 e u 3




   l o n g e r . . . . .
  . r e c t a n g u l a r
 r . b l o c k . . . . . .
. a .                 b r l
 . l .               l e o
  . u .             o c n
   . g .           c t g
    . n k         k a e
     r a c       . n r
      e t o     . g .
       g c l   . u .
        n e b . l .
         o r . a .
          l . r .




        v b
       8 e l
      x l r o
     2 a   t c
    k c     i k
   c i       c 2 
  o t         a x
 l r           l 8
b e l a c i t r e v
 v 8 x 2 k c o l b  




 1 . l i n e
e           1
 n         .
  i       l
   l     i
    .   n
     1 e




     e .
    n   l
   i     i
  l       n
 .         e
1 e n i l . 1




Your score will be the area of the source code as a String Block™. Assuming your code can just fit inside a rectangle of width \$w\$ and height \$h\$, the score will be:

$$w \cdot h$$

Winning Criteria

The submission with the lowest score in each language wins.

  • \$\begingroup\$ The obvious problem here is that the reverse challenge is "cluttered" with the information being available three times. The solutions won't profit from the structure being a full hexagon, one of the three skewed rectangles is enough. \$\endgroup\$ Commented Dec 22, 2019 at 16:47

Joyous Kwanzaa!

Kwanzaa is an annual week-long celebration of African culture and history, and takes place on December 26 to January 1. During Kwanzaa it is traditional to light the seven candles of a kinara, one on each day. The middle candle is lit first, followed by the rest of the candles from left to right.


Your challenge will be to write a program or function that when given ASCII art (in any convenient format) of candles on a kinara (as specified below), some of which may be lit, will return or output a ASCII art of what the kinara would look like on the next day.


A kinara will contain of seven even columns of equal length with equal spacing between them, representing the candles. The candles will be constructed with some consistent printable, non-whitespace ASCII character.

Some of the candles might have a flame above them, which will be represented by a single printable, non-whitespace ASCII character, possibly the same as the candle's character. If no candles are lit, there will be an empty line above the candles.

Here is an example of a kinara ASCII art:

*     *
| | | | | | |
| | | | | | |


The input will be a kinara with seven candles, 0-6 of them lit according to the rule (middle candle first, then the rest from left to right).

The output will be a kinara with candles and flames identical to the input kinara, but with one more lit candle than the input. The extra candle will be lit according to the rule. If no candles are lit in the input, you may use any character for the flame.

You may assume the input is valid according to the specification given. You may assume the input has no trailing or leading whitespace in any of the lines, but trailing or leading whitespace is acceptable in the output as long as the kinara has the proper shape.



*     *
| | | | | | |
| | | | | | |

* *   *
| | | | | | |
| | | | | | |


** *



5 5 5 5
6 6 6 6 6 6 6
6 6 6 6 6 6 6

5 5 5 5 5
6 6 6 6 6 6 6
6 6 6 6 6 6 6


               # pretend this is an empty line
q q q q q q q

q q q q q q q


  • No standard loopholes

  • Shortest code in bytes wins


  • Is this too complicated? If so how could I simplify it?

  • Is the wording unclear?

  • Is this too similar to an existing challenge? I found another challenge which involves creating a menorah, but this one takes candles as input instead of a date.


Hit the most Balloons with one Arrow

You got 1 arrow to hit as much balloons as possible. A common way to solve this, is to mark the tangent points of every balloon and project the angles on the source's position. As seen in the following image this has been down already. The task is now to find the optimal and angle-centered solution to hit the most Balloons.


The Input:

A json array of length 360 (for every 1° one entry) representating the number of Balloons hit at this angle.

JSON: https://pastebin.com/raw/Rd8g7Z6J

The Task:

Find an algorithm that solves the task with the following requirements:

  • return the number of most hits
  • return the max range of angles with the most hits
  • return the the centered angle of this range
  • there are no format restrictions how you are returning the values, it could be 3 prints or an array... whatever, as long as it is clear to see whats the hits, range and center

Solution of given JSON:

  • Most Hits: 6
  • Range: 358 - 0
  • Center: 359


Remember its a circle, so you need to check if the range crosses the 360°/0° mark!!! A range can be like 300° - 10° for example.

For simplicity the angles are 0° - 359° as 360° would be 0°.

  • 3
    \$\begingroup\$ That's a lot of words and a picture wasted because your challenge is really just "Find the longest max-value sequence in the array", which is probably a duplicate. I think the challenge would be a lot better if you actually had to calculate this angle distribution from an input of balloon coordinates and a size. \$\endgroup\$ Commented Dec 23, 2019 at 6:29

Bunda-Gerth parser for abstract APL-family language


APL has four kinds of tokens: arrays, functions, monadic operators (mops) and dyadic operators (dops).1) Let's denote them A (arrays), F (functions), M (mops), and D (dops) respectively. Usually when programming in APL, we use a mental model like this:

  • Strand notation: A A ... A -> A
  • Monadic function application: F A -> A
  • Dyadic function application: A F A -> A
  • Mop with left operand: (A|F) M -> F
  • Dop with both operands: (A|F) D (A|F) -> F
  • Mops and dops bind first from left to right (producing functions), and then function applications are evaluated from right to left

But J.D.Bunda and J.A.Gerth proposed another way to parse APL expressions. In this method, each (ordered) pair of tokens is assigned a binding strength and a resulting token. Below is the translation of the above mental model. Note that some token pairs do not bind at all, and we have a new token type AF, which stands for a function with bound left argument.

Binding strength | Token pair(s) -> result
               5 | A A -> A        # Strand notation
               4 | D (A|F) -> M    # Dop + Right operand -> Mop
               3 | (A|F) M -> F    # Left operand + Mop  -> Function
               2 | A F -> AF       # Array + Function    -> Left-bound function
               1 | (F|AF) A -> A   # Function + Array    -> Array

Then the actual parsing proceeds as follows: given a stream of tokens,

  1. Evaluate the binding strengths between adjacent tokens.
  2. Select the token pair whose binding strength is the rightmost local "peak", i.e. the x y pair in w x y z satisfying wx < xy >= yz. w and/or z can be empty. Note that the leftmost pair is bound first in A A ... A.
  3. Group the pair and produce a new token as specified in the transition table.
  4. Repeat from 1 until single token is left (successful parse) or no more reduction is possible (syntax error).


Given a list of tokens, output the order of binding (refer to the I/O section for specification) using the transition table and algorithm described above.

Input and output

The input is a non-empty list of A/F/M/D tokens. You may use any number or single character to represent a token. You may assume that the input will always parse successfully, and the input won't contain any parentheses (since it isn't specified in the table above).

For the output, the order of binding represents in which order each gap between the tokens is closed:

Given the tokens:       A A F M A
Assign each gap an ID:   w x y z
Binding strength:        5 2 3 0
Rightmost local peak:       F M
Bind them first:        A A (F M) A     -> y = 1
Bind A-A next:         (A A) (F M) A    -> w = 2
Bind A-F next:        ((A A) (F M)) A   -> x = 3
Bind AF-A last:      (((A A) (F M)) A)  -> z = 4

Given the tokens:       A A F M A
The order of binding:    2 3 1 4  (the answer)

Note that, if the input contains L tokens, the answer is always a permutation of 1..L-1 (or 0..L-2 if you choose zero-based numbering).

Scoring and winning criterion

Standard rules apply. The shortest code in bytes wins.

Test cases

Input:  A A A A A
Output:  1 2 3 4
Input:  A F F A A F F A
Output:  6 7 5 2 3 4 1
Input:  A  F D A A  M  A A D F M F A
Output:  11 9 8 7 10 12 3 4 2 5 6 1


  1. An actual implementation of APL has some special tokens, e.g. dot ., jot , and index notation [x]. We ignore them here for simplicity.
  • \$\begingroup\$ Maybe an easy answer format is simply inserting the order of binding? A F F A A F F A((A F) (F (((A A) F) (F A))))((A5F)7(F6(((A1A)2F)4(F3A)))) and maybe even returning the permutation vector 5 7 6 1 2 4 3? \$\endgroup\$
    – Adám
    Commented Dec 17, 2019 at 8:42
  • \$\begingroup\$ @Adám That could work, but I don't think it's any easier to produce than a fully structured output. Also, alternative algorithms can produce the same tree with different binding order. \$\endgroup\$
    – Bubbler
    Commented Dec 17, 2019 at 23:27
  • \$\begingroup\$ It will be really hard to verify with the broad output allowance. Maybe just require fully parenthesising? \$\endgroup\$
    – Adám
    Commented Dec 17, 2019 at 23:55
  • \$\begingroup\$ @Adám IMO it's not a problem, as long as the answers specify which output format they're using. \$\endgroup\$
    – Bubbler
    Commented Dec 18, 2019 at 0:16
  • \$\begingroup\$ On second thought, I decided to emphasize the algorithm itself (over the resulting parse tree). \$\endgroup\$
    – Bubbler
    Commented Dec 26, 2019 at 2:04

Potentially Prime Punch-Card Patterns


Let us define a punch-card to be a set of 'open' and 'closed' holes which can slide over the positive integer number line:

   |   ___     ___     ___   | -->
   |  |   |   |   |   |   |  |
1  |  | 3 |   | 5 |   | 7 |  |  9   10  11  12  13  14
   |  |___|   |___|   |___|  |
   |_________________________| -->

When the first open hole is on the integer \$ p \$, then this punchcard (as it slides across the number line) yields the integers \$p, p+2,\$ and \$p+4\$. So, we can represent this card as the set \$\{0, 2, 4\}\$.


Given a punch-card we may wonder whether it is possible to slide the card to such a position that only prime numbers are under the 'open' holes.

Clearly, for \$\{0, 2, 4\}\$, we can position the punch-card to make 3, 5, and 7 visible. However, this is the only solution. Taking each element modulo 3 yields \$\{0, 2, 1\}\$, which contains every possible remainder under division by 3, so one visible integer must be divisible by 3. But we only want primes, and so 3 itself must be visible; this leaves a finite number of possible positions, of which only one is a valid solution.

More generally, if there exists a prime \$q\$ such that every integer \$0 \le n < q\$ appears in the punch-card set modulo \$q\$, then the punch-card is inadmissible and has a finite number of positions where all visible integers are prime: as we are bounded by the condition that \$q\$ must be visible. We can place \$q\$ in each hole in turn, and perform primality tests to count the valid solutions.

However, if there exists no such \$q\$, then the punch-card is admissible and we cannot assume there are finite solutions; the K-Tuple Conjecture in fact hypothesizes that every admissible punch-card can assume infinitely many positions where all visible integers are prime.

The Challenge

Your task is to write a program or function which, given a list of ordered positive integers representing a punch-card set, outputs the number of positions the punch-card can assume where all visible integers are prime. If the set is admissible, then give a distinct output such as -1, null, Inf - anything that is not a non-negative integer.

Test Cases

Coming soon.


There is a related challenge - testing for admissible sequences. However, I believe this is distinct enough to be a duplicate as rather than being a simple , if a set is admissible this program will have to then try different positions of the punch-card and count the valid solutions; whereas the previous challenge considers admissible sets in isolation, this challenge applies it to prime numbers.

  • \$\begingroup\$ Given that the admissibility test is already a challenge, how about you split off the two-challenge and special case part: The input can be assumed to be an admissible sequence, the task is simply finding the positions resulting in valid solutions. \$\endgroup\$ Commented Dec 28, 2019 at 5:54
  • \$\begingroup\$ @AlienAtSystem i just feel as though that it is much less interesting to golf, and returning the distinct different output would open more interesting golfing opportunities. \$\endgroup\$
    – FlipTack
    Commented Dec 28, 2019 at 6:09
  • \$\begingroup\$ Handling special cases is very rarely interesting to golf, for a quite simple reason: Checking if the special case is present requires bytes. Being told the simple case is the case saves those bytes. \$\endgroup\$ Commented Dec 29, 2019 at 20:29
  • \$\begingroup\$ @AlienAtSystem but for there to be more golfing opportunities, don't there have to be more bytes to golf? \$\endgroup\$
    – FlipTack
    Commented Dec 29, 2019 at 20:37
  • \$\begingroup\$ Not really. The issue is that for multiple task challenges, the byte count is 90% of the time optimal_bytes(task1)+optimal_bytes(task2). Often, one of the tasks is considerably longer to golf, to the point where optimizing the other task is almost irrelevant because it's so small compared to the other. Therefore, the site consensus is to split challenges into their individual components as much as possible, and especially avoid input validation, because it's boring and requires lots of bytes. \$\endgroup\$ Commented Jan 1, 2020 at 8:29
  • \$\begingroup\$ But it's not input validation in the sense of there being erroneous or invalid inputs: it's just that the answer to the question "how many prime positions does this have?" may be 0,1,2..., and also (probably) infinity. \$\endgroup\$
    – FlipTack
    Commented Jan 1, 2020 at 11:04

How many ways can I count on n?

By using addition of natural numbers {1, 2, 3...} and multiplication of natural numbers larger than 1, we can reach the same outcome in several ways. For example 4 = 2 x 2 but also: 4 = 2 + 1 + 1. Using normal mathematical operator precedence, there are actually 6 ways to express 4 and 9 ways to express 5.

Since addition is commutative, a + b is counted as the same solution as b + a. The same holds for multiplication. So 7 = 1 + 2 x 3 is the same solution as 7 = 3 x 2 + 1.

The (trivial) solution n (using no addition or multiplication) is also counted as one of the solutions of n.

Multiplication with 1 is forbidden, because you can do this infinitely.


For a given input n, output c(n), which is defined as the number of ways n can be uniquely expressed using zero, one or more additions and multiplications of natural numbers, using normal mathematical operator precedence and without multiplication with 1.


  • Input and output are integers (your program should at least support input and output in the range of 1 up to 32767)
  • Invalid input (0, floats, strings, negative values, etc.) may lead to unpredictable output, errors or (un)defined behaviour.
  • Default I/O rules apply.
  • Default loopholes are forbidden.
  • This is , so the shortest answers in bytes wins

Final note

I can think of several ways to approach this problem. I think it's interesting to see how the different approaches impact the length of the solution.

Sandbox questions

  • Please let me know if this task/problem is stated clear enough.
  • Please let me know if there are any loopholes that I should cover in the question.
  • I intentionally omitted more examples (because I hope contesters will think about solutions rather than just reproduce an OEIS sequence; although I'm not sure if this question had an OEIS sequence).
  • I will tag this question with .

Morse with Binary

For every input string (in ASCII, containing only lowercase alphabetic characters), output the alphabetic string converted from Morse code to Binary code.

In this case we are assuming that . is 0 and - is 1.

How to do the conversion

For reference, here are a few Morse code libraries:

a .-
b -...
c -.-.
d -..
e .
f ..-.
g --.
h ....
i ..
j .---
k -.-
l .-..
m --
n -.
o ---
p .--.
q --.-
r .-.
s ...
t -
u ..-
v ...-
w .--
x -..-
y -.--
z --..

What's amazing about those codes is that the code length never exceeds 4 codes.

And now we are trying to cofuse binary with Morse code. First let's convert sample to morse code:

... .- -- .--. .-.. .

And consider the whole thing as a binary:

.... ---. --.. -...

Here is an alternative table for mapping the characters:

a ....
b ...-
c ..-.
d ..--
e .-..
f .-.-
g .--.
h .---
i -...
j -..-
k -.-.
l -.--
m --..
n --.-
o ---.
p ----

The result of this operation, after conversion, is aomi. You are never going to end up with a letter past p.

  • 1
    \$\begingroup\$ What if there is a group of characters remaining? Input: e, Output: ? \$\endgroup\$
    – Element118
    Commented Jan 1, 2020 at 5:23

Quine Generator Generator... of any* length!

A Quine Generator Generator... is a quine when the input is empty or 0. Otherwise, for any other sufficiently large positive integer input, it should print a Quine Generator Generator... of that specified length (in the same language, same options).

Let S be the (most likely theoretically infinite) set of Quine Generator Generator... you can generate from your initial Quine Generator Generator....

Your score is the smallest N such that any Quine Generator Generator... in S can generate a Quine Generator Generator... of length N or longer (for reasonably sized N).

Input can be from standard input or as an argument of a function.

Lowest score wins.

Sandbox Meta:

Typically, code is scored by bytes, but now the length would depend on how that is interpreted, since it is included in the description of the question. Hence would it be a problem to put: "You may choose to define characters in terms of bytes or characters (should they differ) for purposes of the program length and scoring purposes."


Integer Keys and Duplicates

Given a list/vector of positive integers, write a function to check the following conditions in as few bytes as possible.

  1. Take the first integer (the key, or k1) and check that the next k1 values have no duplicate values, excluding k1.
  2. Take the last integer (the second key, or k2) and check that the k2 values before k2 have no duplicate values, excluding k2.

Note that both keys, k1 and k2, are elements of the list/vector as either key could contain the other.

Also, k1 and/or k2 can be greater than the number of integers within the list, which means you should check every element of the list besides the given key for duplicates, excluding the key.

If both steps return True, return True, else, return False.

Test Cases

[5,1,2,5,3,4,3] is TRUE because [k1=5][1,2,5,3,4] has no duplicates, nor does [5,3,4] have any duplicates, excluding 3

[6,9,12,15,18,19,8,8,3] is FALSE because [k1=6][9,12,15,18,19,8] has no duplicates while [19,8,8][k2=3] has a duplicate.

[100,100,100,100,101,102,3] is TRUE because [k1=100][100,100,100,101,102,3] has no duplicates, and [100,101,102][k2=3] has no duplicates.

[100,100,100,100,101,102,4] is FALSE. [k1=100][100,100,100,101,102,4] has no duplicates, but [100,100,101,102][k2=4] has duplicates.

[6,6,6,6,6,6,6,3,3,3,3] is TRUE. [k1=6][6,6,6,6,6,6] has no duplicates and [3,3,3][k2=3] has no duplicates.

[1,2] is TRUE (clearly)

[1] is TRUE (clearly)

[] the empty list is also TRUE (if you can make a valid argument why it should be FALSE then I might give it to you)

Drum fill generator

Create a program that generates a drum fill. Your program will output a pattern of L (left hand hits), 'R' (right hand hits), and K for kick drum hits.


  • The pattern must never have more than 2 of the same hits consecutively.
  • The pattern must be loopable, so it mustn't have more than 2 of the same hits when it loops.
  • Your program accepts 1 argument which is the length of the pattern. You can assume this will always be an integer > 0.
  • Program output must be random each time it's ran.
  • IO can be used with any convenient method.
  • Standard loopholes are forbidden.
  • This is code-golf, so smallest program wins!

Example valid output:


Example invalid output:

LRLL // 3 characters when looped
LRLRRRLLR // 3 characters in a row
RRLRLLRR // 4 characters when looped
  • \$\begingroup\$ What's a paradiddle? You should include a description in your question \$\endgroup\$
    – Jo King Mod
    Commented Jan 4, 2020 at 5:18
  • \$\begingroup\$ How's that? I added more detail on what the rules/patterns are. \$\endgroup\$
    – TMH
    Commented Jan 4, 2020 at 21:18
  • 1
    \$\begingroup\$ No it must be random each time the program is ran, I'll add that to the rules now, thanks :). \$\endgroup\$
    – TMH
    Commented Jan 5, 2020 at 21:16

Interpret LCGFuck™


LCGFuck™ is a Brainfuck-like esoteric programming language invented by me. Inspired by Brainfuck and linear congruential generators (LCGs), LCGFuck™ combined both things into one.

An LCG in LCGFuck™ is defined with 5 integers, namely multiplier a, adder b, modulus c, offset d and seed e. Let x be its current state, then the corresponding output will be x + d, and the next internal state x' of the LCG can be calculated by x' = (a * x + b) mod c. All numbers should be non-negative except for d. Moreover, b and e should be in the range [0, c).

Technical details

An LCG is defined with 5 numbers, like 12345 678 90 -123 45. The last two numbers are optional and default to 0.

LCGFuck™ has 3 storage variables, the LCG list, the number list and the number memory. The functions are as follows:

  • LCG list: Cyclic list that stores all LCGs created. Every entry is in turn a list of 5 numbers in the order [a, b, c, d, e] as notated in the introduction. It has a pointer that controls which LCG is chosen at the moment, and moves in a cycle through the list.
  • Number list: Ordinary list that stores the numbers for LCG definition. It can store at most 5 numbers.
  • Number memory: A single variable that can be read and written with an input or an LCG output.

LCGFuck™ has 14 operators, namely:

  • \n (newline): Creates an LCG with the numbers in the order of [a, b, c(, d(, e))] and clears the list if the number list contains 3 or more numbers. No-op if the number list contains no more than 2 numbers.
  • <: Shifts to the previous LCG circularly (back to the last when moving from the first).
  • >: Shifts to the next LCG circularly (back to the first when moving from the last).
  • +: Moves the current LCG to the next state (calculates x' = (a * x + b) mod c)
  • c: Prints the output of the current LCG as a character (with the output as the codepoint).
  • n: Prints the output of the current LCG as a number (with a trailing space)
  • o: Writes the output of the current LCG to number memory
  • i: Reads a value from the input and writes it to number memory. There is two input mode, one reading a character one time, and one reading a number one time. You do not need to implement this operator in this challenge.
  • s: Reads the value from number memory and seeds the current LCG with it
  • m: Reads the value from number memory and pushes it to the number list
  • []: Output loop. Executes the loop if the current LCG is non-zero
  • {}: State loop. Executes the loop if the state of the current LCG is non-zero

An integer, optionally with a negative sign at the front, pushes the number to the number list. Any characters other than the newline \n and any of -0123456789[]{}<>+cimnos are no-ops.

The code runs linearly from the first characters, except when loop ends are encountered. Loops can be nested but must be paired accordingly from the innermost loop to the outermost loop.


Write an interpreter, making it as short as possible, that interprets the LCGFuck source code given as the input. You need not implement the i operator in this challenge. The output should be printed to STDOUT or returned in case of writing a function.

You may assume that your interpreter always receives valid programs, i.e.:

  1. An LCG is always defined before any of the commands that manipulate the LCG or the LCG list pointer
  2. At any moment the number list contains at most 5 numbers
  3. All brackets are paired accordingly

Standard loopholes are forbidden by default.

Sample implementation with operator i (Primality check)


The LCG list need not be printed out. It is just for illustration purpose.

  1. The "Hello world!" program in LCGFuck™ is as follows:

    1 29 30 72
    1 3 9 108
    1 1 2 32
    1 8 9 m
    • Output: Hello world!

    • LCG list after execution:

      [1, 29, 30, 72, 28]
      [1, 3, 9, 108, 0]
      [1, 1, 2, 32, 1] < Current LCG
      [1, 8, 9, 111, 8]
  2. An example that outputs the values of x - 16, where x is the states of the LCG x' = (19x + 17) mod 32, starting with seed x = 4, until the output is 0:

    19 17 32 -16 4
    • Output: -12 13 8 9 -4 5 -16 1 4 -3 -8 -7 12 -11 0

    • LCG list after execution:

      [19, 17, 32, 16, -16] < Current LCG
  3. An example that outputs all possible values of 5(x + 12), where x is the states of the LCG x' = (5x + 3) mod 8:

    5 3 8 12
    5 0 99
    • Output: 60 75 70 85 80 95 90 65

    • LCG list after execution:

      [5, 3, 8, 12, 0] < Current LCG
      [5, 0, 99, 0, 65] 
  4. An example illustrating the 3-number restriction of \n (the 9 in the 3rd line is pushed to the number list but the LCG is defined before the 9 is pushed):

    12 34
    56 78
    • Output: 78

    • LCG list after execution:

      [12, 34, 56, 78, 0] < Current LCG
  5. An example that determines whether 97 is a prime:

    1 -1 97 0 -1
    {o+1 1 m 0 97
    1 1 1 32
    1 4 12 69 4
    1 1 7 78 2
    • Output: PRIME

    • LCG list after execution:

      [1, -1, 97, 0, 0]
      [1, 1, 96, 0, 1]
      [1, 1, 95, 0, 2]
      [1, 1, 94, 0, 3]
      [1, 1, 93, 0, 4]
      [1, 1, 92, 0, 5]
      [1, 1, 91, 0, 6]
      [1, 1, 90, 0, 7]
      [1, 1, 89, 0, 8]
      [1, 1, 88, 0, 9]
      [1, 1, 87, 0, 10]
      [1, 1, 86, 0, 11]
      [1, 1, 85, 0, 12]
      [1, 1, 84, 0, 13]
      [1, 1, 83, 0, 14]
      [1, 1, 82, 0, 15]
      [1, 1, 81, 0, 16]
      [1, 1, 80, 0, 17]
      [1, 1, 79, 0, 18]
      [1, 1, 78, 0, 19]
      [1, 1, 77, 0, 20]
      [1, 1, 76, 0, 21]
      [1, 1, 75, 0, 22]
      [1, 1, 74, 0, 23]
      [1, 1, 73, 0, 24]
      [1, 1, 72, 0, 25]
      [1, 1, 71, 0, 26]
      [1, 1, 70, 0, 27]
      [1, 1, 69, 0, 28]
      [1, 1, 68, 0, 29]
      [1, 1, 67, 0, 30]
      [1, 1, 66, 0, 31]
      [1, 1, 65, 0, 32]
      [1, 1, 64, 0, 33]
      [1, 1, 63, 0, 34]
      [1, 1, 62, 0, 35]
      [1, 1, 61, 0, 36]
      [1, 1, 60, 0, 37]
      [1, 1, 59, 0, 38]
      [1, 1, 58, 0, 39]
      [1, 1, 57, 0, 40]
      [1, 1, 56, 0, 41]
      [1, 1, 55, 0, 42]
      [1, 1, 54, 0, 43]
      [1, 1, 53, 0, 44]
      [1, 1, 52, 0, 45]
      [1, 1, 51, 0, 46]
      [1, 1, 50, 0, 47]
      [1, 1, 49, 0, 48]
      [1, 1, 48, 0, 1]
      [1, 1, 47, 0, 3]
      [1, 1, 46, 0, 5]
      [1, 1, 45, 0, 7]
      [1, 1, 44, 0, 9]
      [1, 1, 43, 0, 11]
      [1, 1, 42, 0, 13]
      [1, 1, 41, 0, 15]
      [1, 1, 40, 0, 17]
      [1, 1, 39, 0, 19]
      [1, 1, 38, 0, 21]
      [1, 1, 37, 0, 23]
      [1, 1, 36, 0, 25]
      [1, 1, 35, 0, 27]
      [1, 1, 34, 0, 29]
      [1, 1, 33, 0, 31]
      [1, 1, 32, 0, 1]
      [1, 1, 31, 0, 4]
      [1, 1, 30, 0, 7]
      [1, 1, 29, 0, 10]
      [1, 1, 28, 0, 13]
      [1, 1, 27, 0, 16]
      [1, 1, 26, 0, 19]
      [1, 1, 25, 0, 22]
      [1, 1, 24, 0, 1]
      [1, 1, 23, 0, 5]
      [1, 1, 22, 0, 9]
      [1, 1, 21, 0, 13]
      [1, 1, 20, 0, 17]
      [1, 1, 19, 0, 2]
      [1, 1, 18, 0, 7]
      [1, 1, 17, 0, 12]
      [1, 1, 16, 0, 1]
      [1, 1, 15, 0, 7]
      [1, 1, 14, 0, 13]
      [1, 1, 13, 0, 6]
      [1, 1, 12, 0, 1]
      [1, 1, 11, 0, 9]
      [1, 1, 10, 0, 7]
      [1, 1, 9, 0, 7]
      [1, 1, 8, 0, 1]
      [1, 1, 7, 0, 6]
      [1, 1, 6, 0, 1]
      [1, 1, 5, 0, 2]
      [1, 1, 4, 0, 1]
      [1, 1, 3, 0, 1]
      [1, 1, 2, 0, 1]
      [1, 1, 1, 0, 0]
      [1, 1, 1, 32, 0]
      [1, 4, 12, 69, 0] < Current LCG
      [1, 1, 7, 78, 4]

Winning criteria

Since this is a code-golf challenge, the shortest solution for every language wins.


I'm stepping down

You are given 4 positive integers: volume of the first container (v1), volume of the second container (v2), volume of the liquid in the first container (l1), and volume of the liquid in the second container (l2). Your task is to move (or "step down", if appropriate) some of the liquid from container 1 to container 2, making the amount of empty space in the containers equal to each other, outputting how much liquid should be moved.

An example

Here is an example of some possible input (formatted for the ease of test cases. The input isn't formatted.):

8 11
6  5

Here, you need to make sure that the differences between the volumes and the containers are equal. Currently the difference is not equal:

  8 11
- 6  5
   6 2

So we need to try to make them equal, by taking some of the values in one container to another container:

  8 11
- 4  7
  4  4

After you have succeeded, output how much liquid you need to take from container 1 to container 2. Therefore the above example should output 2.

Test cases

15 16
 9  2

We move into this state:

 15 16
- 5  6
 10 10

Therefore 4 is the expected result.

Test case #2

16 12
13  1

We move into this state:

 16 12
- 9  5
  7  7

Therefore 4 is the expected output.

Test case #3

20 12
10 2


 20 12
-10 2
 10 10

Therefore 0 is the expected output.


  • The test cases will be made so that the result is always possible as a positive integer. The result will never be a decimal.
  • Input can be taken in any convenient and reasonable format.
  • Output can be given in any convenient and reasonable format.
  • The input string will be made so that a moving is always possible without involving decimals or negative numbers. Also there will not be more liquid than how much a container can hold.
  • Of course, this is , so the answer in each language consisting of the fewest number of bytes wins. Happy golfing!
  • An extra restriction for the test cases: you can assume that there is always going to be space available in the second container. So a test case like this:
10 2
 2 2

is not going to be a valid testcase.

  • \$\begingroup\$ So, it just calculate abs(v1-l1-v2+l2)/2? It seems trivial to me. And what should I do if the calculate result is not an integer? \$\endgroup\$
    – tsh
    Commented Jan 13, 2020 at 6:03
  • \$\begingroup\$ May I assume the solution always exits? What should I do if input is v1=10,l1=2,v2=2,l2=2? \$\endgroup\$
    – tsh
    Commented Jan 13, 2020 at 9:17
  • \$\begingroup\$ The test cases will not contain calculations that yield decimal results; also you can assume that there is always enough empty space in the second container to move the liquid. \$\endgroup\$
    – user85052
    Commented Jan 13, 2020 at 13:26
  • \$\begingroup\$ I find the challenge title confusing. Please change it. \$\endgroup\$
    – Beefster
    Commented Jan 20, 2020 at 17:40
  • \$\begingroup\$ @Beefster The challenge is already posted, and after at least 35 people agreed with you, someone else changed the title. @ a'_': please edit this Sandbox post so it only contains the title and link to the posted challenge and delete it from the Sandbox please (as mentioned in bold in the "What is the Sandbox?" post at the top). \$\endgroup\$ Commented Jan 22, 2020 at 10:49

He. Might. Go. All. The. Way. Touchdown!



In American Football, a team has to drive up the field to their opponent's end-zone to score points. But here's the catch, they have 4 tries (called downs) to go at least 10 yards to gain a new set of downs. They repeat this until they score a Touchdown, or until they fail to get 10 yards and (at least in this challenge) punt it away or go for a Field Goal.

Your task is to simulate such a drive.


You are to output the state of each down, i.e. which down it is, how far to the next down (or the end-zone), and where the ball is. Football location counts up from a team's end-zone (0yd line) up to the 50yd line (the middle), then back down to 0 for the opponent's end-zone.

We differentiate the sides of the field by prefixing the location with the team's name. In this challenge, you can use a 1 character label or use positive and negative values. It must go 0-49,50,49-0 and have a way to differentiate between the sides. Your choice on who owns the 50yd line.

Sample Output: (Our team is A, the opponent's team is B)

1st & 7 on A 13
2nd & 10 on A 48
3rd & 12 on 50 OR 3rd & 12 on A 50 OR 3rd & 12 on B 50
4th & 8 on B 10
2nd & Goal on B 7 (read ahead)

Your team will start on your own 1 yard line on 1st & 10 (1st down, 10 yards to go for another first down). You will then gain a uniformly random number of yards between [-3,10] called N. If you didn't get enough for a 1st down, it will now be 2nd & (10 - N). Repeat drawing another number between [-3,10] and adding the yardage for 2nd and 3rd downs if it's still not enough for a 1st down. If you do gain enough for a 1st down, you simply go back to 1st & 10 on the next go and continue going down the field.

On 4th Down, your team is playing safe and will either punt or go for a Field Goal. If you are further away than their 40, output P. If you're within 40 yards, you will attempt a Field Goal with 100 - Yards Away% chance of success. If you succeed, output FG. If you miss, output NG ("No Good"). Afterwards, terminate.

However, there are two special situations that must be handled.

If you get within 10yd (inclusive) and gain a 1st Down, It will then be 1st & Goal and there are no more opportunities to gain 1st downs. Do or die! If you score, output TD and terminate, otherwise you'll follow the normal Field goal rules.

If you lose enough yards to go into your own end-zone, that's called a Safety. Simply output a S and terminate.


  • No usable input will be provided
  • Output is flexible. Tuples and lists of lists are all fine.

Sample Runs:

Tags: Code-golf, random, game

Feedback? Does the Field goal add enough meat to be worth including?


What order(s) can I fire my tonics in?

Helsing's Fire is a classic mobile game about light. You fire blasts of holy retribution (from chemicals called tonics), using cover to selectively hit enemies in the right sequence.

For this challenge, we're going to ignore the line-of-sight stuff and focus on just the tonic order. Each monster is represented by a string like RBBGB—this indicates that, in order to kill it, you need to hit it with a red tonic, followed by 2 blue tonics, then one green tonic and finally one more blue tonic.

Since you're allowed to ignore cover and pick any subset of the monsters to hit, any of the following sequences will kill it:


Your goal is to take in a list of monsters as well as how many of each tonic you have, and output every possible ordering of tonics that kills every monster, including ones where not every tonic is fired. For instance:

R; 2 red -> R, RR
R; 1 red/1 blue -> R, RB, BR
No monsters, but tonics -> every possible permutation of the tonics listed
No tonics, but monsters -> no output, empty set output, or single trailing separator
Neither tonics nor monsters -> empty string
RB,BR; 2 red/2 blue -> RBR, BRB, BRBR, RBBR, RBRB, BRRB

Would there be a duplicate for this?


Fun with Lasers and Prisms (WIP)

Given a rectangular grid of objects, one or more laser pointers, and a target, determine if any laser beam will hit the target.


ASCII will be used for illustration purposes

  • Laser Pointer: ^, V, <, > - a beam will shoot up, down, left, right, respectively, starting from this cell.
  • Target: O - return true if a beam reaches this cell
  • Mirror: /, \ - reflects a beam 90 degrees
  • Prism: # - the laser will split into three beams, one for each direction
  • One-way block: A, U, (, ) - a beam will pass up, down, left, right, respectively, but not other directions
  • Corridor block: =, " - a beam will only pass horizontally or vertically, respectively
  • Gate block: I, H - a beam will pass through horizontally if another beam touches it vertically, or vice-versa, respectively


  • Use any convenient representation
  • \$\begingroup\$ I think it is likely that your gate blocks prevent this from being a dupe of other similar challenges, though I haven't thoroughly checked yet. \$\endgroup\$ Commented Jan 18, 2020 at 3:19

How low can you go?

Time to play so ascii-art limbo!

Here's the bar:

|  |
|  |

Can you fit under it?


Write a program or function that takes an ascii string representing a some shape, and a positive integer representing a bar height.

Output the shape from the input after it has attempted to do the limbo.


In limbo you lean back to make yourself as small as possible to fit under the bar, and that is just what the input shapes will try and do.

If the input shape contains any repeating patterns in its lines, then you can remove all but the last of the repetitions that are in the pattern. In additions the pattern must start at the top line, and once the repeating pattern is broken no more sections can be removed.

If there is a repeating pattern that contains another repeating pattern, only the innermost pattern is stripped.

For example this is how the following inputs would look after "Leaning back":

1. XXX              2. xxx            3. xxx           4. xxx      
   YYY                 xxx       xxx     xxx              xxx      xxx
   XXX   -->   XXX     yyy  -->  yyy     xxx  -->         yyy      yyy
   YYY         YYY     zzz       zzz     xxx              yyy      yyy
   zzz         zzz     aaa       aaa     xxx      xxx     xxx  --> xxx
                                                          xxx      xxx
                                                          yyy      yyy
                                                          yyy      yyy

Note how in example number 4 there was a repetition ox xxx insinde of another repetition of xxx, xxx, yyy, yyy. In this case only the inner repeating lines got reduced.

The bars will be drawn as shown below for the given heights:

1 -> |--|    2 -> |--|   3 -> |--|  etc...
                  |  |        |  |
                              |  |

If the given input shape in its reduced form does not fit underneath the bar then the bar will be drawn on the ground like this |__|



a. height: 3      b.  height: 2     c.  height: 1
   shape: xxx         shape: xxx        shape: (emptystring)
          xxx                xxx
          xxx                xxx
          yyy                yyy


a. |--|           b. |  | xxx       c. |--| 
   |  | xxx          |__| yyy  
   |  | yyy


  1. You can assume only valid inputs will be given, handle invalid input however you want
  2. The input shape will be drawn 1 space after the bar, and the bottom of the input shape will always line up with the bottom of the bar.
  3. Extra whitespace after is fine as long as all the lines are properly aligned.
  4. If there is whitespace in the given input then that should be included in the output
  5. The shape will not necessarily always line up in a perfect rectangle as I drew it.

This is for code-golf so the answer using the fewest bytes wins.

Please let me know what you think / if anything is unclear and needs to be improved. Hope you guys like it!

EDIT: Would whoever down voted please explain whats wrong with it?

  • \$\begingroup\$ I'm not the voter, but I'd bet they voted because what you have right now is very difficult to understand. I had to read this three times to figure out what you wanted. It may be worth revisiting the concept of "leaning over" as it is deeply unintuitive to me at the moment. On top of that, this requires a lot of "boring" golfing for the required output format when true/false seems to be basically the same. I hope this is helpful! \$\endgroup\$ Commented Jan 20, 2020 at 20:24
  • \$\begingroup\$ @FryAmTheEggman Hmm, I thought I'd explained it fairly clearly - its just removing any lines that form a repetitive pattern, but I will try to update it. The output is slightly more than just T/F because of wanting to see the "limbo'ed" input shape with the shaved lines, and having to draw the bar different if it fails... though maybe that is what you meant by boring golf? \$\endgroup\$
    – Quinn
    Commented Jan 20, 2020 at 20:30
  • \$\begingroup\$ @FryAmTheEggman I tried updating the explanation, though I'm not sure if it is any clearer, please let me know if it makes more sense now \$\endgroup\$
    – Quinn
    Commented Jan 20, 2020 at 20:33
  • \$\begingroup\$ Explaining things is often harder than one would guess. Here I think a big problem is that your definition of bending is not what I would expect, so it makes the whole idea harder to grasp - particularly the rules about which repetitions happen first. Since I don't get the why I struggle to get the what. Maybe try explaining this to someone verbally to see if you can get rapid and direct feedback. What you have now is better, but I still think I'd have a hard time following on a first read. \$\endgroup\$ Commented Jan 20, 2020 at 20:35

Factorise a floating point number

Given a target floating point number, \$T\$ and a set of \$N\$ floating point numbers \$\{x_{1},..,x_{N}\}\$ and a permissible error \$tol\$ , find a set of integer coefficients \$A\$, \$\{m_{1},..,m_{N}\}\$ such that: $$ A\prod\limits_{i=1}^{N}x_{i}^{m_{i}} = T\pm{}tol $$


Input will be a target number, a set of real numbers and a tolerance as a decimal or percentage (note which) in any order or format required by your language.


Output should be \$A\$, \$\{m\}\$ and the corresponding error as a percentage. If multiple combinations are valid any or all sets of \$A\$ and \$\{m\}\$ are within tolerance.

General rules

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



15857.6 [3.2, 7.1] 0.05 => 3, [4, 2]


145.85 [2.7182, 3.1415] 0.1 => 2, [2, 2]


0.3 [3.14159, 0.1] 0.05 => 3, [0, 1]

The periodic table and the chemical symbols

Periodic table

The periodic table is a large tablecitation needed where we can find the chemical elements written out with their chemical symbols. For example, Helium shows up as He and Carbon shows up as C. You can read Wikipedia's article on the periodic table, if you want.

Your task

You have to write a function/program/procedure/... that, given a chemical element's name, returns its chemical symbol. For the purposes of this challenge, we will use the 118 elements listed below:

['Hydrogen', 'Helium', 'Lithium', 'Beryllium', 'Boron', 'Carbon', 'Nitrogen', 'Oxygen', 'Fluorine', 'Neon', 'Sodium', 'Magnesium', 'Aluminium', 'Silicon', 'Phosphorus', 'Sulfur', 'Chlorine', 'Argon', 'Potassium', 'Calcium', 'Scandium', 'Titanium', 'Vanadium', 'Chromium', 'Manganese', 'Iron', 'Cobalt', 'Nickel', 'Copper', 'Zinc', 'Gallium', 'Germanium', 'Arsenic', 'Selenium', 'Bromine', 'Krypton', 'Rubidium', 'Strontium', 'Yttrium', 'Zirconium', 'Niobium', 'Molybdenum', 'Technetium', 'Ruthenium', 'Rhodium', 'Palladium', 'Silver', 'Cadmium', 'Indium', 'Tin', 'Antimony', 'Tellurium', 'Iodine', 'Xenon', 'Cesium', 'Barium', 'Lanthanum', 'Cerium', 'Praseodymium', 'Neodymium', 'Promethium', 'Samarium', 'Europium', 'Gadolinium', 'Terbium', 'Dysprosium', 'Holmium', 'Erbium', 'Thulium', 'Ytterbium', 'Lutetium', 'Hafnium', 'Tantalum', 'Tungsten', 'Rhenium', 'Osmium', 'Iridium', 'Platinum', 'Gold', 'Mercury', 'Thallium', 'Lead', 'Bismuth', 'Polonium', 'Astatine', 'Radon', 'Francium', 'Radium', 'Actinium', 'Thorium', 'Protactinium', 'Uranium', 'Neptunium', 'Plutonium', 'Americium', 'Curium', 'Berkelium', 'Californium', 'Einsteinium', 'Fermium', 'Mendelevium', 'Nobelium', 'Lawrencium', 'Rutherfordium', 'Dubnium', 'Seaborgium', 'Bohrium', 'Hassium', 'Meitnerium', 'Darmstadtium', 'Roentgenium', 'Copernicium', 'Nihonium', 'Flerovium', 'Moscovium', 'Livermorium', 'Tennessine', 'Oganesson']

with the respective element symbols:

['H', 'He', 'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne', 'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe', 'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se', 'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo', 'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn', 'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce', 'Pr', 'Nd', 'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy', 'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'Hf', 'Ta', 'W', 'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb', 'Bi', 'Po', 'At', 'Rn', 'Fr', 'Ra', 'Ac', 'Th', 'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk', 'Cf', 'Es', 'Fm', 'Md', 'No', 'Lr', 'Rf', 'Db', 'Sg', 'Bh', 'Hs', 'Mt', 'Ds', 'Rg', 'Cn', 'Nh', 'Fl', 'Mc', 'Lv', 'Ts', 'Og']


The code you write should receive an element name in any sensible format, such as a string "helium". You may assume whatever capitalization that suits your needs.


The code you write should return the element's symbol as a string, with any capitalization that suits your needs. Bonus imaginary internet points if you return the symbol with the standard capitalization.


This is so your answer doesn't win by being the shortest! You will be provided 118 test cases. Your score will be your code's byte count divided by the percentage of test cases your code passes correctly. Lowest score wins!

E.g. my code has 1 byte and I get 1 test case correct. My score is \$1 / \frac{1}{118} = 118 \$. Someone else writes some code with 110 bytes but gets all the test cases correct. The other person scores \$ 110 / \frac{118}{118} = 110 \$, meaning the other person has a better score than me.

Test cases:

'Hydrogen' -> 'H'
'Helium' -> 'He'
'Lithium' -> 'Li'
'Beryllium' -> 'Be'
'Boron' -> 'B'
'Carbon' -> 'C'
'Nitrogen' -> 'N'
'Oxygen' -> 'O'
'Fluorine' -> 'F'
'Neon' -> 'Ne'
'Sodium' -> 'Na'
'Magnesium' -> 'Mg'
'Aluminium' -> 'Al'
'Silicon' -> 'Si'
'Phosphorus' -> 'P'
'Sulfur' -> 'S'
'Chlorine' -> 'Cl'
'Argon' -> 'Ar'
'Potassium' -> 'K'
'Calcium' -> 'Ca'
'Scandium' -> 'Sc'
'Titanium' -> 'Ti'
'Vanadium' -> 'V'
'Chromium' -> 'Cr'
'Manganese' -> 'Mn'
'Iron' -> 'Fe'
'Cobalt' -> 'Co'
'Nickel' -> 'Ni'
'Copper' -> 'Cu'
'Zinc' -> 'Zn'
'Gallium' -> 'Ga'
'Germanium' -> 'Ge'
'Arsenic' -> 'As'
'Selenium' -> 'Se'
'Bromine' -> 'Br'
'Krypton' -> 'Kr'
'Rubidium' -> 'Rb'
'Strontium' -> 'Sr'
'Yttrium' -> 'Y'
'Zirconium' -> 'Zr'
'Niobium' -> 'Nb'
'Molybdenum' -> 'Mo'
'Technetium' -> 'Tc'
'Ruthenium' -> 'Ru'
'Rhodium' -> 'Rh'
'Palladium' -> 'Pd'
'Silver' -> 'Ag'
'Cadmium' -> 'Cd'
'Indium' -> 'In'
'Tin' -> 'Sn'
'Antimony' -> 'Sb'
'Tellurium' -> 'Te'
'Iodine' -> 'I'
'Xenon' -> 'Xe'
'Cesium' -> 'Cs'
'Barium' -> 'Ba'
'Lanthanum' -> 'La'
'Cerium' -> 'Ce'
'Praseodymium' -> 'Pr'
'Neodymium' -> 'Nd'
'Promethium' -> 'Pm'
'Samarium' -> 'Sm'
'Europium' -> 'Eu'
'Gadolinium' -> 'Gd'
'Terbium' -> 'Tb'
'Dysprosium' -> 'Dy'
'Holmium' -> 'Ho'
'Erbium' -> 'Er'
'Thulium' -> 'Tm'
'Ytterbium' -> 'Yb'
'Lutetium' -> 'Lu'
'Hafnium' -> 'Hf'
'Tantalum' -> 'Ta'
'Tungsten' -> 'W'
'Rhenium' -> 'Re'
'Osmium' -> 'Os'
'Iridium' -> 'Ir'
'Platinum' -> 'Pt'
'Gold' -> 'Au'
'Mercury' -> 'Hg'
'Thallium' -> 'Tl'
'Lead' -> 'Pb'
'Bismuth' -> 'Bi'
'Polonium' -> 'Po'
'Astatine' -> 'At'
'Radon' -> 'Rn'
'Francium' -> 'Fr'
'Radium' -> 'Ra'
'Actinium' -> 'Ac'
'Thorium' -> 'Th'
'Protactinium' -> 'Pa'
'Uranium' -> 'U'
'Neptunium' -> 'Np'
'Plutonium' -> 'Pu'
'Americium' -> 'Am'
'Curium' -> 'Cm'
'Berkelium' -> 'Bk'
'Californium' -> 'Cf'
'Einsteinium' -> 'Es'
'Fermium' -> 'Fm'
'Mendelevium' -> 'Md'
'Nobelium' -> 'No'
'Lawrencium' -> 'Lr'
'Rutherfordium' -> 'Rf'
'Dubnium' -> 'Db'
'Seaborgium' -> 'Sg'
'Bohrium' -> 'Bh'
'Hassium' -> 'Hs'
'Meitnerium' -> 'Mt'
'Darmstadtium' -> 'Ds'
'Roentgenium' -> 'Rg'
'Copernicium' -> 'Cn'
'Nihonium' -> 'Nh'
'Flerovium' -> 'Fl'
'Moscovium' -> 'Mc'
'Livermorium' -> 'Lv'
'Tennessine' -> 'Ts'
'Oganesson' -> 'Og'

I used this code to shape the list into the test cases, might be useful to you.

Elements and symbols extracted from https://www.thoughtco.com/element-list-names-atomic-numbers-606529, visited at the 9th of February of 2020. At the time of writing, 118 elements were available. Source included "Aluminum" and "Aluminium" as alternatives, dropped "Aluminum" for the purposes of this challenge.

  • \$\begingroup\$ This is just a massive lookup table. I don't like it. \$\endgroup\$
    – S.S. Anne
    Commented Feb 10, 2020 at 0:50
  • \$\begingroup\$ "Aluminum" might be in the dictionaries of some languages. I suggest allowing either but and/or both in the solution and specifying which one was chosen. \$\endgroup\$
    – S.S. Anne
    Commented Feb 10, 2020 at 1:07
  • \$\begingroup\$ Dupe \$\endgroup\$
    – Jo King Mod
    Commented Feb 10, 2020 at 2:55
  • \$\begingroup\$ @JoKing this being a code challenge doesn't make it different from the dupe you linked? \$\endgroup\$
    – RGS
    Commented Feb 10, 2020 at 7:02
  • \$\begingroup\$ I think the problem you have is that your scoring strongly incentivises submitting H as the best answer. The other question had a shortest solution of 200 bytes - which can't get a better score than the 1 byte 1 answer program. \$\endgroup\$ Commented Feb 10, 2020 at 19:52
  • \$\begingroup\$ @FryAmTheEggman thanks for the feedback. Would you suggest tweaking the score or dropping this challenge? \$\endgroup\$
    – RGS
    Commented Feb 10, 2020 at 20:19
  • 2
    \$\begingroup\$ You might consider a similar idea but with something that hasn't been done as much. I think it depends on how you feel, it certainly isn't unsalvageable. \$\endgroup\$ Commented Feb 10, 2020 at 20:27
  • 1
    \$\begingroup\$ @FryAmTheEggman very nice idea. I am thinking airport codes, country codes or military rank abbreviations... \$\endgroup\$
    – RGS
    Commented Feb 10, 2020 at 21:21
  • \$\begingroup\$ I really like this idea, and I think allowing approximate answers makes it distinct enough from this that it's not a dupe. However, the current scoring encourages very inaccurate, trivial answers. The best I could find in 05AB1E is (05AB1E to output the first 2 characters of the input), which gets 45 test cases correct, scoring better than a 6 character answer that gets everything right. \$\endgroup\$
    – Grimmy
    Commented Feb 14, 2020 at 16:03
  • \$\begingroup\$ @Grimmy thanks for your very detailed feedback! Like I mentioned above, I'm exploring the possibility of using something other than chemical symbols. In your opinion, would you tweak the scoring or would you suggest something other than chemical symbols? \$\endgroup\$
    – RGS
    Commented Feb 14, 2020 at 16:20
121 122
124 125

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .