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

4702 Answers 4702

128 129
131 132

Write a fast-growing assembly function


Your goal is to implement the (asymptotically) fastest growing function within bounded code on a fictional CPU utilizing a quite limited, yet (probably) turing-complete instruction set.


The CPU utilizes unbounded RAM as well as two registers, the accumulator A and the program counter C, with words consisting of arbitrary integers, such that neither overflows nor underflows are possible. RAM is used to store data as well as code, allowing for self-modifying programs. Each instruction takes one parameter and therefore consists of two words; all instructions of your program are stored sequentially in RAM, starting at address 0. The following instructions can be used, P representing the parameter of the instruction:

Mnemonic Corresponding word Behavior
LOAD P 0 A := RAM[P]; C += 2
SAVE P 1 RAM[P] := A; C += 2
CNST P 2 A := P; C += 2
ADDT P 3 A += RAM[P]; C += 2
NEGA P 4 A := -RAM[P]; C += 2
JUMP P 5 C := P
JMPN P 6 If A <= 0 then C := P else C += 2.
HALT P every other number The program halts.

At each step, the instruction at address C will be executed using the parameter stored at C + 1. Both A and C will be initialized to 0 at the start of a program's execution. The word at -1 is supposed to be your input which can be guaranteed to be non-negative, other words not storing any instructions initially contain 0. The number stored at -2 will be considered your program's output, which must also be positive in all but finitely many cases.


At the initial state, your program may not occupy more than the first 2048 words, however, during execution, there are no bounds. Of course, you don't have to write your program in bytecode, using some assembly equivalent or ultimately any other language is fine as well, as long as you provide some rules/translator and show the result does not exceed the given bounds.

Every answer should come with some rough argument showing the program always halts, as well as some approximate lower bound on its growth rate. As the given space might very well suffice for some extremely fast-growing functions, it might be helpful to utilize the slow-/fast-growing hierarchy, as it provides a relatively simple way to compare two answers. Answers will be ranked by lower bounds that can be shown to hold.


I wonder what tags could be used in this case, atomic-code-golf, restricted-source and busy-beaver perhaps? Not entirely sure whether these fit. Also, is there any behavior left undefined? It doesn't seem like that's the case, but there might be some edge cases I forgot about.

  • \$\begingroup\$ 2048 words should be enough to run every possible program \$\endgroup\$
    – l4m2
    Commented Apr 23, 2021 at 10:35
  • \$\begingroup\$ @l4m2 what do you mean by that? you surely can't just take the first <input> programs and run them, otherwise you'd have to solve the halting problem \$\endgroup\$
    – univalence
    Commented Apr 23, 2021 at 12:01
  • \$\begingroup\$ I mean there's, in any measure, way to make it better, in the 2048, and we don't want a "who say bigger number" game \$\endgroup\$
    – l4m2
    Commented Apr 23, 2021 at 15:39
  • \$\begingroup\$ @l4m2 Ah, so you'd reduce the maximum size, correct? \$\endgroup\$
    – univalence
    Commented Apr 23, 2021 at 16:13
  • \$\begingroup\$ no, reducing to turing incomplete likely make it too weak \$\endgroup\$
    – l4m2
    Commented Apr 23, 2021 at 16:44
  • \$\begingroup\$ @l4m2 not the RAM size, the allowed code length \$\endgroup\$
    – univalence
    Commented Apr 23, 2021 at 16:57
  • \$\begingroup\$ since this has been posted, it suggest shortening to one line and deleting to save sandbox space. \$\endgroup\$
    – Razetime
    Commented Apr 30, 2021 at 2:51

May the wind be always at your back

  • 1
    \$\begingroup\$ Challenge is well-written with good test cases. My only critique is that as a puzzle, it's just "is there a path from A to B in this directed graph?" But to get the directed graph you have to parse a bunch of ascii (well, unless you are very flexible with input), which is a "turn this ascii into a directed graph" challenge. The former challenge would likely be a duplicate. The latter is somewhat interesting, but perhaps a bit mechanical. I find it helpful to look at challenges from this "what is the heart of this problem?" perspective. \$\endgroup\$
    – Jonah
    Commented Apr 25, 2021 at 0:48
  • 1
    \$\begingroup\$ Note: The above isn't to say you shouldn't post the challenge -- it's definitely postable quality. Just giving you some feedback. \$\endgroup\$
    – Jonah
    Commented Apr 25, 2021 at 0:50
  • \$\begingroup\$ Thanks for the feedback, though I'm not sure how to improve this (the only thing I can think of is to make the challenge be "list all of the possible paths"). Do you have any suggestions? \$\endgroup\$
    – knosmos
    Commented Apr 25, 2021 at 1:13
  • \$\begingroup\$ You could make it "turn this ascii into an adjacency list or matrix," which is more focused, but becomes too technical. My comment is probably more useful for evaluating future ideas rather than as a way to improve this one. \$\endgroup\$
    – Jonah
    Commented Apr 25, 2021 at 1:16
  • \$\begingroup\$ Okay, thank you! \$\endgroup\$
    – knosmos
    Commented Apr 25, 2021 at 1:17
  • \$\begingroup\$ I'd suggest adding in a falsey testcase where the wind deposits you on a patch of calm sea next to Ithica, similar to the west path in the third test case \$\endgroup\$ Commented Apr 25, 2021 at 13:04
  • \$\begingroup\$ Thanks, implemented \$\endgroup\$
    – knosmos
    Commented Apr 25, 2021 at 14:27
  • \$\begingroup\$ I've edited this down to a stub now that it's been posted to save space \$\endgroup\$ Commented Apr 25, 2021 at 17:28

Compute a real root of a cubic polynomial.

You are given a cubic polynomial of the form \$x^3 + a x^2 + b x + c\$ and your task is to compute one real root of this polynomial, or equivalently a solution to the equation \$x^3 + a x^2 + b x + c = 0\$.

Input will be three numbers \$a\$, \$b\$ and \$c\$. These are guaranteed to be real numbers. The inputs may be taken separately or as a list or a vector or whatever else is convenient in your language.

A cubic polynomial always has at least one real root, and can have up to three. It always has three complex roots but the non real ones are of no interest for this challenge. If the polynomial has multiple real roots, outputting any one of them is fine.

Output should be one number. Solutions with three correct decimal places are good enough, more accuracy or exact algebraic expressions are fine too.

This can be solved by using Cardano's formula but this requires handling of complex roots and some messy lengthy algebra. Alternatively one could use some algorithm for a numeric approximation such as Newton's method. If your language has a build-in that works as well as long as you fish out exactly one real root.

Test cases can be easily generated with any online solver for cubic equations such as this one.

This is , so the shortest code in bytes wins.

  • \$\begingroup\$ Welcome to Code Golf, and thank you for using the Sandbox! I've edited the MathJax slightly (we use \$ as delimiters here), and added in a couple more edits to fit the site defaults slightly better. Feel free to revert these if you dislike them. I'd suggest including some test cases in the challenge body as challenges should be self-contained, and linking to the generator for even more. Finally, for tags, I'd suggest [code-golf], [polynomials], [math] and [number-theory] \$\endgroup\$ Commented Apr 26, 2021 at 19:14

Your client asks you to produce an "org chart" of their statically generated Website's navigation paths.

You can use the Google sheets chart feature if you like, as long as the chart looks similar to what the client expects here:

Notice that a child can only have one parent, so you need to calculate the shortest path to the root element (aka "Home").

Your coding challenge is to create the same chart programatically for the static html as well as their Website at https://simple.goserverless.sg/

Example output:

generate-site-structure [index.html | https://simple.goserverless.sg/]
Privacy Policy,About Us
Sustainability statement,About Us
About Us,Home
  • \$\begingroup\$ Welcome to the Sandbox! This currently isn't nearly clear enough, I'd recommend looking at some other graphical-output challenges to see the typical requirements. You also haven't specified an objective winning criterion; the most popular by far is code-golf (shortest code), but there are also some others like fastest-algorithm or test-battery. \$\endgroup\$ Commented Apr 29, 2021 at 2:55
  • \$\begingroup\$ Thanks, I've tried to be clearer by stating what the expected output is to be. Does that make sense? \$\endgroup\$
    – hendry
    Commented Apr 29, 2021 at 6:12
  • \$\begingroup\$ I'm not sure I understand the goal. Are programs supposed to print that exact text, or a graphical representation of it, or take some sort of site as input and make a representation of it? \$\endgroup\$ Commented Apr 29, 2021 at 6:21
  • \$\begingroup\$ The output is the text/csv which can be drawn by Google Sheets as a organizational chart. \$\endgroup\$
    – hendry
    Commented Apr 29, 2021 at 7:38
  • 1
    \$\begingroup\$ That definitely needs to be much clearer in the post. Without much prior knowledge or assumptions, it should be possible to tell exactly what is expected of answers from the challenge text, and also typically with a bit of explanation on how and some test cases. I'd recommend answering a challenge or two, doing that gives you a pretty good idea of what a challenge needs in order to be clear enough to answer. \$\endgroup\$ Commented Apr 29, 2021 at 13:25

[Draft] 2x2 algorithm with half the faces

A fun fact about the 2x2x2 Rubik's cube is that due to the way a 2x2 only has two layers, doing one turn on one face is indistinguishable from doing the same direction turn on the opposite face and then rotating the cube. So algorithms, that is sequences of moves and cube rotations, ignoring the cube's orientation in space, only need to turn the up (U), right (R), and front (F) faces, and don't need to turn the down (D), left (L), and back (B) faces.

A move is represented by a face, one of the letters U, R, F, followed by a direction: clockwise (empty string or space ), counterclockwise (apostrophe '), or 180 degrees (2). A cube rotation is represented as one of x (rotating the entire cube wrt R face), y (rotating the entire cube wrt U face), and z (rotating the entire cube wrt F face).

enter image description here (credit: J Perm)

enter image description here (credit: Ibero Rubik)

From the previous example, U move is equivalent to D y, meaning the result of turning the top face clockwise is indistinguishable from the result of turning the bottom face clockwise and then rotating the entire cube clockwise wrt the top face.

It is possible to rewrite algorithms with cube rotations into algorithms without cube rotations by appropriate substitution of all following face rotations. For example, y F is equivalent to R, and y U is equivalent to U.

Your task is given an input 2x2 algorithm, rewrite it using only U, R, and F moves, and without cube rotations.

I know this notation is probably confusing to people not familiar with it, so let me know how I can clarify the post.


The Smallest Grammar Problem

Here is a write-up for the main site.

Some changes I want to add are:

  1. You can use any language.
  2. You must formally prove the Big-O of the worst case of your algorithm in your answer.
  3. You must formally prove the correctness of your algorithm as well.

As far as running the code, that's up to the viewers of the page who wish to run the algorithm, as I can't reasonably be expected to compile code from so many different languages.

  1. Before I post to main, I will have a solution to the problem which provides correct answers and can check if an output of your algorithm is correct. It will be coded in Python 3.x. But since the question is about fastest algorithm, that shouldn't matter.

  2. Your algorithm only needs to provide one correct smallest grammar to a given input string (there are usually many), and it must be in standard form (see below).

  3. Therefore my Python 3.x code will enumerate all smallest grammars up to standard form.

  4. I will provide an example formal proof of my algorithm, both so that you can see what a formal proof entails and also so that we know that the solutions we're computing are indeed correct.

How does this all sound to you all? Where would you like to see improvements in the write-up? I am okay with rewriting the whole thing :)

The Smallest Grammar Problem (SGP), is defined as:

Given an input string s, compute a smallest CFG g such that L(g) = {s} generates the string and only the string s itself. Grammar size is defined as:

$$ |g| = \sum_{A \in \text{Vars}(g)} |g(A)| $$

Where the grammar is $$g = \{ A \to g(A), B \to g(B), C \to g(C), \dots \}, \\ \text{ and, } |g(A)|$$ simply takes the string length.

So the size of the grammar g is the sum of the lengths of all right hand sides (RHS's) of the production rules making up g.

All literature on this problem talks about approximation algorithms, and not one article demonstrates a decent exact smallest grammar algorithm. That is to say, computing the very thing the article is about in the first place. I would personally like to see what an exact SGP algorithm looks like. How optimal can we make it, and so on...

I have had many ideas on how to solve the problem. Every one of my attempts ended up with inefficient (exponential running time code). The question is can you make a speedy SGP algorithm.

The language of choice for speed of development is of course Python. Though these resulting programs should not be used in a production compressor for large data. Still, an exponential algoritm remains inefficient even if ported to C++.

So, the benchmark will be running time. You are to use standard Python 3.x, and not Cython, etc.

I have included below some relatively bug-free boilerplate utility code that you may wish to use. It handles the methods for enumerating substrings of a grammar and so on.

These are methods I will use in my own answer, which I am currently still designing. My approach will use what I call the "Groupoid of smallest grammars". Groupoids are heavily involved in combinatorial optimization problems at an advanced level, so from that heuristic they seem like the right structure to use. Another way to code this problem is translating it into a linear integer programming problem and representing substring conflicts using summation modulo 2 (or something like that). Though, linear programming problems open another can of worms since a lot of those problems also have hard running times.

To teach you about the problem, let's inspect some examples. Though we cannot prove that the examples are indeed smallest grammars - there are no theorems out there that tell whether a certain grammar is indeed minimal. A proven algorithm however, tells you whether or not your grammar is minimal. You will need to provide a proof of your algorithm in English / math text accompanied by relavent chunks of your algorithm.

Example 1. Take the string s = aaaa. Reduce it with B -> aa to get the CFG g = { A -> BB, B -> aa}$. Measure its size: |g| = 4 which is the same size as s and so therefore no compression happened.

Example 2. Take the string s = aaaaaa. Reduce using either B -> aaa, or C -> aa to get two smallest grammars:

$$ g = \{A \to BB, B \to aaa\} \\ g' = \{A \to CCC, C \to aa\} $$

Those, by experience and inspection, are precisely the full set of smallest grammars of the string of 6 $a$'s.

Example 3. Let s = abababab. Reduce using first B -> bab then C -> ab.

You get:

$$ g = \{A \to aBaB, B \to bab \}, |g| = 7 \\ g' = \{A \to CCCC, C \to ab \}, |g| = 6 \\ $$

So as you can see, a naive greedy algorithm can quite easily make wrong min / max guesses and come up with a resulting grammar that is not optimal.

Define a grammar to be reduced if no substring of length 2 or more occuring within it occurs more than once.

Reduced does not imply smallest and smallest does not imply reduced. However, every smallest grammar can be reduced, without a change to its size. Thus we will call a reduced smallest grammar the standard form of the smallest grammar.


1. Your algorithm must not only solve the SGP (which is to compute at least one smallest grammar), but it must enumerate all smallest grammars, in standard form, of a given input string.
  1. You must provide a formal proof of your algoritm in your answer. I.e. a mathematical argument that it does indeed compute the output describe in rule 1.
3. Python 3.x, no Cython or C++.

The standard form requirement reduces the total number of result smallest grammars that you must list.

Code to get you started:

# pip install bidict

from bidict import bidict
# Any involved grammar in a smallest grammar algorithm will usually have unique RHS's and unique
# variables on the left.  So it's a perfect use case for a bidirectional dictionary.  Using
# one should speed up the code greatly, otherwise we have to loop through dict values or create
# an inverse dictionary on the fly.

class Grammar:
    def __init__(self, s:str):
        Start out with the trivial grammar g = {S -> s}.
        self._alphabet = set(s)
        self._previousVar = 'A'
        A = self.new_variable()
        self._start = A
        self._definition = bidict({ A : s })   # Bidict is useful, we do use the inverse lookup
    def grammar_size(self):
        This is the standard definition of grammar size (cost) used in all literature
        with regards to the smallest grammar problem.  Minimizing this means you've found
        a smallest grammar for the given input string s.
        size = 0
        for A, rhs in self._definition.items():
            size += len(rhs)
        return size
    def __getitem__(self, A):
        Compute one iteration of expansion at a variable only.
        return self._definition[A]
    def fully_expanded_string(self, s=None, memo=None):
        Fully expand the a string passed in.  Could be a variable or a string of mixed
        variables and terminals.  Any string really.  If variables of this grammar
        occur within the string, they are fully expanded to what the grammar defines
        them to be expanded to, recursively.
        if memo is None:
            memo = {}
        if s is None:
            s = self._start
        exp = ''
        for x in self._definition[s]:
            if x in self._definition:
                exp += self.fully_expanded_string(x)
                exp += x
        memo[s] = exp
        return exp        
    def __repr__(self):
        The obvious representation for debugging / showing results.
        rep = ''
        for A, rhs in self._definition.items():
            rep += A + ' ---> ' + rhs + '\n'
        rep = rep[:-1]  # remove last newline
        return rep
    def __str__(self):
        return repr(self)
    def new_variable(self):
        Take the first unicode character that is not already in the grammar's alphabet.
        So it will eventually take weird-appearing characters, but who cares.  I think this
        methodology beats escape or delimit characters.  However, you're also limited to a 
        maximal alphabet size that is the Unicode character set.  That's usually just fine.
        If not, then what on Earth are you compressing ? :)
        X = self._previousVar
        while X in self._alphabet:
            X = chr(ord(X) + 1)            
        self._previousVar = X
        return X
    def greedily_reduce(self):
        A grammar is defined to be reduced if no substring of length >= 2 occurs twice, anywhere
        within the grammar.  There are many paths to a reduced grammar.  The smallest grammar
        problem involves taking the correct reduction path such that the resulting grammar is
        indeed minimal in size.  Greedy algorithms are known not to work in general for producing
        a smallest grammar.  However, they can easily produce a reduced grammar as you can witness.
        A smallest grammar is not necessarily reduced, though there exists a smallest grammar which
        is the reduction of that smallest grammar.  Reducing a smallest grammar would involve
        compressing all substrings of length 2 that occur exactly twice. g = {S -> abab} has the 
        same size as g' = {S -> AA, A -> ab}, namely 4.  Thus reducing a smallest grammar does not
        reduce the size (obviously), but instead puts it into a "standard form", which might be
        useful to your algorithm.
        R = self.repeating_disjoint_substring_indices()                
        while len(R) > 0:
            m = self.arbitrary_greedy_max_function(R)                        
            if m not in self._definition.inv:
                M = self.new_variable()
                M = self._definition.inv[m]
            for A, indices in R[m].items():
                subtract = 0
                for i in indices:
                    rhs = self._definition[A]
                    self._definition[A] = rhs[0:i-subtract] + M + rhs[i+len(m)-subtract:] 
                    subtract += len(m) - 1                         
            self._definition[M] = m
            R = self.repeating_disjoint_substring_indices()
    def arbitrary_greedy_max_function(self, R:dict):
        Seems like a good choice.  The total coverage of a substring if you were to compress it
        into a grammar rule.
        For example:
              If g = {A -> BaBaBaCC, B -> CCC, C -> aaa} then (3 Ba's) * |Ba| = 3 * 2 = 6 is maximal.
        total_indices = lambda rule_indices: sum(len(x) for x in rule_indices.values())
        return max(R.keys(), key=lambda x: len(x) * total_indices(R[x]))        
    def repeating_disjoint_substring_indices(self, min_len=2):
        If there is overlap, this algorithm clearly does a leftmost packing.
        Same as `disjoint_substring_indices()` except we compute only the
        substrings that occur >= 2 times within the same rule or in two
        separate rules.
        Output form:
           'substring1' : {
                 'A': [0, 3, 7],
                 'B': [1, 4, 8],
           'substring2' :  ...
        where 'A' indicates the rule in which the indices occur, and the list is the list
        of indices within the rule RHS string where you'll find the substring occuring.
        The indices returned are such that the substrings occuring at those indices are mutually
        disjoint (they don't overlap).
        return self._repeatingSubstringIndices(min_len, lambda t, indices: indices)
    def repeating_substring_indices_all(self, min_len=2):
        Return all substring indices even if there is overlaps among them.
        Output form:
           'substring1' : {
                 'A': [0, 3, 7],
                 'B': [1, 4, 8],
           'substring2' :  ...
        where 'A' indicates the rule in which the indices occur, and the list is the list
        of indices within the rule RHS string where you'll find the substring occuring.
        This includes all occurences even if two occurences overlap.
        return self._repeatingSubstringIndices(min_len, lambda t, indices: self.all_substring_indices(t))
    def _repeatingSubstringIndices(self, min_len=2, rule_indices_func=None): 
        Output form:
           'substring1' : {
                 'A': [0, 3, 7],
                 'B': [1, 4, 8],
           'substring2' :  ...
        where 'A' indicates the rule in which the indices occur, and the list is the list
        of indices within the rule RHS string where you'll find the substring occuring.  Overlap
        or disjoint is governed by the rule_indices_func passed in.
        S = {}        
        for A, rhs in self._definition.items():
            T = self.disjoint_substring_indices(rhs, min_len)
            for t, indices in T.items():                
                if t not in S:
                    S[t] = { A : indices }
                    S[t][A] = indices
        R = {}        
        for t, rule_indices in S.items():
            if len(rule_indices) >= 2:
                R[t] = rule_indices_func(t, rule_indices)
                for var, indices in rule_indices.items():
                    if len(indices) >= 2:
                        R[t] = rule_indices_func(t, rule_indices)
        return R
    def disjoint_substring_indices(s:str, min_len=2, max_len=None):
        Leftmost-first packed indices of all substrings of the string s.  The substring
        occurences (indexes) are guaranteed to be of disjointly occuring substrings.
        If two occurences overlap, by for-loop logic we're taking the leftmost.  Hence
        "leftmost-first packed".
        Output form:
           'substring1' : {
                 'A': [0, 3, 7],
                 'B': [1, 4, 8],
           'substring2' :  ...
        where 'A' indicates the rule in which the indices occur, and the list is the list
        of indices within the rule RHS string where you'll find the substring occuring.
        The indices are such that the substrings occuring at those indices are disjoint 
        (they don't overlap).
        if max_len is None:
            max_len = int(len(s)/2)   # Maximum length of a repeated substring
        S = {}
        for i in range(0, len(s)-min_len+1):
            for j in range(i+min_len, i+min(max_len, len(s))+1):
                t = s[i:j]
                if t in S:
                    if i >= max(S[t]) + len(t):
                    S[t] = [i]
        return S
    def all_substring_indices(self, t:str):
        The indices of all occurences of the given substring.  Output form:
           'A' : [0, 3, 7],
           'B' : [1, 4, 8],
        where 'A' indicates the rule in which the indices occur, and the list is the list
        of indices within the rule RHS string where you'll find the substring occuring.
        This includes all occurences even if two occurences overlap.
        R = {}        
        for A, rhs in self._definition.items():
            for i in range(0, len(rhs)-len(t)):
                if rhs[i:].startswith(t):
                    if A not in R:
                        R[A] = [i]
        return R
    def include_all_possible_rules(self):
        A possible rule is one such that the length of its RHS is >= 2 and fully
        expanded it occurs at least twice in the input string s.  Including all possible
        rules does not change the fact that the grammar expands to s for some starting
        variable.  In other words we still have a grammar for s, by definition, though
        some of its rules may be unused.
        # So first get all disjointly repeating substrings:
        R = self.repeating_disjoint_substring_indices()
        # To "include all rules" we form a rule for each repeating substring:
        for r in R:
            A = self.new_variable()
            if r not in self._definition.inv:
                self._definition[A] = r
if __name__ == '__main__':
    s = 'aaaaaa'
    g = Grammar(s)
    print('The canonical example on a singleton alphabet.  The smallest example such that the smallest '
          f'grammar is indeed smaller than the input {s}')
    s = 'ababab'
    g = Grammar(s)
    print(f"This is known to indeed be a smallest grammar of {s}, by inspection.")    
    s = 'abcabcabababc'
    g = Grammar(s)
    print(f"Similarly, this too also is probably a smallest grammar for {s}")
    s = 'ababababbaaaaaaaabbbbaa'
    g = Grammar(s)
    s1 = g.fully_expanded_string()
    assert (s1 == s)
    print('A more complicated example demonstrating "including all possible rules" and then greedily reducing '

Which prints:

A ---> BBB
B ---> aa
The canonical example on a singleton alphabet.  The smallest example such that the smallest grammar is indeed smaller than the input aaaaaa
A ---> BBB
B ---> ab
This is known to indeed be a smallest grammar of ababab, by inspection.
A ---> CCBBC
B ---> ab
C ---> Bc
Similarly, this too also is probably a smallest grammar for abcabcabababc
A ---> DDOLLLbbbO
B ---> ab
C ---> aba
D ---> BB
E ---> ba
F ---> bab
G ---> abb
H ---> bb
I ---> bba
J ---> bbL
K ---> baa
L ---> aa
M ---> aaa
N ---> LL
O ---> bL
A more complicated example demonstrating "including all possible rules" and then greedily reducing everything.
  • 2
    \$\begingroup\$ The explanation is kind of long, and I would suggest separating a section that clarifies the task and input-output format. \$\endgroup\$
    – okie
    Commented Apr 30, 2021 at 7:45

Cleaning KoTH

Clean up a 50x75 room with a JSbot before there is too much junk!

The Challenge

A 50x75 room is cluttered 375 items, each taking up 1 cell of space. Create a JSbot that takes an array as an input to clean up the room. If the bot is on a cell with junk in it, the junk is automatically removed.

Each bot will be paired against another bot. One bot will be the "cleaner," the other will be a "disorganizer." The cleaner is exactly what it is. The disorganizer, every turn, has a 10% chance of being able to place a junk where it is.

The disorganizer wins if the amount of junk reaches 400 or more, while the cleaner wins if the amount of junk reaches 0.


  • Preset commands you may use are:

    • left(bot_name) Moves left 1 cell (x-1)
    • right(bot_name) Moves right 1 cell (x+1)
    • up(bot_name) Moves up 1 cell (y+1)
    • down(bot_name) Moves down 1 cell (y-1)
  • Storing data in your bot is allowed!


Here is an example of a bot, and how to format it.

bots.ConfusedBot = { // bots.Foo where Foo is the name of your bot
    x: 0 // 0 is the center
    y: 0 // 0 is the center
    clean: function (array) { // cleaning function
    sabotage: function (array) { // disorganizing funcction

Comments and/or concerns? Comment down below to notify me.

  • \$\begingroup\$ I'd recommend giving this a read. KotHs are one of the hardest types of challenges to get right (if not the hardest). Currently it doesn't look like there's much strategy at all here. \$\endgroup\$ Commented May 3, 2021 at 14:34
  • \$\begingroup\$ @RedwolfPrograms Yep, that's been a problem for all of these. I will edit it to make it more strategic. \$\endgroup\$
    – WarpPrime
    Commented May 3, 2021 at 14:41

Base Guard (Rewritten)

Base: part 1

This is part 2, Strongly suggest you go try out the first one if you haven't tried it.


As one of the solvers, You've managed to get to the door of the base heaven. In front of the door stands the base guard @Lyxal, he was angry that you all just left the encoded text on the ground, he deems you to clean(decode) the ground before joining the party, those who are irresponsible gets no ticket!


You will get 2 inputs

  • First being X which is a non-negative integer in base of base list.
  • Second being base which is a list of bases.
  • bases range from 1 ~ 10
  • The base will contain at least one not 1 base
  • answer should be in the base 10


X, [bases] -> answer
110 ,[2] -> 6
30 ,[2,4] -> 6
2100 ,[2,3] -> 30

You may want to look at part 1 for more detail


Basic Rules

Satisfy Lyxal with the shortest code, because a long code indicates that you are lazy and not doing your best!


  • Is this count as a dup of part 1?
  • Any extra suggestions?
  • Lyxal are you willing to become the guard? Or anyone else would like to be the guard?
  • \$\begingroup\$ You say lowercase alphabet, but your example uses capital F. Also, this would be a duplicate of the first part because handling higher numbers shouldn't require much modification from part 1, and indexing into the base digits is a pretty trivial extra step that doesn't add anything to the challenge anyway. \$\endgroup\$
    – hyper-neutrino Mod
    Commented May 4, 2021 at 5:23
  • \$\begingroup\$ No tickets for anyone unless they impress me. \$\endgroup\$
    – lyxal
    Commented May 4, 2021 at 5:25
  • \$\begingroup\$ @hyper-neutrino Then I will rewrite this challange to somethin more creative. \$\endgroup\$
    – okie
    Commented May 4, 2021 at 6:04
  • \$\begingroup\$ I'm good with guarding \$\endgroup\$
    – lyxal
    Commented May 4, 2021 at 6:46
  • \$\begingroup\$ @Lyxal Excellent \$\endgroup\$
    – okie
    Commented May 4, 2021 at 6:48

Given a subset of {+,*,<,=,E,A,(constant),(variable)}. For most of the subsets, use the symbols to express Riemann hypothesis.

Output format flexible. Most subset, and on tie, smallest (code length+sum symbols used) in each language wins. (So there'll also be a winner in Text)

You can also choose to focus on sum symbols used, and claim that you answered in Custom, counting like a 0-byte solution.


Regex, ASCII-literal


Execute the given regex for the given text. The regex is in a special scheme I made.


For most regexes the usual languages support, they assign some printable ASCII characters for special instructions. For POSIX as an example, * is the Kleene star, . matches an arbitrary character, and ( and ) groups a subexpression. Because of this, If such characters themselves were to be matched, I must escape them by a backslash \. This may cause the regex seem obfuscated. Not to mention that in most languages, backslashes must be escaped themselves like \\.

So instead of printable ASCII characters, I chose ASCII control characters to assign some special instructions.


Two strings indicating the regex and the text. They are assumed to consist of ASCII characters. Otherwise, the entire challenge falls in don't care situation.


A list of pairs of integers. Each pair indicates the starting position and the ending position of each strings matched.

Indexing is implementation-defined, but preferred to be zero-indexed.

Each pair shall be left-inclusive of its indicated string. The right, however, is implementation-defined whether inclusive or exclusive. (Exclusive is preferred)


Here, I shall call a unit of regex a packet.

For all characters within \x20\x7E, it is a minimal packet that matches itself.

For control characters (with some exceptions), however, it has a special functionality. It classifies to one of:

  • A minimal packet.

  • A parenthesis. A pair of parentheses group packets into one packet.

  • A unary operator. They accept one packet, and they all are suffixes. They have higher precedence to all binary operators.

  • A binary operator. They accept two packets, they all are infixes, and they all associate to right.

The regex munches each strings matched. In other words, the matched strings cannot overlap.

If an empty string is matched, it shall be ignored. In other words, all matched strings shall be nonempty.

The regex is case-sensitive by default.


The lines of the text are delimited by \n, \f, \r, and \v.

The words of the text are separated by ASCII whitespaces ( and \t, in addition to the above).

Control characters

  • \x00 (NUL; Null) has an implementation-defined functionality. It's because in some languages, strings are null-terminated.

  • \x01 (SOH; Start of Header): Minimal packet. It matches the start of a line.

  • \x02 (STX; Start of Text): Left parenthesis corresponding to ETX.

  • \x03 (ETX; End of Text): Right parenthesis corresponding to STX. Concatenates the packets inside.

  • \x04 (EOT; End of Transmission): Minimal packet. It matches the end of a line.

  • \x05 (ENQ; Enquiry): Left parenthesis corresponding to ACK or NAK.

  • \x06 (ACK; Acknowledgement): Right parenthesis corresponding to ENQ. It serves as an arbitrary-input OR gate. The first alternative that matches shall be matched.

  • \x07 (BEL; Bell): Unary operator. It "inverts" its operand, like this:

    • If its operand is a minimal packet that matches a single character, it matches a character the packet doesn't match.

    • It commutes with a unary operator.

    • It distributes to a binary operator.

    • It distributes to packets within parentheses.

    • Otherwise, it has no effect.

  • \x08 (BS; Backspace): Minimal packet. It matches an arbitrary ASCII whitespace.

  • \x09 (HT; Horizontal Tab): Minimal packet. It matches \t.

  • \x0A (LF; Line Feed): Minimal packet. It matches \n.

  • \x0B (VT; Vertical Tab): Minimal packet. It matches \v.

  • \x0C (FF; Form Feed): Minimal packet. It matches \f.

  • \x0D (CR; Carriage Return): Minimal packet. It matches \r.

  • \x0E (SO; Shift Out): Minimal packet. It matches an arbitrary lowercase Latin letter.

  • \x0F (SI; Shift In): Minimal packet. It matches an arbitrary uppercase Latin letter.

  • \x10 (DLE; Data Link Escape): Unary operator. Its operand shall be matched case-insensitive.

  • \x11 (DC1; Device Control One): Unary operator. Its operand shall be matched zero or more times. It is greedy.

  • \x12 (DC2; Device Control Two): Unary operator. Its operand shall be matched one or more times. It is greedy.

  • \x13 (DC3; Device Control Three): Unary operator. Its operand shall be matched two or more times. It is greedy.

  • \x14 (DC4; Device Control Four): Unary operator. Its operand shall be matched zero or one time. It is greedy.

  • \x15 (NAK; Negative Acknowledgement): Right parenthesis corresponding to ENQ. It is equivalent to ACK BEL.

  • \x16 (SYN; Synchronous Idle): Binary operator. If and only if the operands match the same string, it shall match the string. Has higher precedence to CAN, and has lower precedence to EM.

  • \x17 (ETB; End of Transmission Block): Minimal packet. Matches either the start of a word or the end of a word.

  • \x18 (CAN; Cancel): Binary operator. Two-packets version of ENQ-ACK. Has the lowest precedence.

  • \x19 (EM; End of Medium): Binary operator. Treats surrounding characters as escaped, and matches a character within the range they indicate, both inclusive. If the left operand has higher ASCII code point than the right operand, the range wraps around the ASCII codepage.

  • \x1A (SUB; Substitute): Minimal packet. Matches an arbitrary character.

  • \x1B (ESC; Escape): As a prefix, this character is used to escape a control character. An escaped ASCII character, including DEL (but not necessarily including NUL), shall match itself.

  • \x1C (FS; File Separator): Minimal packet. Matches a hexadecimal digit, case-insensitive.

  • \x1D (GS; Group Separator): Minimal packet. Matches a decimal digit.

  • \x1E (RS; Record Separator): Minimal packet. Matches an octal digit.

  • \x1F (US; Unit Separator): Minimal packet. Matches a binary digit.

  • \x7F (DEL; Delete): Unless escaped by ESC, this character shall be skipped. It doesn't even count as a packet.


Upon the following conditions, it shall fall in an implementation-defined behavior to indicate an error:

  • Unpaired parenthesis

  • Unary/Binary operator without an operand



Ungolfed solution



Sandbox questions

  • Is this challenge too hard or cumbersome?

  • Do you have better ideas for the functionalities of control characters?

  • \$\begingroup\$ Suggest map to usual RegEx, and explanation for those whthout direct map \$\endgroup\$
    – l4m2
    Commented May 4, 2021 at 11:13

Radio station hopping

You are listening to a car radio. You are pressing seek up/down, moving you to the next frequency some radio station broadcasts on, to avoid all this pointless music and listen to all the ads, or vice versa. But there is a tendency of these broadcasts to have your radio jump to another frequency, where signal of that radio station is stronger. So, suppose this radio station A broadcasts at 99, 100 and 101 MHz with 100 MHz having the strongest signal at your place. The moment you reach 101 MHz, radio will jump to 100 MHz.

Because of that, you can get trapped. Suppose there is one extra radio station B, broadcasting only at 102 MHz. The moment you are stuck at the station A, you can never listen to station B again - if you try going with frequency down, you will hit 99 and jump to 100, if you go up you reach 101 and jump to 100 again... never escaping that trap.

But if there is yet another station C at 99.5 and 98.5 MHz with latter being the strongest, you can listen to all 3 radios again - starting from B you get down to A, then down to C, then pressing down loops you back again to the highest frequency.

So, you start wondering - can I listen to all radio stations at least once if I start at any frequency? And will I be able to endlessly cycle through all of them, or listen to all just once before getting cut off some stations?

Your task:

Get a list of radio stations, along with a designation of which has the strongest signal, in any reasonable format (1). Return one of three values to distinguish whether you can cycle through all stations indefinitely, you can cycle through all stations once or you cannot reach all stations from any starting point. Again in any reasonable format (2).

(1) Test cases have inputs as radio stations separated by semicolon, for each radio station, the strongest broadcast for the station is first, entries separated by comma. You can pick anything else as your input format, along with any reasonable extra information you would like - for example number of radio stations, number of channels each station broadcasts at etc. You can use integers (eg just multiply everything in example by 10).

(2) Test cases have output as 1 - cycle all, 2 - cycle once, 3 - cannot reach all stations. You can return anything reasonable to distinguish these three options, as long as you return/print the value. You must return, eg "you can cycle all" crashing or never stopping is NOT allowed.

Test cases:

input: 102; 100, 99, 101 output: 2

input: 102; 100, 99, 101; 98.5, 99.5 output: 1

input: 100, 99, 101; 103, 102, 104 output: 3

input: 100, 99, 101; 103, 102, 104; 101.5, 99.5, 103.5 output: 1

input: 100, 99; 99.5, 100.5; 102, 103; 102.5, 101.5 output: 3

May the shortest code win.

Tags: code-golf
Any suggestions? (and is this a duplicate maybe, I haven't found it but I don't know what exactly to search for here)


Determine tournament winners

Given a table of names and per round scores, arrange the names in descending order of their Neustadtl Sonneborn–Berger score.


A player's Sonneborn-Berger score(which we will from now on refer to as "tiebreak score"), is the sum of the points they received in each round (\$x_{i}\$), multiplied by the points that each their round opponent achieved totally via standard scoring(\$p_{i}\$), given round count \$n\$.

Effectively, each player's score is: $$ \sum_{i=1}^n p_ix_i. $$

Your challenge is to calculate this score for each player and arrange them in increasing order of ordinary score, and then use the tiebreak score to resolve any ties in points.

From Wikipedia:

here is the crosstable of the 1975–80 World Correspondence Chess Championship Final (here cs indicates conventional score, ns Neustadtl score):

                  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15  cs   ns
1.  Sloth         X ½ ½ 1 ½ ½ 1 1 ½  1  ½  1  1  1  1  11   69.5
2.  Zagorovsky    ½ X 0 ½ 1 ½ 1 1 1  ½  1  1  1  1  1  11   66.75
3.  Kosenkov      ½ 1 X ½ ½ ½ ½ ½ 1  1  ½  1  1  1  1  10½  67.5
4.  Khasin        0 ½ ½ X ½ 1 ½ 0 1  1  ½  1  ½  1  ½  8½   54.75
5.  Kletsel       ½ 0 ½ ½ X ½ ½ ½ ½  0  1  1  ½  1  1  8    47.75
6.  De Carbonnel  ½ ½ ½ 0 ½ X ½ ½ 0  1  ½  ½  0  1  1  7    45.25
7.  Arnlind       0 0 ½ ½ ½ ½ X ½ 1  0  ½  ½  1  1  ½  7    42.5
8.  Dunhaupt      0 0 ½ 1 ½ ½ ½ X 0  ½  1  0  1  ½  1  7    41.5
9.  Maedler       ½ 0 0 0 ½ 1 0 1 X  1  ½  ½  ½  ½  1  7    41.5
10. Estrin        0 ½ 0 0 1 0 1 ½ 0  X  1  1  1  0  1  7    40.5
11. Walther       ½ 0 ½ ½ 0 ½ ½ 0 ½  0  X  0  1  ½  1  5½   33.25
12. Boey          0 0 0 0 0 ½ ½ 1 ½  0  1  X  ½  ½  1  5½   28.5
13. Abramov       0 0 0 ½ ½ 1 0 0 ½  0  0  ½  X  ½  1  4½   24.75
14. Siklos        0 0 0 0 0 0 0 ½ ½  1  ½  ½  ½  X  1  4½   22.75
15. Nun           0 0 0 ½ 0 0 ½ 0 0  0  0  0  0  0  X  1    7.75

As an example, Sloth's score is calculated as: 0.5*11 + 0.5*10.5 + 1.0*8.5 + 0.5*8.0 + 0.5*7.0 + 1.0*7.0 + 1.0*7.0 + 0.5*7.0 + 1.0*7.0 + 0.5*5.5 + 1.0*5.5 + 1.0*4.5 + 1.0*4.5 + 1.0*1.0 = 69.5


Surprisingly, I don't think there has been a question about Whyte notation before. I suspect the ASCII challenge is a bit too easy, but not sure how many people are interested in a graphical challenge. Thoughts? Comments?

Whyte notation

Write a program which turns a string containing a valid (subset of) Whyte notation into an ASCII/graphical representation.

Whyte notation is a system for succinctly describing the arrangement of wheels on a steam locomotive. For the purpose of this challenge, a valid input consists of:

  • one or more wheelsets, joined by a + symbol
  • where each wheelset is of the form l-d1[-d2...]-t, where:
    • l is an integer specifying the number of leading wheels (small wheels at the front of the wheelset that aren't powered, but help keep it on the tracks)
    • d1 (and d2 etc) is the number of driving wheels (large wheels powered by a steam engine) coupled together. If there is more than one number, it means multiple coupled sets of driving wheels. (All the sets are powered by the same engine, but using different sets of cylinders - divided drive)

(Multiple wheelsets means an articulated locomotive, that is, two engines powered by the same boiler, but able to rotate independently, which is good for getting powerful locomotives around tight bends).

For instance:

  • 2-4-0 means a locomotive with 2 leading wheels (1 axle), 4 driving wheels (2 axles), and no trailing wheels. We can represent it like this: o-O=O
  • 4-8-8-2 means a locomotive with 4 leading wheels, two coupled sets of 8 driving wheels, and 2 trailing wheels. We can represent it like this: o-o-O=O=O=O-O=O=O=O-o
  • 2-4-2+2-4-2 means an articulated locomotive with two wheelsets. Each one consists of 2 leading wheels, 4 driving wheels and 2 trailing wheels. We can represent it like this: o-O=O-o:o-O=O-o

A Baldwin 2-4-0 locomotive: 2 leading wheels, 4 driving wheels, no trailing wheels

Image: A Baldwin 2-4-0 locomotive: 2 leading wheels, 4 driving wheels, no trailing wheels.


Input is a string (or equivalent) that is valid in this subset of Whyte notation. You may assume:

  • Leading and trailing wheel counts are even integers in the range 0-6 inclusive.
  • Driving wheel counts are even integers in the range 2-14 inclusive.
  • There are 1-4 coupled sets of driving wheels per wheelset.
  • There are 1-2 wheelsets.

Output (ASCII)

The rules for output are thus:

  • the train is always facing left, so the leading wheels are at the start of the input and output strings.
  • leading and trailing wheels are represented as one o per 2 wheels, joined by -
  • each set of driving wheels are represented as one O per 2 wheels, joined by =.
  • sets of driving wheels are joined by -
  • wheelsets are joined by :

Output (graphical)

Alternatively, you may output a graphical representation of a similar type: a series of circles from left to right. At a minimum:

  • all wheel circles must have a dark stroke and light fill, with the stroke no more than 10% the width of the circle
  • the lowest point of all wheel circles must be equal (they all touch the same imaginary track)
  • all wheel circles of a given type must be the same size
  • leading/trailing wheels must have a diameter in the range 20-50% of the diameter of driving wheels
  • coupled sets of driving wheels must be indicated by a horizontal line connecting their centres*.
    • * you may offset this line up to 40% of a driving wheel diameter in any direction to maintain artistic integrity
  • non-coupled wheels must not be connected, and have a space in the range 25-50% of the diameter of a driving wheel between them.
  • for an articulated locomotive, the two wheelsets must be separated by a space of between 100% and 150% of a driving wheel diameter.


This is code golf, shortest program in bytes wins. Standard rules/loopholes apply. There are two categories: ASCII output and graphical output.

  • \$\begingroup\$ Make it one or the other, otherwise it's too confusing. \$\endgroup\$
    – emanresu A
    Commented May 10, 2021 at 9:41

Is this code golf too simple? Do I need to add more? Has something similar been done before?

The idea of this golf is to convert a string of 3 or more characters to a grammatically correct list.


12345 becomes 1, 2, 3, 4, and 5.

ab5 becomes a, b, and 5.

A comma and space is to be inserted between each character, and the last character should be preceded by "and", and be followed by a period. Your code should be able to handle up to 50 characters in series.

  • \$\begingroup\$ Well, you need to flesh out your challenge a little more. I'd suggest putting the last paragraph at the top and adding more test cases. However, I don't know how interesting this would be. \$\endgroup\$
    – user
    Commented May 10, 2021 at 21:38
  • \$\begingroup\$ May input contains whitespace characters and / or comma? \$\endgroup\$
    – tsh
    Commented May 11, 2021 at 2:32

How Many Students are in our clubs?

You are a principal in CG High School, and you want your school fliers to include data on how many students are part of any particular set of clubs. You command your secretary to get this data, but they goofed up.

Instead of giving you the data on how many students attend (for example) tech club, math club, and spanish club as their only clubs, they included students who attend more clubs, like the arts club! You decide to fix the data yourself.


Your school has n clubs, and for each subset of the n clubs, you have data on how many students attend the clubs in that subset (but potentially more clubs).

In this challenge, you want to output data for each subset which tells you how many students attend exactly those clubs in that subset (and no others).


We represent each subset as an n digit binary number by placing a 1 in the ith position if the ith club is in the subset. For example, the number 3, in binary, is 11, meaning that it represents the subset of the first and second clubs.

The input (zero-indexed) list is of length 2^n, with the secretary's data for a particular subset placed at the index representing that subset (as in the previous paragraph).

The output is also a list of length 2^n, with the data changed.


  • List of length 2^n of non-negative integers
  • (Optional) positive integer n


  • List of length 2^n of non-negative integers

Test Cases

[41,16,15,14,5,5,6,2] -> [10,8,6,5,3,3,4,2]

More to be added


I worded this challenge really poorly: any help on explaining this better?


[Draft] Write out the 2x2 Hamiltonian Circuit

Unlike the 3x3 Rubik's Cube, which famously has over 43 quintillion possible positions, the 2x2 Pocket Cube "only" has about 3.7 million positions, making a Hamiltonian circuit (a set of moves that visits every position exactly once) perfectly feasible to output or store in its entirety.

The full circuit was posted by cuBerBruce in 2011 on the SpeedSolving Forums. You don't need to understand any Rubik's cube notation to complete this challenge. You only need to understand simple string replacements (in the form of a context-free grammar), in that lower case letters are "non-terminal" and can be replaced with longer strings, while upper case letters are "terminal", in that they are "atomic" and cannot be replaced further. For example, given b=URURUR and a=bURUR, you can replace the b in a to get a=URURURURUR, and you cannot expand a any further.

One additional detail: if a letter is followed by an apostrophe, you replace the letter and the apostrophe in the string with the inverse of the moves. That means the the entire string is reversed and the direction of all moves is reversed: U becomes V and vice versa, R <-> S, and F <-> G. More formally, (ab)'=b'a', so for example a'=(bURUR)'=R'U'R'U'b'=SVSV(URURUR)'=SVSVSVSVSV.

Todo: upload full move list and compute hash


  • \$\begingroup\$ Should you maybe allow to choose whatever tokens you want instead of U,V,R,S,F,G, as long as there's only a single valid way to parse it to the tokens? \$\endgroup\$ Commented May 13, 2021 at 9:36
  • \$\begingroup\$ @CommandMaster this question is a kolmogorov-complexity question, about producing a constant string, and I intend all solutions to be able to be verified by hash \$\endgroup\$
    – qwr
    Commented May 13, 2021 at 9:41

Posted here

  • \$\begingroup\$ I think the explanation for how the game works could be a bit clearer. How many cards are dealt each round? How is the trump card chosen? \$\endgroup\$ Commented May 12, 2021 at 21:19
  • \$\begingroup\$ @RedwolfPrograms Fixed. \$\endgroup\$ Commented May 12, 2021 at 21:24

You want to have some drinks. Each bottle of drink has a drink itself and \$n\$ other parts (the bottle, etc.) \$P_1, P_2, ..., P_n\$. Thus when buying a bottle of drink, you also get one of each of \$P_1, P_2, ..., P_n\$.

You can buy a bottle of drink using 1 dollar, \$a_1 P_1\$s, \$a_2 P_2\$s, ..., or \$a_n P_n\$s.

Given the amount of dollars \$b\$ and amount of each part you have \$c_1, c_2, ..., c_n\$[1], how many bottles of drink can you have?

You may choose to borrow some parts, aka. having a negative amount of some parts during the buying and drinking, so long as after the whole process you don'thave negative amount. But beware that simply giving each part a value and use the actual worth of the drink itself may fail. See example (*) below.

Also, you need to handle Infinity results correctly. I'd accept format Infinity, , 1/0, for other formats ask here or on meta for a default.

Test cases:

n, a, b, c => resuly
1, [2], 5, [0] => 10 // Borrow 10 P1, buy 10BoD, and return
1, [2], 0, [10] => 10
2, [3,4], 1, [0,0] => 1 // (*)
2, [3,3], 1, [0,0] => 3 // (**)
2, [2,2], 0, [0,0] => Infinity
2, [1,2], 0, [0,1] => Infinity

(*) If you get 2, you result in 2 \$P_1\$s and 2 \$P_2\$s, neither of which afford one BoD and therefore you can't pay.

However, if you just claim that each \$P_1\$ worth $0.333 and each \$P_2\$ worth $0.250, then the drink itself worth $0.417, and you can drink two of them, which is incorrect.

(**) Even though you can't get 2 as that gives you 2 \$P_1\$s and 2 \$P_2\$s, which is not enough to pay; getting 3 gives you 3 \$P_1\$s and 3 \$P_2\$s, and with the initially $1 you can pay the fee of 3 bottles of drink.

One sentence meaning:

Given \$n, \{a_i\}, b, \{c_i\}, i=1..n\$, find the largest integer \$r\$, maybe infinite, such that \$b+\sum_{i=1}^n\left\lfloor\frac{c_i+r}{a_i}\right\rfloor\ge r\$.

Input range:

  • \$n>0, a_i>0, b, c_i\ge 0\$

Sandbox Notes

  • Should I take c input or just assume it's zero at [1]?
  • \$\begingroup\$ I mostly get the problem statement from the first three paragraphs, but the rest of the challenge sort of loses me. I can piece together a bit from the test cases. If you added a more worked through example perhaps I could help rephrase the parts of the challenge I don't get right now. \$\endgroup\$
    – Wheat Wizard Mod
    Commented May 14, 2021 at 15:24
  • \$\begingroup\$ @WheatWizard Is treating borrowing as having negative amount of parts or pay after drinking better? Also fixed a bug in test cases. And do such question have an English usualseen version? \$\endgroup\$
    – l4m2
    Commented May 14, 2021 at 16:12

Implement the ordering monoid


Mimic Haskell's (<>) :: Ordering -> Ordering -> Ordering.

What's the fuss?

This particular monoid is rather useful for comparing sequential containers lexicographically.


Though Ordering is defined as a three-element enumeration, in this challenge, the format of the 2 inputs and the output is arbitrary.

The 2 inputs and the output must be the same domain, and their classification of their values (see below) also must be the same. This restriction is due to that (<>) is associative.

Any input outside of the domain falls in don't care situation.


The elements of the domain shall be classified to 3 categories: Negative, zero, and positive.

  • If the left operand is negative, output a negative value.

  • If the left operand is zero:

    • If the right operand is negative, output a negative value.

    • If the right operand is zero, output a zero value.

    • If the right operand is positive, output a positive value.

  • If the left operand is positive, output a positive value.


A Python 3 implementation of this operation:

lambda x,y: x if x != 0 else y

This has integers as the domain, and classifies integers by their signature.

  • 2
    \$\begingroup\$ looks like in many languages this will just be an "or" builtin \$\endgroup\$
    – Wezl
    Commented May 14, 2021 at 23:04
  • \$\begingroup\$ I want to say this might be clearer if the spec for the operation just used the names LT, EQ, and GT, but the example domain leads to the unfortunate revelation that your example solution could be simply lambda x,y:x or y... \$\endgroup\$ Commented May 14, 2021 at 23:08
  • \$\begingroup\$ @Wzl How would an "or" operator act? Bitwise "or" is commutative, while (<>) isn't. \$\endgroup\$ Commented May 15, 2021 at 0:26
  • \$\begingroup\$ Python 3: lambda x,y: x or y \$\endgroup\$ Commented May 15, 2021 at 9:25
  • \$\begingroup\$ Finally, I am the outgolfer. \$\endgroup\$ Commented May 15, 2021 at 9:25
  • \$\begingroup\$ Javascript: $=>_=>$||_ \$\endgroup\$
    – Makonede
    Commented May 24, 2021 at 20:19

Generate simultaneous equations

You've been tasked to write maths exam questions, but you're getting quite bored of coming up with simultaneous equations with integer solutions, so you decide to write a program to generate them. Because this is a school test, the questions mustn't be too easy, but they also mustn't be trivial.

The simultaneous equations should be of the form:

$$ ax + by = R $$ $$ cx + dy = S $$

where \$ a \$, \$ b \$, \$ c \$, \$ d \$, \$ R \$, \$ S \$ are integers. The equations must have exactly one set of solutions, the solutions must both be integers, and \$ x \$ must not equal \$ y \$.

The random generation method you choose is completely up to you, as long as there are at least 100 distinct equations that could be generated each with a non-zero probability. If the coefficients or equations are swapped, they count as the same (this is to discourage hard-coding of valid equations).

You may output in any reasonable format, such as a string "-1x-2y=3;4x+5y=6" or a list of 6 integers like [-1, -2, 3, 4, 5, 6]. The format must be consistent for all outputs.


Valid              x   y
-1x-2y=0; 4x+5y=6  4  -2

Invalid              Notes
-1x-2y=7; 4x+5y=6    Non-integer solutions
-1.5x-3y=0; 4x+5y=6  Non-integer coefficients
0x+2y=8; 2x+2y=6     Zero coefficients
3x+4y=1; 6x+8y=2     Infinitely many solutions
3x+4y=1; 6x+8y=3     No solutions

TODO: add more examples



  • Is this a duplicate?
  • Is this clear enough?
  • Any other feedback?
  • \$\begingroup\$ I'm not sure if this is too trivial \$\endgroup\$
    – tsh
    Commented May 17, 2021 at 2:59
  • \$\begingroup\$ @tsh A lot of Kolmogorov questions are therefore even more "trivial". \$\endgroup\$ Commented May 20, 2021 at 12:59


Based square-free words

A square-free word is a word that contains no squares, i.e. contains no adjacent repeating subwords. For example, 0123 is square-free, while 0112 and 012123 are not (because 11 and 1212 are repetitions, respectively).

In base-1 there is only one square-free word: 0. In base-2 there are 6 square-free words: 0, 1, 01, 10, 010, 101. In base-3 and up there are infinitely many.

The challenge

Given a base N and a length L, output a square-free word of length L in base N, or a distinct falsy value (or an error) if no such word exists. Both the base and the length will be positive integers.
Alternatively, you may take an alphabet instead of a base as input, e.g. you may take "ABC" as an input instead of base-3 and give output in that alphabet.

Any reasonable input-output, standard restrictions, code golf.

Test cases

Other similar outputs are also valid.

Base  Length  Output
2     1       0
2     2       01
2     3       010
2     4       Error or a distinct falsy value
3     4       0121
3     5       01210
3     50      01210212012101202102012021201021012010212021020120


Given an real polynomial equation \$c_0+c_1x+c_2x^2+...+c_nx^n=0\$, count how many real roots it has.

You can and need to assume infinite precision. You can assume repeated root doesn't exist.[1]

You can take input [c0,c1,...,cn], [cn,...,c1,c0], or just the polynomial or the equation in your language support.

Test cases:

1=0 => 0
0=0 => Infinity
2+1x=0 => 1
3+4x+1x^2=0 => 2
6+4x+1x^2=0 => 0
0+0x+0x^2+1x^3+0x^4=0 => 1

Sandbox Notes

[1] Is checking repeated root always possible?

  • \$\begingroup\$ This feels like a factorisation code-golf, though the question is still very good \$\endgroup\$ Commented May 18, 2021 at 16:40
  • \$\begingroup\$ @StackMeter But you can't solve some poly eq? \$\endgroup\$
    – l4m2
    Commented May 19, 2021 at 3:20
  • \$\begingroup\$ Do you have a reason to believe it is solvable in finite time? \$\endgroup\$
    – Bubbler
    Commented May 25, 2021 at 1:03
  • \$\begingroup\$ Also, in your last example (x^3=0 in simplified form), 0 is the repeated root. \$\endgroup\$
    – Bubbler
    Commented May 25, 2021 at 1:06

Golf Code Golf

Given the transcript (what I mean by full transcript is you can access all days of the transcript) of The Nineteenth Byte (the general chat room of code golf), output the full transcript in text form (you only have to include messages, though including other things is allowed. You can use any format as long as it includes the poster and contents of each message. As for people changing names, the way you handle this is up to you, do whichever is shortest). You can access the full transcript in your code, but you cannot access any other external sources.

Since this is code golf, shortest answer wins, and standard loopholes are not allowed

  • \$\begingroup\$ Any feedback would be helpful, since this is my first question idea here. \$\endgroup\$ Commented May 18, 2021 at 20:14
  • \$\begingroup\$ By "access the full transcript" what do you mean? There's no single page with the entire transcript, so do you mean all pages that are https://chat.stackexchange.com/transcript/240/<date>? \$\endgroup\$ Commented May 18, 2021 at 20:18
  • \$\begingroup\$ @cairdcoinheringaahing yes that is what I meant, I’ll update it now, thank you. \$\endgroup\$ Commented May 18, 2021 at 20:21
  • \$\begingroup\$ You'll need to be much more specific about what "text form" is. I'm assuming ...people talk... is not correct, but there are a huge amount of formats, such as person: message and <person> message, not even considering stars, multi-line messages, and users changing their usernames \$\endgroup\$
    – Wezl
    Commented May 18, 2021 at 20:29
  • \$\begingroup\$ @Wzl I edited it, is it more clear now or is there something I missed? \$\endgroup\$ Commented May 18, 2021 at 20:48
  • \$\begingroup\$ If people are as lazy as me I think they'll just output the raw HTML, since it complies with your constraints (however I think this is a good thing as answers shouldn't be required to parse HTML) \$\endgroup\$
    – Wezl
    Commented May 18, 2021 at 20:54

JS onelineriser

JavaScript is a very easy language to onelinerise. All one has to do is insert a semicolon in the correct locations and concatenate every line.

Your task is to write a program that, given a valid JS program, returns a program in one line but is otherwise identical to the input.


  • Clarifications?
  • Any edge cases where any operation other than inserting semicolons is required?
  • Should I include basic JS syntax in the question or provide a link?
  • \$\begingroup\$ I think you should ask the programs to minimize the amount of semicolons placed. \$\endgroup\$
    – Razetime
    Commented May 19, 2021 at 2:42
  • 3
    \$\begingroup\$ You definitely need to tell where one needs to insert ;s. \$\endgroup\$
    – Adám
    Commented May 19, 2021 at 2:42
  • \$\begingroup\$ I know where one should place semis but I'm not exactly clear whether those semis are necessary. However, I intended this to be a code-golf and not a code-challenge (shortest source) \$\endgroup\$ Commented May 19, 2021 at 2:59
  • 2
    \$\begingroup\$ Either the input code is guaranteed to conform to a format where some simple rules can be applied (and you'll have to include these rules in the challenge), or this is going to require a full parsing and syntax analysis -- which is probably far too complicated for a code-golf challenge. \$\endgroup\$
    – Arnauld
    Commented May 19, 2021 at 22:14
  • \$\begingroup\$ Can I make the whole input toJson and then feed it to eval? This is valid since ES2019. (And CSP is never a part of ES specification, so that doesn't matter.) \$\endgroup\$
    – tsh
    Commented May 20, 2021 at 2:26
  • \$\begingroup\$ Other than inserting semicolons: remove comments. For example, foo(); // do something<line-break>bar();. And remember to keep line break in comments. For example, ()=>{return//<line-break>42;}. More terrible comments: `${()=>{return // this is a comment in template string. <line-break> }}`. Even even terrible edge case: If hashbang proposal landed... \$\endgroup\$
    – tsh
    Commented May 20, 2021 at 10:35
  • \$\begingroup\$ @tsh tbh comments aren't "code" so to speak, so I might not actually have those test cases. They would be hell to deal with. \$\endgroup\$ Commented May 20, 2021 at 12:46
  • \$\begingroup\$ Can I just warp the code eval? (ok also asked by tsh) \$\endgroup\$
    – l4m2
    Commented Jun 6, 2021 at 5:04

Gabriel's Horn


  • 1
    \$\begingroup\$ 1. I don't think I've seen anything very similar. 2. Wording looks fine to me (mainly because the image helps a lot) 3. I don't have a strong opinion on this. Either way should be fine. 4. Looks correct. 5. Actually the whole challenge is simply "generate a specific arithmetic progression based on the input", which can be seen as not so interesting, and it has very little to do with Gabriel's Horn itself. Maybe a better title would be "Convince me Gabriel's Horn is possible"? \$\endgroup\$
    – Bubbler
    Commented May 18, 2021 at 0:28

Print a BigNum

Your task is to take an arbitrary precision unsigned integer, separated into 7-bit parts (a.k.a. base 128), and output it in base 10.


All arithmetic for conversion (excluding basic indexing) must be done only using values \$-2^{15}\le x \le 2^{15}-1\$, or in simpler terms, the range of a signed 16-bit integer.

So for example, something like this in Python would be illegal because a[i]<<i*7 and sum are capable of making a number larger than \$2^{15}-1\$.

lambda a:str(sum(a[i]<<i*7for i in range(len(a))))

Note that you are not required to explicitly use 16-bit integers or mask every time.

Your algorithm must be able to handle numbers of any length, if the resources are available.

Assume all inputs to be valid and the shortest possible length.


The input is a list of numbers, each 0-127, in big or little endian order. You only need to handle up to 224 bits, or 32 base 128 digits, though.

Any reasonable encoding format is fine, as long as all digits are in base 128 and the length is variable. You could do this: 122 bananas, 0 bananas, 20 bananas, 12 apples, I don't care. ULEB128 is allowed if that is easier.

The output can be either an ASCII string or printed to standard output, all in base 10. These must be ordered in big endian (as if you were to print it).

Test cases

Inputs are in little endian order.

[0] -> 0
[1] -> 1
[127] -> 127
[99] -> 99
[0, 0, 1] -> 16384
[127, 0, 0, 0, 127] -> 34091303039
[21, 26, 111, 58] -> 123456789
[1, 78, 123, 61, 102, 86, 17, 32, 74, 41, 114, 79, 1] -> 31415926535897932384626433
[63, 29, 51, 105, 61, 107, 45, 70, 105, 97, 38, 36, 121, 15, 77, 24, 72, 4, 52, 56, 6, 5, 36, 38, 87, 10, 37, 26, 96, 16, 21, 110] -> 23203475113112158652497114438750306328443726354045579113768791363263
  • 3
    \$\begingroup\$ What does "All calculations must use a maximum of 16 bits" exactly mean? Does it mean I can only use 16 bits RAM (including registers)? \$\endgroup\$
    – tsh
    Commented May 20, 2021 at 7:54
  • \$\begingroup\$ You probably want to limit the absolute value, otherwise someone could calculate -<ans>, convert it to a string, and remove the first character \$\endgroup\$ Commented May 21, 2021 at 7:38
  • \$\begingroup\$ Your algorithm must be able to handle numbers of any length given a large enough buffer. So given a number with >2^15 base-128 digits how to access? \$\endgroup\$
    – l4m2
    Commented May 21, 2021 at 8:46

What is the link to your answer?


Your task is to create a program taking the input that returns the link to your answer. You can find a link to your answer by clicking at the share button on your answer.


  1. Standard loopholes apply except for searching for the answer online. In fact, you are expected to find the answer online.
  2. You are allowed to use curl or the equivalent, but you are not allowed to use any html parser library or built-in. If you need to import the library, the import declaration does NOT count into the code size as long as you don't rename any identifiers.
  3. You are not allowed to assume the link to your answer. You have to search this page for your submission. If you remove your submission and readd it, and your code breaks, you fail the challenge.
  4. You may still assume your username, the contents of your code, and the programming language/byte count you are using. You are not allowed to assume the description below your code. If you edit the description part of the submission and the code breaks, you fail the challenge. You may assume that the code of each submission is unique and no one copies your submission into another answer.


This is so, the shortest answer in bytes wins.

  • 2
    \$\begingroup\$ What prevents me from simply hardcoding my output? \$\endgroup\$ Commented May 20, 2021 at 9:24
  • 1
    \$\begingroup\$ @StackMeter If you delete your answer, and post again the same answer, and it break, it fails the challenge. \$\endgroup\$
    – Xwtek
    Commented May 20, 2021 at 9:42
  • \$\begingroup\$ thanks for the clarification \$\endgroup\$ Commented May 20, 2021 at 9:44
  • \$\begingroup\$ What if my language has built-in for HTML parser (Yes, JavaScript running in browsers , aka. BOM, does have one)? Also, what will happen if I post 2 answers to this question? \$\endgroup\$
    – tsh
    Commented May 20, 2021 at 9:46
  • \$\begingroup\$ Can I assume no one else will contain my code as part of an answer/comment? \$\endgroup\$ Commented May 20, 2021 at 10:12
  • \$\begingroup\$ @CommandMaster Yes \$\endgroup\$
    – Xwtek
    Commented May 20, 2021 at 11:43
  • \$\begingroup\$ @tsh 1. You have to avoid using that built-in, 2. You have to be able to distinguish your submissions. \$\endgroup\$
    – Xwtek
    Commented May 20, 2021 at 11:44
  • \$\begingroup\$ [tag: self-referential] ? \$\endgroup\$ Commented May 21, 2021 at 5:10

Recreate the Stack Overflow logo

  • \$\begingroup\$ note that the last time this was attempted, it got closed \$\endgroup\$
    – Wezl
    Commented May 21, 2021 at 21:54
  • \$\begingroup\$ @Wzl this one is a code-golf question. I don't see why it can be off-topic. \$\endgroup\$ Commented May 21, 2021 at 21:55
  • \$\begingroup\$ @Wzl also, the logo for this one is not the one specified from that question you linked. \$\endgroup\$ Commented May 21, 2021 at 22:42
  • \$\begingroup\$ I've edited this down to a stub now that it's been posted to save space \$\endgroup\$ Commented May 22, 2021 at 23:09

Lowest effort to fill the bucket

There are two man, Paul and Jhon, who can move only along a line; they are real persons so Paul cannot goes to the right of John and Jhon cannot goes to the left of Paul. At time 0 they start at the opposite ends of the line.

Paul |------X1----X2----BUCKET--------X3-----X4-----| Jhon

Their goal is to pickup the balls along the line (denoted as Xn) and fill the bucket in the lowest time. The time needed to go from A to B along the line is equal to the distance from A to B.

For the challenge the balls are 20 and they are located on the line in the following way:

  1. Paul = 0
  2. X1 = 1
  3. X2 = 2
  4. X3 = 3
  5. x4 = X5 = x6 = 5
  6. BUCKET = 8
  7. X7 = 10
  8. X8 = 11
  9. X9 = X10 = X11 = 15
  10. X12 = 20
  11. X13 = X14 = X15 = 22
  12. X16 = X17 = X18 = 28
  13. X19 = 29
  14. X20 = 30
  15. Jhon = 32

Which is the best sequence to reach they goal?


Verify the Perfect Rectangle

According to Wolfram Mathworld, a perfect rectangle is defined to be a rectangle that can be divided into squares of different side lengths.

In this challenge, we are going to verify whether or not an arrangement is a perfect rectangle.

For the input, there should be at least 3n+2 non-negative integers in it:

  • The first two numbers should show the size of the rectangle.
  • Rest of the 3n numbers should describe n squares.
  • Each square should be described with 3 numbers, which are the side length(>0) and the position(x, y).
  • Position should be consistent throughout the whole input. For example, If the program gets the position of the bottom left corner of the square for one time, it should do that every other time as well.

For the output, the program should print a truthy value if the given arrangement is a perfect rectangle, and a falsey value otherwise.

  • Every squares should be different in side length.
  • There should be neither overlaps nor voids.

Test cases(Note that any input and output formats are acceptable if they are reasonable):

-> True #This is the first example in the above link. 

-> True #This is the second example in the above link. 

-> False #There are sqaures of same sizes. 

-> False #There are overlaps and voids. 

This is , which means that codes with least bytes win.

128 129
131 132

You must log in to answer this question.

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