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

4706 Answers 4706

111 112
114 115

I got them Mad Matrix Moves

Given a list of edges representing a simple directed graph and (optionally) the number of vertices n>1, output the adjacency matrix of that graph.

The vertices will always be numbered consecutively starting at 0 (or 1 -- your choice).

The adjacency matrix is defined as the n by n square matrix M such that M[i][j] is 1 if there is an edge from vertex i to vertex j and 0 otherwise.


For this example and the test cases, we will have the vertices numbered starting at 1.

Let's use the sample input [(1,2),(1,3),(3,2)]. Since there are vertices numbered 1-3, n=3 and our output is a 3 x 3 matrix.

The output should be

[[0, 1, 1],    <= (1,1) doesn't exist in the input list, (1,2) does, (1,3) does.
 [0, 0, 0],    <= (2,1) doesn't exist, same with (2,2) and (2,3)
 [0, 1, 0]]    <= (3,1) doesn't exist, (3,2) does, and (3,3) doesn't

(concisely represented as [[0,1,1],[0,0,0],[0,1,0]] in test cases).


  • Every vertex is the start and/or end of at least one edge.
  • You may replace 1 and 0 in the output with any two consistent distinct values of your choosing.
  • The input graph is simple, meaning that it has no loops nor multiple edges (e.g. no edge [1,1] or graph [[1,2],[1,2]])
  • The graph is directed, meaning that each edge has a start and an edge (e.g. the edge [1,2] is distinct from [2,1])
  • Every vertex is an endpoint of at least one edge
  • This is , so shortest code in byes in each language wins.

Test Cases

One test case per line. Each test case is in the format edges, n => output.

[(1,2)], 2 => [[0,1],[0,0]]
[(2,1)], 2 => [[0,0],[1,0]]
[(1,2),(2,1)], 2 => [[0,1],[1,0]]
[(1,2),(1,3),(3,2)], 3 => [[0,1,1],[0,0,0],[0,1,0]]
[(1,2),(2,3),(3,4),(4,5)], 5 => [[0,1,0,0,0],[0,0,1,0,0],[0,0,0,1,0],[0,0,0,0,1],[0,0,0,0,0]]
[(1,2),(3,4),(4,3),(2,1),(2,4),(4,2)], 4 => [[0,1,0,0],[1,0,0,1],[0,0,0,1],[0,1,1,0]]
[(1,2),(2,3),(3,4),(4,5),(2,1),(3,2),(4,3),(5,4)], 5 => [[0,1,0,0,0],[1,0,1,0,0],[0,1,0,1,0],[0,0,1,0,1],[0,0,0,1,0]]
[(1,2),(3,1),(2,3),(1,1),(2,1)], 3 => [[1,1,0],[1,0,1],[1,0,0]]
[(1,2),(3,2),(1,3),(5,4),(5,6),(5,1),(2,3),(1,5),(5,2),(3,6),(4,5),(5,3),(2,1),(3,5),(4,6),(6,3),(6,5),(4,2),(3,4)], 6 => [[0,1,1,0,1,0],[1,0,1,0,0,0],[0,1,0,1,1,1],[0,1,0,0,1,1],[1,1,1,1,0,1],[0,0,1,0,1,0]]

Get the Average Number of Bytes for an Answer

Have you ever wanted to know the average number of bytes all the answers to a given code golf question took? Probably not. But I did!


You'll have to take in a link to a codegolf exchange question by text or you can run this in a browser extension/user-script. If you have a clever way of identifying the webpage and producing the necessary output, just ask about it in the comments, and I'll update the question as long as it doesn't violate the rules. The input will be a link to a codegolf question. It will include http::// or https:://. The slashes will be facing this way: "/". The link may not be to a code-golf challenge specifically, but it could be something like a code-challenge.


If the user inputs something that isn't to a code golf website output something along the lines of "Hey! That's not a link to a code-golf challenge" If the user inputs a link that links to the codegolf exchange, but isn't a codegolf (maybe it's a code-challenge) the program should output anything that is not a natural number.

If there are strikethroughs through previous amounts of bytes a solution took, those should not be included in the average. If the person answering the question in one of the links did not conform to formatting standards, the program doesn't have to account for it. Minor differences will be allowed. Specifically, the number of bytes should be within 5 lines of the top of the answer and bolded.

All answers should be rounded to the nearest whole number with .5 rounding up.






Winning Criterion

The winner will be given by (1 / execution time (s) + bytes).

If you know of anything that I missed, comment below.

  • \$\begingroup\$ What if I make the output message my entire program and then just exec it? \$\endgroup\$
    – hyper-neutrino Mod
    Commented Oct 10, 2017 at 23:30
  • \$\begingroup\$ @HyperNeutrino I'm not really sure what that means. If it takes a link in and outputs the answer then you've completed the challenge. If it outputs the answer and 20 lines of unnecessary information that the user can see, I would say that that doesn't pass the program. \$\endgroup\$
    – Byte11
    Commented Oct 10, 2017 at 23:34
  • \$\begingroup\$ My point is, what if I make a string containing my entire program, use string slicing to output a good falsy message, and then use exec to run the string? Would I be exempted from counting the bytes of my string? \$\endgroup\$
    – hyper-neutrino Mod
    Commented Oct 11, 2017 at 0:05
  • \$\begingroup\$ @HyperNeutrino That's a smart way to get around the rules. No, you wouldn't be exempt from the rules, but from a literal interpretation, you could argue that that is allowed. How should most concisely update my rules to prevent this? \$\endgroup\$
    – Byte11
    Commented Oct 11, 2017 at 0:08
  • \$\begingroup\$ I'd just guarantee that the input will follow a specific format, because making the input contain backslashes, missing components, etc. is just a pain and doesn't demonstrate the answerer's ability to actually do what you really want. Essentially, don't add too much fancy stuff \$\endgroup\$
    – hyper-neutrino Mod
    Commented Oct 11, 2017 at 0:22
  • \$\begingroup\$ @HyperNeutrino Okay, I've updated the question. \$\endgroup\$
    – Byte11
    Commented Oct 11, 2017 at 0:47
  • \$\begingroup\$ along the lines of → unclear what you're asking. \$\endgroup\$
    Commented Nov 3, 2017 at 13:21
  • \$\begingroup\$ Also what exactly is the winning criteria? Another point: A link to this site never have https:://, only https://. \$\endgroup\$
    Commented Nov 3, 2017 at 13:21

Optimised Hashing

For a given set of input, output a program that can 'hash' the input with a minimum number of collisions.

The Challenge

Write a method or function that receives an array of Strings (see input for more detail) and outputs a full program. This program must, for each String in the original input array, print to STDOUT (or equivalent) some positive integer i where i<100 and is unique for that input.

The Input

Each program will be tested with 4 different input sets of 50 unique Strings;

  • 50 English words of the same length.
  • 50 English words of differing lengths.
  • 50 randomly generated character strings of the same length
  • 50 randomly generated character strings of differing lengths

All Strings in all inputs will only contain the character set [a-zA-z] (ASCII values 65-90 and 97-122) and will all be no more than 20 characters long.

Special Rules

  • Standard loopholes are forbidden.
  • Inbuilt hashing functions are not allowed.
  • You must provide a free and easily accessible environment to compile and run both programs with your answer.
  • I reserve the right to discount any program which takes more than 10 minutes to complete any test.


You will be scored by combining the following;

  • The byte count of your original program
  • The byte count of each outputted program
  • 5 penalty points for each 'collision'.

I will keep and update a leader board as programs are added and I can test them.

Please let me know if I've missed anything; this is my first question idea!


Hunting The Wren

Write a program to produce the words to the folk song Hunting The Wren.


"We're hunting the wren." says Robin to Bobbin.
"We're hunting the wren." says Richard to Robin.
"We're hunting the wren." says Jack of the land.
"We're hunting the wren." says everyone.

"Where oh where?" says Robin to Bobbin.
"Where oh where?" says Richard to Robin.
"Where oh where?" says Jack of the land.
"Where oh where?" says everyone.

The song continues with the same structure.

"In yonder green bush."
"How get him down?"
"With sticks and stones."
"How get him home?"
"The brewer's big cart."
"How will we eat him?"
"With knives and forks."
"Who'll come to the dinner?"
"The King and the Queen."

The song concludes with three more verses, which because they have no repetition, we'll omit for the purposes of this challenge.


  • The program must produce the full words of the song as 54 or 55 lines of text.
  • Each verse of four lines must be separated by a blank line. A blank line on the end is optional.
  • You must not use a text decompression library. (GZIP the whole song is 380 bytes.)
  • Normal code golf rules apply. Shortest code wins.

C# Reference Implementation

public class Program
  public static void Main()
    string[] starts = new [] {
      "We're hunting the wren.",  
      "Where oh where?",            "In yonder green bush.",
      "How get him down?",          "With sticks and stones.",
      "How get him home?",          "The brewer's big cart.",
      "How will we eat him?",       "With knives and forks.",
      "Who'll come to the dinner?", "The King and the Queen." };

    string[] ends = new [] {
      "says Robin to Bobbin.",      "says Richard to Robin.",
      "says Jack of the land.",     "says everyone."            };

    foreach (string start in starts)
      foreach (string end in ends)
        System.Console.WriteLine("\"" + start + "\" " + end);       

Pokémon Champion


This challenge is about writing the ultimate bot for battling Pokémon. Since knowledge of competitive Pokémon battling is necessary, I'll leave that to the experts at Smogon University.


  • Your bot must battle another bot in a Gen 7 Random Battle Format.
  • Your bot will be judged based on its performance in a round-robin tournament orchestrated by the author of the challenge, against all other submitted bots before a specific deadline.
  • In order to avoid reinventing the wheel, there are several frameworks already available to choose from. Unfortunately, a lot of these are written in Node.js, so you might still have some porting to do, unless this challenge decides to create its own framework for battling.
  • Since your bot will be connecting to a Showdown server using the existing Web Socket API, any error in your program that causes the bot to become non-responsive or to disconnect will automatically forfeit that match.
  • Standard loopholes apply, and do not exploit any possible bugs in the API. If you find a bug, please report it here.

Further Considerations

While in theory, I think this would be a great idea, I believe this would require a lot of time-investment and groundwork, which frankly I don't have the availability for right now, so anyone is free to take this over, but please be courteous and get my consent in The Nineteenth Byte first. Just @PatrickRoberts and wait for a reply before modifying this proposal.

* Not sure if it's preferable to write an API specifically for this challenge to eliminate the need for Web Socket communication, since there are already available platforms. The idea is to host an official tournament at a certain date (yet undecided) on Pokémon Showdown.

  • 1
    \$\begingroup\$ I could use a new bot on my side server (the one I've got doesn't know about Z-moves so even I can beat it at Ultimate Z...) \$\endgroup\$
    – Neil
    Commented Oct 18, 2017 at 0:19

All the same digits


For any two coprime integers n, b > 1 there exist infinitely many integers k > 0 for which n * k's representation in base b only contains the digit b-1.
This challenge's task is to output the smallest such k for given integers n, b.


Two integers n, b with the above described properties in any reasonable format (integers, strings, ...). If your language does not support arbitrary precision integers, you can assume that n, b < 2**31.


An integer k with the above described properties in any reasonable format (integer, string, ...). If your language does not support arbitrary precision integers, you can assume that k < 2**31.

Test cases

f(  n,     b) == k

f(  7,    10) == 142857
f(  13,    5) == 48
f(  14,   13) == 12
f(1728, 1729) == 1
f( 107,   99) == 54863250648363053681585635237627534906401818527472898624219397466199311510764517134614152141940101983414

To generate more test cases, take a look at my reference implementation written in Python 2.


Fraction periods can also be used to calculate k (example given for n, b = 13, 10).

1/13             =      0.076923(076923)* (period length 6)
1/13 *  10**6    = 076923.076923(076923)*
1/13 * (10**6-1) = 076923
        999999   = 076923 * 13
               k =  76923
  • 2
    \$\begingroup\$ Not true. Consider n=b>1. You need a coprimality condition. \$\endgroup\$ Commented Oct 17, 2017 at 16:03
  • \$\begingroup\$ @PeterTaylor Thanks for noting. \$\endgroup\$ Commented Oct 17, 2017 at 17:38

I'm posting this on sandbox first, because this might not be a good challenge for this site, or just too complicated, because it's about constructing a meaningful sentence. Please, tell me, if it's appropriate task for this site.

Also a note: If you want, I can wait for Christmas with this.

Back to the New Year!

You encounter a probably hard challenge.

Inspired by this answer by @dansalmo.

If we sum character codes in the string Happy new year to you!, we will get 2014. With later years, people started to modify the string, so it fits the current year:

  • 2015: A Happy New Year to You!
  • 2016: Happy New Year to you!!!

The challenge

Given an integer year, output a string meaning "Happy new year!". Sum of character codes should be equal to the integer.


  • No default loop holes allowed
  • Output rules:
    • Meaning rules:
      • You must use the word Happy - you cannot use any other adjective instead.
      • You must wish a NEW year, no matter if it's 2010 or 2020!
      • You can only wish a happy new year - You can't wish a happy new Easter...
      • You can target the string to a person or group, or to everybody: Happy new year!, Happy new year, Soaku!, Happy new year, CodeGolfers!
      • You can add new words, but the sentence can't lose the meaning!
      • Output must have valid grammar, but you can mess up the punctuation. Just note that you can't use punctuation characters except trailing exclamation marks.
    • Letter case rules:
      • First word must start with uppercase letter.
      • Any other word can start with uppercase or lowercase.
      • Letters that aren't first should be lowercase. The only exception is when all letters in the word are uppercase.
    • Punctuation rules:
      • You are not allowed to use any punctuation characters, except on the end of the string
      • There must be exactly one or three exclamation marks ! at the end.
    • Spacing rules:
      • There must be exactly one space between words.
      • No line breaks allowed
      • Leading and trailing spaces/newlines are allowed, but they don't count in the character code sum. Word is the same as outputting Word.
    • Character rules:
      • You cannot use digits!
      • You must only use ASCII letters (the only exception are the trailing exclamation marks)
  • You can assume the input is an integer between 2000 and 3000

Test cases

examples, don't need to be the same

2001 - Happy new YEAR to MYSELF!
2003 - Happy NEW Year TO MYSELF!!!
2004 - A happy new year to me!
2013 - A HAPPY NEW Year To The SE!!!
2014 - Happy new year to you!
2015 - A Happy New Year to You!
2016 - Happy New Year to you!!!
2030 - A Happy New Year To PPCG!!!

Please, suggest any changes and upgrades in the comments

  • 5
    \$\begingroup\$ I think meaning "Happy new year!" is too unclear. There is no way to objectively enforce this. \$\endgroup\$
    – Wheat Wizard Mod
    Commented Oct 23, 2017 at 17:38

Behavior Driven Golfing


From wikipedia (emphasis mine): Behavior Driven Development (BDD) is largely facilitated through the use of a simple domain-specific language (DSL) using natural language constructs (e.g., English-like sentences) that can express the behavior and the expected outcomes.

Example in normal BDD (also from Wikipedia):

Story: Returns go to stock

As a store owner In order to keep track of stock I want to add items back to stock when they're returned.

The challenge:

Write a program that reads like a single English-like sentence that executes the meaning of that sentence.

Other details

  • The program must receive input of some kind (stdin, arguments are okay depending on your language's syntax).
  • The input can be limited in scope, (e.g. all real numbers, all positive even integers), but there must be infinitely many possible inputs assuming that your language doesn't have a cap.
    • For example, if the input is an integer, you don't actually have to handle integers beyond the language's cap, if your language happens to cap at 32 bit long, it just has to be infinitely many in theory but not necessarily in practice.
  • The program must have at least log(n) distinct outputs over an input space of size n.
    • For example, if there existed a language where convert to zero was a valid program, returning 0 on all inputs would not be okay, but printing a number of 0 equal to the base 10 number of digits of the input number would be okay.
  • The program should not error out on legal input.
  • Irregular case and unicode characters are allowed
  • Unicode characters will be interpreted as the similar character in English (so most commands in 05AB1E are allowed).
  • Words may be delimited by punctuation marks instead of spaces, but they must be delimited.
  • Punctuation should not be present in the middle of a word unless it's legal in English (such as an apostrophe in a contraction or a possessive)

Example valid answer for all requirements except the "must take input" requirement:


Print Hello, world.

Since only the H character is an instruction in this language, all the other characters are ignored, and the program prints hello, world. Since case is ignored, this program does what the english sentence says it will do.

  • 3
    \$\begingroup\$ As it's currently written, the task is way too broad. The task that the program should do must be narrowed and clearly specified (e.g., "add the input with itself") in order for this to be well-received. \$\endgroup\$ Commented Oct 20, 2017 at 20:00
  • 2
    \$\begingroup\$ I like the challenge, but I think it should be popularity-contest rather than code-golf. I just feel like code-golf will attract too many answers similar to the example: pick a language that ignores most characters, then write a sentence that describes a built-in and includes that built-in as the only executed character. Popularity Contest seems like it would attract much more interesting answers. \$\endgroup\$ Commented Oct 20, 2017 at 21:59
  • \$\begingroup\$ @KamilDrakari popularity-content is typically not well received, most of those are closed. \$\endgroup\$
    – durron597
    Commented Oct 20, 2017 at 23:20
  • \$\begingroup\$ I'm not exactly sure how we can measure "X is a similar character to Y" objectively.. Probably @Kamil is right and this should be a popularity contest. \$\endgroup\$ Commented Oct 26, 2017 at 19:02
  • \$\begingroup\$ @BruceForte, pop-con is not a "solution" to the problem that the spec is not objective. A pop-con should have an objective validity criterion and not be amenable to an objective scoring criterion. \$\endgroup\$ Commented Oct 27, 2017 at 12:04

Are these numbers perfect for each other?

A perfect number is a number that is the sum of its divisors. Examples of perfect numbers are:

     | Divisors                                  | Divisor sum
6    | 1, 2, 3                                   | 6
28   | 1, 2, 4, 7, 14                            | 28
496  | 1, 2, 4, 8, 16, 31, 62, 124, 248          | 496

Similarly, numbers that are perfect for each other are numbers where each is the sum of the other's divisors.

     | Divisors                                  | Divisor sum
220  | 1, 2, 4, 5, 10, 11, 20, 22, 44, 55, 110   | 284
284  | 1, 2, 4, 71, 142                          | 220


Write a program/function that takes two positive integers and outputs a truthy/falsey value based on whether they are perfect for each other.


  • Standard I/O rules apply.
  • Standard loopholes are forbidden.
  • The output must be consistent for both truthy and falsey values.
  • This challenge is not about finding the shortest approach in all languages, rather, it is about finding the shortest approach in each language.
  • Your code will be scored in bytes, usually in the encoding UTF-8, unless specified otherwise.
  • Built-in functions that perform this task are allowed but including a solution that doesn't rely on a built-in is encouraged.
  • Explanations, even for "practical" languages, are encouraged.

Test cases

Input         Output

1, 1          truthy
3, 7          falsey
6, 6          truthy
13, 42        falsey
220, 284      truthy
563, 492      truthy
1184, 1210    truthy

In a few better formats:

1, 1
3, 7
6, 6
13, 42
220, 284
563, 492
1184, 1210

1 1
3 7
6 6
13 42
220 284
563 492
1184 1210

Reference implementation

This is written in Haskell.

divisors :: Integer -> [Integer]
divisors 1 = [1]
divisors n = [i | i <- [1..n - 1], n `mod` i == 0]

perfectPair :: (Integer, Integer) -> Bool
perfectPair (a, b) = (sum $ divisors a) == b && (sum $ divisors b) == a

Try it online!

This challenge was sandboxed.

  • 2
    \$\begingroup\$ Although I wouldn't really VTC (seems fine to me), this is very likely to be closed as a dupe of Am I perfect (number)?. \$\endgroup\$
    – Mr. Xcoder
    Commented Oct 29, 2017 at 19:46
  • \$\begingroup\$ it's also kinda trivial... Try it online! - 3 bytes, 05AB1E \$\endgroup\$ Commented Oct 31, 2017 at 20:24

Self-language validator

Create a language validator, which takes a string/file that might or might not be syntactically in the language of your choice, and returns a value corresponding to whether or not it is a syntactically valid program in the implementing language.

  • At a bare minimum, your submission must return a truthy value for code where a strict implementation compiles/interprets without any problems, and must return a falsey value for code that even lax implementations cannot recognise as valid in your language.
  • Your submission must have cases where it returns a truthy value, and cases where it returns a falsey value.
  • As long as a construct is syntactically valid and could possibly be of the correct scope/type/whatever, it can be called valid. No need to dig into a repository to fetch documentation for an import or anything like that.
  • Constructs whose syntactic validity depends on the current runtime execution state do not need to be checked, as statically checking their validity would necessitate reasoning about program execution.
  • Appealing to external programs/libraries or to the compiler/interpreter, runtime, or standard libraries to parse or execute the string as language instructions for you would circumvent the whole point of this challenge, and thus is forbidden.
  • Standard loopholes apply.
  • \$\begingroup\$ I don't think quine is correct. Also, you might want to be more explicit that there must be a false case, as languages like Seriously are always syntactically valid. \$\endgroup\$
    – ATaco
    Commented Oct 30, 2017 at 22:31
  • 1
    \$\begingroup\$ I wonder how many languages get trivial solutions to this. \$\endgroup\$
    – Joshua
    Commented Oct 30, 2017 at 22:55

Budget my lunch!

I'm a man of habit, but I also like to live quite frugally so every day I make myself the same lunch consisting of;

  • 3 Falafel
  • 2 Flatbreads
  • A serving of houmous
  • Some lettuce

Now in order to make sure I always put aside enough money for my lunch I need a program that will calculate the total cost of these ingredients for x number of days, and that is where you come in!

The Challenge

Write a method that, when given two integers representing the start day and the number of days to calculate for, will return/print out a the total cost of my food for that number of days. There are several rules that this calculation follows;

  • Each pack of falafel contains 8 falafels and costs £1.50. However, every three days I get lucky and the pack has 9 falafel in it!
  • Each pack of flatbreads contains 6 flatbreads and costs £1.
  • Each pot of houmous contains 4 servings and costs £1.10.
  • Each head of lettuce provides 7 servings and costs 46p (£0.46).
  • Houmous and flatbread both go off over the weekend/I eat them so have to be bought fresh on Monday.

The Input

You will recieve two integers as input. These can be read from STDIN, passed as individual arguments, or passed as an array. Up to you.

The first integer represents the starting day e.g. 1=Monday, 2=Tuesday etc. This will always be between 1 and 5 inclusive.

The second integer is the number of days to budget for not including weekends e.g. an input of 1 and 5 would be budgeting my lunch for each day of the standard working week.

Sample program

Below is a throroughly ungolfed program to use as reference and clarification of the above rules.

public static double budgetMyLunch(int startDay, int days){
    double totalCost = 0;

    final double falafelCost = 1.5;
    final int falafelsInPack = 8;
    int falafels = 0;
    int falafelPackCount = 0;

    final double flatbreadCost = 1;
    final double flatbreadsInPack = 6;
    int flatbreads = 0;

    final double houmousCost = 1.1;
    final int houmousServings = 4;
    int houmous = 0;

    final double lettuceCost = 0.46;
    final int lettuceServings = 7;
    int lettuce = 0;

    int endDay = startDay + days;
    int currentDay = startDay;


        // If there are less than 3 falafels I have to buy some more
            falafels += falafelsInPack;
            // Every third pack of falafel I get lucky and it has 9 instead of 8!
            if(falafelPackCount%3==0) falafels++;
            totalCost += falafelCost;

        // If there are less than 2 flatbreads I have to buy some more
            flatbreads += flatbreadsInPack;
            totalCost += flatbreadCost;

        // If there are no servings of houmous left I have to buy some more
        if(houmous == 0){
            houmous += houmousServings;
            totalCost += houmousCost;

        // If there is no lettuce left I have to buy some more
        if(lettuce == 0){
            lettuce += lettuceServings;
            totalCost += lettuceCost;

        // Use up the ingredients for my lunch!
        falafels -= 3;
        flatbreads -= 2;
        houmous -= 1;
        lettuce -= 1;

        // If it's the end of the week, I eat the remaining
        // houmous and flatbread over the weekend
            houmous = 0;
            flatbreads = 0;

    return totalCost;

Questions for sandbox

  • Any suggested tags other than ?
  • Is the question of appropriate complexity to be an interesting challenge? Should I add more rules?
  • Is the sample program required or are the rules clear enough on their own? If it is required should it be included in the question (as above) or linked through to somewhere like Pastebin?

UTF-8 repair

UTF-8 is the standard by which most of the world operates. Software that was intended to take in other encodings have been modified or wrapped to use UTF-8 as input and output, some with bugs and/or sloppy adherence to the standard. Even rock-solid software with years-old implementations of UTF-8, such as Java, can contain numerous UTF-8 implementation errors.

The challenge

Given a string of characters as input, apply a list of transformations to it. The transformations can be applied in any order, but should have the same result as if the transformations were applied in the listed order.

  • Replace overlong sequences with their equivalent minimal-length encodings.
  • If a byte taking the form 0b11111xxx occurs, replace it, and up to three trailing bytes of the form 0b10xxxxxx, with a single replacement character (\uFFFD).
  • Replace any run of extraneous bytes taking the form 0b10xxxxxx with a single replacement character.
  • If a byte of the form 0b11xxxxxx is followed by an insufficient number of bytes of the form 0b10xxxxxx (either because of a byte of the borm 0b11xxxxxx or the end of the file/string), replace it and any trailing 0b10xxxxxx bytes with a single replacement character.
  • Convert a high surrogate character followed by a low surrogate character to the utf-8 encoding of the supplemental plane codepoint it represents.
  • Replace extraneous surrogate characters with the replacement character.
  • Remove the initial byte order mark (\uFEFF), if one occurs at the start of the string.
  • Keep all other characters intact. Make particular care to make sure that null characters are handled correctly.

The following are errors:

  • An inverted byte order mark (\uFFFE) occurs at the start of a string.
  • The transformed string consists of more than 16 codepoints, and more than 1/8 of them correspond to bad byte sequences.
  • The input string consists of more than 32 bytes, and more than 1/8 of them do not correspond to a valid character, an overlong character, or a surrogate character.

If an error occurs, use an error indication mechanism (return a null pointer, utilize a tagged union indicating an error condition, set an global error variable, throw an exception, raise a signal, whatever), and do not output anything other than an optional error message. Otherwise, print the whole transformed string.

Standard loopholes apply. As with all code golf challenges, shortest submission wins.

Test cases:

To be added if this submission gains traction.


Reverse a regex

The .NET regex engine has the ability to process a regex in right-to-left order. There are some subtle differences between right-to-left and left-to-right order, so for the purposes of this challenge, right-to-left order is equivalent to running a reversed regex on a reversed string.

But how do you reverse a regex? Aha, that's where you come in. You need to write a program or function that reads a regex and writes one that will match reversed strings.

Fortunately reversing regexes is quite simple: break them down into symbols and concatenate them in reverse order. The symbols you should support are as follows:

  • Unquoted nonmagic characters
  • Quoted characters
  • Character classes (anything from [ to an unquoted ])
  • Symbols with repetition suffixes (assume that any of +*? or {...} is a valid repetition suffix)
  • Parenthesised regexes (the inner regex will itself need to be reversed)

So for instance the reverse of a{2,}(\*[b-g])+ is ([b-g]\*)+a{2,}.

TODO: More examples, rules, loopholes.

Should I add lookaheads/behinds to the list or is that too complex?

  • \$\begingroup\$ Character classes and repetition suffixes, at the very least, need more detail. Obviously some advanced repetition suffixes simply can't work, but which ones should be implemented? \$\endgroup\$ Commented Nov 3, 2017 at 11:16
  • \$\begingroup\$ @PeterTaylor I don't understand why they can't work. You'll be able to assume that the input is a valid regex, so you'll be able to treat a+? as the symbol a+ with a suffix of ?. \$\endgroup\$
    – Neil
    Commented Nov 3, 2017 at 13:42
  • \$\begingroup\$ I had possessive quantifiers particularly in mind. I do retract the "obviously": now that I'm trying to think of an explicit example, it's not easy. But I'm still confident that one can be constructed. \$\endgroup\$ Commented Nov 3, 2017 at 18:26

Find local Minimum

META: This is just meant as an introductory challenge for functional input (black box functions) and hopefully establish some more inputs.

Given a real number e > 0 and some black box function f: (0,1) → (-10,10) ⊆ ℝ, return a value x that is within e of a local minimum x* that means x ∊ [x* - e, x* + e].


  • A value x* is local minimum of f if and only if there is some a > 0 such that f(x*) < f(x) for all x ∊ (x* - a, x* + a) \ {x*}. This means all other points in some neighbourhood must have a strictly greater function value. (This definition is just for this challenge and might be different from other definitions.)
  • The input function f can assumed to be differentiable and satisfy f'(0) < 0 and f'(1) > 0 which means there are no local minima at 0 and 1.
  • You can assume that |f'(x)| < 1000 this means the function cannot be to steep.
  • You can use your native floating point numbers and assume e is sufficiently great. (That means greater than the machine precision of your floating point type.)
  • You can use any language for which there are defaults for black box functions input in the standard IO meta post. If there are no such default for your language feel free to add one in the sense of the definition of black box functions, and make sure to link your proposals in that definition. Also don't forget to vote on them.


x*                 f(x)
0.5                x*(x-1)
0.5                (x+1/2)^(2*k-1) * (x-3/2)^(2*k-1) for k=1,2,...,1000 
2*(k+1/4)/(2*n-1)  -sin(pi*(2*n-1)) for n=1,2,3,...,159 (for every applicable k there is one minimum)
  • \$\begingroup\$ FWIW there was a black-box function question a long time ago: codegolf.stackexchange.com/q/3839/194 . On a separate issue, being differentiable is quite a weak condition: is it strong enough to make this answerable? I don't know the whole zoo of nasty counterexamples in analysis, but ISTM that to have a local minimum you need a second derivative, and to solve for a black box you probably want at least the second derivative to be continuous. \$\endgroup\$ Commented Nov 6, 2017 at 14:47
  • \$\begingroup\$ Thank you for the feedback. You're right, right now it is not answerable, I found an counterexample, and also with requiring second derivatives we can solve it as a black box function. \$\endgroup\$
    – flawr
    Commented Nov 6, 2017 at 20:13

I asked this question in main site. Got a very bad review. So, I would be glad if any kind soul here would like to help me make this question better. And Some feedback on how can i make it good.

Given any input, you need to encode / decode it in or from base 16, 32, 64.

So your task will be to make a base 16, 32, 64 encoder / decoder.

Standard Loopholes apply.
and that's all
In any format you like.
The inputs will be the 
i. Data
ii. Task (encoding or decoding) (0 or 1)
iii. Base (16 or 32 or 64)

The Encoded/Decoded data

The shortest code in byte wins.

Reference : RFC

  • \$\begingroup\$ Just as a starter, I would remove the "It should not be a builtin" (see this) Secondly, rather than link to a website with a description of what you mean, include that description in your question. Finally, allow function answers, rather than restricting to a full program. \$\endgroup\$ Commented Nov 5, 2017 at 16:10
  • \$\begingroup\$ @cairdcoinheringaahing thanks. I will add those changes \$\endgroup\$ Commented Nov 6, 2017 at 2:36

The Guardian of the Chessboard

Given a collection of chess squares1, output the chess piece with the smallest value, together with its position, that is able to reach all the given squares in a single step.

1 - A chess square is a notation of a position on an 8x8 grid, with the x-axis being labeled with letters instead of numbers, meaning for example that the notation of 3|2 would be c2.


Input must be received as a collection of strings, each string representing a chess square. You may assume that the chess square will always be in the range a1 - h8.

Example Input: [ "b7", "c4", "h1", "g8" ]


Output must be in the format [piece][square], with piece being the notation of the chess piece, such as N, Q or K, and square being the notation of the square that the chess piece has to be located at.

You may either return a string from a method or directly output the result to stdout.


  • Note that you have to use the chess piece with the least possible value, so if there is a choice between for example Queen and Bishop, you would choose the Bishop. See below for a table noting the piece values.
  • Special moves such as pawn's first move, en passent and castling do not have to be respected.
  • This is , shortest code in bytes, in any programming language wins.
  • Standard loopholes are forbidden.

Data Table

Here you can look up each pieces value and its notation character.

|  Piece | Value | Character |
| Pawn   | 1     | P         |
| King   | 2     | K         |
| Knight | 3     | N         |
| Bishop | 3     | B         |
| Rook   | 5     | R         |
| Queen  | 9     | Q         |

Test Cases

Input -> Output

[ "b7", "c4", "h1", "g8" ] -> Bd5

(TODO: Add more testcases)


  • Duplicates?
  • Possible misunderstatings?
  • Task changes?
  • \$\begingroup\$ Reach in exactly 1 step? Is 0 step allowed? What about multiple steps? \$\endgroup\$
    Commented Nov 6, 2017 at 1:23
  • \$\begingroup\$ @user202729 Thanks, clarified. \$\endgroup\$
    – Ian H.
    Commented Nov 6, 2017 at 8:55
  • \$\begingroup\$ Needs a mention of special cases (pawn's first move, en passant, castling): should we assume that none of them are available? \$\endgroup\$ Commented Nov 6, 2017 at 14:35
  • \$\begingroup\$ @PeterTaylor That's correct, I added it to the rules section, thanks! \$\endgroup\$
    – Ian H.
    Commented Nov 6, 2017 at 16:27

Ternary Parity of Substrings


The ternary parity of a string is the number of 1's in its ascii bitstring mod 3. For instance, the ascii values for "Hello World!" are:

H:72 e:101 l:108 l:108 o:111 space:32 W:87 o:111 r:114 l:108 d:100 !:33

Converting each ascii value to binary gives:

H:1001000 e:1100101 l:1101100 l:1101100 o:1101111 space:100000 W:1010111 o:1101111 r:1110010 l:1101100 d:1100100 !:100001

Concatenating these together gives the combined bitstring:


Which has 45 1's. As a result, the ternary parity of "Hello World!" is 45%3 = 0.


Write the shortest program in the language of your choice that does the following:

  • Takes a string, s, as input.
  • Finds S, the collection of all substrings of s
  • Calculates the ternary parity of each element of S
  • Creates a ternary string, q, by concatenating the parity bits of each element in S
  • Outputs the ternary parity of q. That is, the number of 1's in q mod 3.


Input and output may use any of the standard methods listed here. The program must output three distinct values that indicate ternary parity. For instance, the program could print "one", "two", or "three", it could exit with an error code of 0, 1, or 2, or could be a function that returns False for 1 and Null for 2, and 100 for 0, etc.

Test Cases

"Hello World!" => 0
"foobar" => 2
"ABCDEFG" => 1
"abcdefg" => 0
"One" => 2
"Four" => 0
"2049" => 1
  • 2
    \$\begingroup\$ One element of a good question is a clear motivation. This looks like a random mishmash of operations. Why should anyone care about the result of this calculation? \$\endgroup\$ Commented Nov 7, 2017 at 10:14

Output an Anagram! No Not That One!

Given a list of unique strings that are anagrams of each other, output an anagram of those words that is different from each word in the list.

The strings will be alphanumeric, and there is guaranteed to be a valid anagram.

The program or function can, but doesn't have to be non-deterministic, meaning given the same input, multiple running a of the code can yield different outputs, as long as every possible output is a valid one.

Test Cases

[Input] -> Possible output
[ab] -> ba
[aba, aab] -> baa
[123, 132, 231, 312, 321] -> 213
[hq999, 9h9q9, 9qh99] -> 999hq
[abcde123, ab3e1cd2, 321edbac, bcda1e23] -> ba213ecd

Sandbox questions

  • Is this a duplicate of anything?
  • Any other test cases I should include?
  • 1
    \$\begingroup\$ I should probably post my other sandboxed challenge at some point... \$\endgroup\$ Commented Sep 27, 2017 at 1:23
  • 1
    \$\begingroup\$ Should it output the same string each time given the same array of strings as input? \$\endgroup\$
    – Shaggy
    Commented Sep 27, 2017 at 10:17
  • \$\begingroup\$ What do you mean by "unique" in the first sentence? \$\endgroup\$ Commented Sep 27, 2017 at 19:43
  • \$\begingroup\$ @PeterTaylor Did that clear it up? \$\endgroup\$ Commented Sep 27, 2017 at 20:42

Clear the centrally significant on bits

Related and inspired by.


Input is a single positive integer n.


It's easiest to describe this by example.

n = 433

Take n's binary representation.

bin(n) = 110110001 

Note which bits are on.

^^ ^^   ^

Set the center bit of those that are on to 0. (if there is an even number of 1 bits, set both to 0).

^^ !^   ^

Finally, represent the input as an integer again.

unbin(110010001) = 401

Test cases

1 => 0
13 => 9
115 => 99
236 => 204
433 => 401
732 => 652
1555 => 1539
1556 => 1028

Additional Rules


Bring an end to the Vigil

Vigil, being the supreme moral paragon of programming languages, inspires us all to write bug-free code without exceptions through supreme medieval punishment.

However, every hero has their weakness, and Vigil's weakness is on line 98:

    print("Vigil has failed to uphold supreme moral vigilance.")

Your goal is to write a Vigil program that forces Vigil to experience an exception, reach this line, and print this error. Because it's not enough to merely succeed at our master plans, but instead we ought to succeed efficiently, the shortest answer in bytes wins.

Draft proposal notes

  • This is a language-specific challenge in the Vigil language alone. (Is there a tag for that?)
  • I'm not sure if a standard challenge is the best way to measure a winner in this scenario, but it's the primary measure that comes to mind.
  • I'd like to ham this up a bit more with narrative. Maybe about us being the villains. The title could be wittier.

Inverse Radiation Hardened Quine


Radiation hardened quines have been around for a long time. The basic idea is that it's (possibly) a valid quine, and if you remove any character, it's still valid. But what about the other way around? What if you added a character?

Challenge Description

Develop a program which will output its source code, even when a character is inserted in any position in the source code.


This program is a quine. It shouldn't take any input.


When the quine runs, it should either output its own source code, or the source code of the proto-quine.


Programs are scored on their robustness. That is, for a given program, if the characters "a", "!" or "😷" could be put into the program at any point and it remain a quine, then the program has a score of 3. I leave the burden of testing what characters work for your program up to you. Note that in languages with a limited character set (such as HQ9+ or brainfuck) characters that do nothing yield no score. You couldn't write a normal quine in brainfuck and then claim that every single unicode codepoint except the few used in a brainfuck program was your score.

Finally, other than that, standard rules apply.

  • \$\begingroup\$ Not a bad challenge, but could use some more fleshing out. Take a look at the framework of some other challenges, both here and in main, to see what the usual framework is. \$\endgroup\$
    – Gryphon
    Commented Nov 17, 2017 at 0:58
  • \$\begingroup\$ To clarify, I mean specifically the usual: brief story about the challenge (optional), "Your Task:", task, "Input:" input methods, "Output:", output methods, "Examples:", examples, "Scoring:", scoring method. That framework works well for most challenges \$\endgroup\$
    – Gryphon
    Commented Nov 17, 2017 at 1:00
  • \$\begingroup\$ Can we chose where the character is inserted? \$\endgroup\$
    – ATaco
    Commented Nov 17, 2017 at 1:13
  • \$\begingroup\$ @ATaco no, it has to be valid for anywhere. Otherwise, somebody would make a safety box for the character. \$\endgroup\$ Commented Nov 17, 2017 at 1:21
  • \$\begingroup\$ I would suggest clarifying your scoring section, specifically specifying "robustness" better. I'm pretty sure I get what you mean, but others may misinterpret that. Other than that, this looks like a great challenge. +1 \$\endgroup\$
    – Gryphon
    Commented Nov 17, 2017 at 1:57
  • \$\begingroup\$ Is the emoji bad? I put it in there to demonstrate únicode, but I'm not sure the point is that obvious. \$\endgroup\$ Commented Nov 17, 2017 at 2:41
  • \$\begingroup\$ Nah, it's fine. The example makes it more clear. I might add something to specifically say that it doesn't count if a character can be inserted twice (or at least, that's my understanding of the rules), but other than that, you should be good. \$\endgroup\$
    – Gryphon
    Commented Nov 17, 2017 at 3:24
  • \$\begingroup\$ To be certain, when you say it should output "it's own source code, or the source code of the proto-quine" then, after a character is added, your code may either output the original code or the modified code? Is it alright if a single submission does one or the other depending on the type or location of the inserted character? \$\endgroup\$ Commented Nov 17, 2017 at 15:34
  • \$\begingroup\$ @KamilDrakari yeah, as long as it does do at least one of the two. \$\endgroup\$ Commented Nov 17, 2017 at 18:16

Rhythm Generator

Your task: given a number n from 2 to 5 inclusive, (pseudo)randomly generate a valid rhythm in the time signature n/4, and output using the system explained below. It must have an equal chance of choosing each valid rhythm.

Background Information:

In music, collections of beats are called "measures." You can only fit a certain number of beats in a measure, determined by the time signature. For example, a time signature of 4/4 would mean that you can put 4 (as determined by the first number) quarter note (determined by the second number) beats in the measure.

There are different kinds of notes. For the purposes of this challenge, the following characters will represent different kinds of notes (and how many quarter note beats each one is worth):

W        Whole note                4
H        Half note                 2
K        Dotted Half note          3
Q        Quarter note              1
D        Dotted Quarter note       1.5
E        Eighth note               0.5
F        Dotted Eighth note        0.75
S        Sixteenth note            0.25

(There are other kinds of notes but they do not apply to this challenge)

Note: A dotted note takes 1.5 of the length of its non-dotted counterpart.

In a n/4 measure there can only be n quarter note beats. Some notes take more than a beat, some less. But the total number of beats needs to add up to n.

For example, here are some valid 4/4 measures (separated by newlines):


And here are some examples of valid 3/4 measures:


So, your task is to generate a rhythm and output it in that format.

So now let's make some music!

Test Cases:

Coming soon. Will be a complete list of all possible valid rhythms.


Examining the Student's Swing

The 2017 Level 1 Mathematics and Statistics NCEA examination paper has been making headlines in New Zealand for being 'impossible' and bringing students to tears.

One of the questions involves a children's playground swing, and finding where the holes in the swing seat should be placed. But lets generalise the problem in code in the fewest number of bytes, in case they have to solve for a different swing (in a different exam).


Find how far apart the holes in the board need to be if the shape of the rope stays the same, given the following swing setup:

  • The rope hangs from a cross beam at a height h, and will have a parabolic shape, as presented in the exam (rather than a catenary shape), and will maintain this shape with the seat.
  • The rope is connected to the crossbeam at two points, that are separated by a distance d.
  • The lowest point (vertex) of the rope sits above the ground at a height of v.
  • We have an adequately sized wooden board for the seat, and we want this to be at a height s above the ground.

Exam questions often have a visual representation to help clarify the question, so I've also included one:

enter image description here


  • inputs must take positive real values
  • s will be greater than v
  • output must be correct to at least 2dp.
  • This is , therefore, the lowest byte count in each programming language wins
  • Standard rules apply, and no forbidden loopholes

Test Cases

(h,d,v,s) -> hole separation
(4, 6, 1, 1.2) -> 1.549
(10, 4, 2, 4) -> 2
(14.5, 12, 2.5, 5.5) -> 6
(4.25, 3.4, 0.5, 1.2) -> 1.468

Sandbox Questions

  • First time question, so any recommendations would be great
  • Any recommendations for how I can make this a well received question?
  • are there any rules I'm missing, or should add?
  • is this a duplicate?
  • What other tags should this question have?
  • \$\begingroup\$ About the output must be correct to at least 2dp. part, I'm afraid that there will be some problems from that requirement. A better requirement is "the algorithm in the code must be able to theorically calculate to infinite precision, but numerical error from programming language type limit is acceptable". / Also, the "the rope is always in parabolic shape" is weird, is that correct? If so you should highlight it. (normally a unweighed rope has catenary shape, and a weighed rope has the shape of multiple straight line segment) / Otherwise the challenge looks good. \$\endgroup\$
    Commented Nov 22, 2017 at 7:48
  • \$\begingroup\$ Thanks for the suggestions; the 2dp was based on the exam question requirement of showing your working to 2dp, though I understand the precision issue. Maybe I just remove that rule? I didn't know about catenary shape, the exam question just used a parabola, so I'll highlight that fact. \$\endgroup\$
    – Ayb4btu
    Commented Nov 22, 2017 at 8:39
  • \$\begingroup\$ So in other words, given (h,d,v,s) output d sqrt((s-v)/(h-v)). I don't think it's a duplicate, but I also think that the reason that it isn't is because everyone has previously (and correctly) concluded that calculating a square root without restrictions to prohibit builtin sqrt functions is too trivial to be worth posting. \$\endgroup\$ Commented Nov 22, 2017 at 15:00
  • \$\begingroup\$ @PeterTaylor Well, (you know) on this site it is generally discouraged to post a "puzzle", because once the first answer had been posted, the other answers can just use that - and your comment has already specified the method. / You meant sqrt should be prohibited? That will lead to the (well-known) do X without Y problem. \$\endgroup\$
    Commented Nov 22, 2017 at 15:15
  • \$\begingroup\$ @user202729, no, I did not mean that. I meant that "Calculate sqrt without a builtin sqrt" would be a duplicate (although maybe only of closed questions). See codegolf.stackexchange.com/q/73/194 and linked questions. \$\endgroup\$ Commented Nov 22, 2017 at 15:25
  • \$\begingroup\$ @PeterTaylor This exam question certainly simplified down to a trivial coding answer; I think I was more posting due to the story behind it. I'll have a think about if or how to make it a bit more challenging. Will just mean that it may not be as closely related to the exam question on which it is based. \$\endgroup\$
    – Ayb4btu
    Commented Nov 22, 2017 at 20:29

View float numbers in graphical binary

IEEE 754 is a well known format for representing floating point numbers.

Your task is to give an input to the user where he/she enters a signed float number and represents clearly the number in a color separated by functional area binary 32 bit single representation, like:

  • You do not have to append the captions like they are in the figure.

  • You must follow the order Sign, Exponent, Fraction

  • You may choose whatever colors you want, as they are distinguishable from each other and from the binary text numbers.

  • The input (I suggest a text box) does not have to forbid invalid values, but if does not, the graphical binary view needs to indicate the invalidity. You can leave it empty or replace with some text like "ERROR" or "INVALID".

  • Every little change on the input needs to make the binary view to be immediately updated. Changing and have to confirm with an "OK" like button is not acceptable.

No winner, unless I see some very creative answer. I would like to see a golfed and an ungolfed version of the code.

  • 1
    \$\begingroup\$ Needing the output to be dynamically updated based on the input changing (and not an OK or the like) is going to drastically limit the languages that can participate. \$\endgroup\$ Commented Nov 21, 2017 at 18:58
  • 1
    \$\begingroup\$ Additionally to what @AdmBorkBork said, the requirement of dynamically updating the output & validating input is just distracting from the real challenge. I'd just leave behaviour on invalid input undefined. \$\endgroup\$ Commented Nov 22, 2017 at 15:08

Optimise Retina transliterations

For the question Translate Morse code based on tone duration I stupidly created the following transliteration:


The first thing wrong with it is that it 2, 8 and 9 transliterate to themselves, so they are superfluous. This saves 6 bytes:


The next thing to notice is that we have some runs of consecutive letters, but because they're not ordered we can't reduce them. Let's sort them:


We can now save another 3 bytes by using the run G-K, a byte by using the run M-O, and 3 bytes by using the run R-W:


Total 13 bytes saved. Note that there are other optimisation opportunities but I think they might be too difficult be worth adding to the question; for instance, inserting a C (at a cost of 2 bytes) allows the creation of the run A-E for a 3-byte saving, which is still overall a byte saved; inserting all of the letters to achieve run A-Z would then be simplified to L.

Is the Retina command string too inflexible an input format? I suppose input could be in the form of an unordered mapping from printable ASCII to printable ASCII, but output would need to be the actual Retina syntax, including appropriate quoting, because the length of the result is important.

(Quoting: The characters -dEOHhLlwpoR`\ need to be quoted except that the letters don't need to be quoted as part of a range.)

Should this be a question or ?


A Knight's Walk

On a chessboard, a knight has two options for movement: it can move one square horizontally and two squares vertically, or two squares horizontally and one square vertically. In short, it can follow the path drawn by an upper-case "L". These can be oriented in any way, and as such, a knight has 8 potential moves from any given position.

There have been a number of challenges posted at one time or another regarding knights and their movement because they're so mathematically interesting (and the problems are easy to state) but we're going to go for a basic one that I haven't seen.

The Challenge

Given two 2d coordinates (x1, y1), (x2, y2) return the minimum number of moves required to travel from (x1, y1) to (x2, y2).

There are no other pieces on the board, and you may assume that the coordinate values given are valid (a set of two integers) though they may not be unique. You may also assume that each individual coordinate value will be between 0 and 255, and that the board is large enough that you needn't consider edges.

Input Format

As long as the coordinates are inputted in the order x1 y1 x2 y2 you can accept them as four separate values, two tuples, two lists, etc...


(0, 0) (1, 2) => 1
(0, 0) (1, 1) => 2
(125, 125) (126, 127) => 1
(-100, -100) (0, 100) => 100
  • \$\begingroup\$ You might want to more explicitly state that negative numbers must be supported. Also, 'less than 128' applies only to inputs? or to anything? \$\endgroup\$
    – Riker
    Commented Nov 24, 2017 at 0:24
  • \$\begingroup\$ Will do! And I'm not sure what you mean by that second part: I mean the input values will individually have absolute values of less than 128 a.k.a. (-127, -127) to (127, 127). This is totally a point I'm flexible on though. I just figured there may be languages that don't support very large numbers in any given memory location, and didn't want to give them additional hoops to jump through. Edit: Should I just make the valid range 0-255? \$\endgroup\$
    – Willbeing
    Commented Nov 24, 2017 at 1:45
  • \$\begingroup\$ I'd recommend making it 0-255, yeah. I don't really think it's fair to have input be -127, +127, and then the boundaries of the chesboard be infinity. That's just kinda contradictory. \$\endgroup\$
    – Riker
    Commented Nov 24, 2017 at 2:14
  • \$\begingroup\$ Do you think I should keep a bound like 255 at all? Would 2^16-1 or 2^32-1 be better? My whole premise with picking a number like this was that I want it to be easy to represent any number you'd run into, but impossible to use any kind of naive recursion to solve it \$\endgroup\$
    – Willbeing
    Commented Nov 24, 2017 at 3:31
  • \$\begingroup\$ "impossible to use any kind of naive recursion to solve it" - Why? I don't understand your argument. / What is the winning criteria? \$\endgroup\$
    Commented Nov 24, 2017 at 13:29
  • \$\begingroup\$ @Willbeing I think 255 is fine, it doesn't matter too much. I've seen successful challenges that only require you to support up to 255, but that's it. \$\endgroup\$
    – Riker
    Commented Nov 24, 2017 at 14:35
  • \$\begingroup\$ @user202729 Yeah, it sounds odd when its played back to me, hahaha. I only care if the program deterministically produces the correct step count. I still think limiting the input size is probs a good idea, just not for that reason anymore. \$\endgroup\$
    – Willbeing
    Commented Nov 24, 2017 at 19:21

Clean duplicate website from my history


I am looking for help to monitor my history. I parsed everything, but I am not yet happy with the final result. Could you help me? I want to remove following same website.

My history looks like this:

| url                                               | id |
| https://codegolf.stackexchange.com/q/147318/15214 | 4  |
| https://codegolf.stackexchange.com/q/148927/15214 | 4  |
| https://en.wikipedia.org/wiki/Code_golf           | 3  |
| http://lichess.org                                | 2  |
| https://en.wikipedia.org/wiki/Code_poetry         | 1  |

But I want it to be:

| url                                               | id |
| https://codegolf.stackexchange.com/q/148927/15214 | 4  |
| https://en.wikipedia.org/wiki/Code_golf           | 3  |
| http://lichess.org                                | 2  |
| https://en.wikipedia.org/wiki/Code_poetry         | 1  |
  • If I browse a site, then another one, then the first one. I keep all of them.
  • If I browse a site, then another part of the same site. I keep only the first one.
  • The list is ordered from young to old. (we keep the older)

This challenge is inspired by my day work, but it is not related in any ways with anything in it.


  • Input is a list of identifier.
  • Output is a list of two elements (identifier's index, identifier).
  • No Empty input
  • No standard loophole
  • This is code-golf, so shortest answer in bytes wins.

Examples Input and Output

2 links on website 1


[ 1, 1 ]



1 link on website 2, then 3 links on website 1


[ 1, 1, 1, 2]



1 link on website 1, then 1 link on website 2, then 2 link on website 1


[ 1, 1, 2, 1]




  • Should I allow outputs as list of object, list of tuple or dictionary/map?
  • Should I ask for url parsing where identifier is the hostname?
  • 1
    \$\begingroup\$ Question title and tag? \$\endgroup\$
    Commented Nov 24, 2017 at 14:11
  • 1
    \$\begingroup\$ Also I think the I/O specification (Input is a list of two elements. / Output is a list of two elements.") seems to contradict the test cases. \$\endgroup\$
    Commented Nov 24, 2017 at 14:33
  • \$\begingroup\$ @user202729 Update title, tag and I/O specs. Thank you. \$\endgroup\$
    – aloisdg
    Commented Nov 24, 2017 at 14:53
  • \$\begingroup\$ You definitely should allow using tuples, maps and dictionaries for input and output. In fact, that's an understatement. You should read the meta post on I/O methods. URL parsing will make the challenge more interesting, IMO. \$\endgroup\$
    – Maya
    Commented Nov 24, 2017 at 19:12

Implement a basic two-dimensional esolang

There are hundreds of two-dimensional stack-based esoteric programming languages out there, and lots of them follow a very similar syntax:

v redirect instruction pointer down
> redirect instruction pointer right
^ redirect instruction pointer up
< redirect instruction pointer left
/ redirect instruction pointer: up -> right, right -> up, left -> down, down -> left
\ redirect instruction pointer: up -> left, left -> up, right -> down, down -> right
0 push 0 to the stack. 1 pushes 1, ... 9 pushes 9.
A push 10 to the stack. B pushes 11, ... F pushes 15.
: duplicate the top stack value
~ swap top two stack values (all languages implement this as a different character)
i read input as a ASCII character and push to stack
o print the top of stack as an ASCII character
n read input as integer and push to stack
u print the top of stack as an integer
+ increment the top of stack
- decrement the top of stack
! jump over the next command
; stop execution

Almost all two-dimensional esolangs contain more commands, but for the sake of simplicity, the one we're writing will contain only the above.


The stack should be able to hold at least 30,000 values. You may pick any integer size (e.g. 32-bit, 64-bit, unbounded, etc) for stack values.

The instruction pointer should start moving right from the top left corner of the source code, and should wrap upon exiting the playing field, meaning that this code will be an infinite loop:


First, < will be reached, pointing the IP off to the left.
The IP will wrap around to the right, continuing left, and hit the ^, directing it up.
Then it will wrap, hit the > and travel right, wrap, hit the v and travel down, wrap, hit the <, and start over.


DNA Quine

Problem Description

Design a quine that outputs its own source code, but encoded into amino acids.
Read your source code in as binary. Each pair of bits now maps to a nucleotide like so:

00 -> A
01 -> C
10 -> G
11 -> T

For example, the ASCII character N has a binary representation of 01001110, so it would produce the nucleotide sequence CATG. A set of three nucleotides produces an amino acid. You can find the charts online, and I can't access imgur, so... yeah.

Anyways, your program must output its own source code as the three letter amino acid names. For example, if your code were 013201323300 in base 4, its nucleotide representation would be ACTGACTGTTAA and its amino acid representation would be ThrAspCysSTP.


Your program must output its representation in amino acids.

Further Rules

All quines must also be valid proteins themselves. This means that:

  • The quine has a number of nucleotides divisible by three
  • The last three nucleotides are either TAG, TAA, or TGA, corresponding to a STP codon
  • No STP codons appear anywhere but the end of the quine.

Apart from that, the standard rules apply.


This is code golf, so the shortest code wins.

Notes/Questions for Sandboxing

Ok, so I get that it's rather short. Is my point clear? Is the scoring section clear? How about loopholes? Should I point out that printing a single STP is not allowed? Would that even be possible?

  • 1
    \$\begingroup\$ You might want to elaborate on "expand it into base 4". Does that mean get each byte's codepoint, concatenate into one big binary integer, and then convert to base 4? \$\endgroup\$
    – FlipTack
    Commented Nov 27, 2017 at 20:00
  • \$\begingroup\$ What happens if the number of nucleotide is not a multiple of 3? | The base 4 conversion is indeed unclear. \$\endgroup\$
    Commented Nov 28, 2017 at 1:01
  • \$\begingroup\$ @user202729 if there's a spare nucleotide, it's not a valid program. \$\endgroup\$ Commented Nov 28, 2017 at 1:27
  • \$\begingroup\$ So basically "program length must be a multiple of 3". / For example program 00 FF should be 00 00 00 00 11 11 11 11 = AAAATTTT or TTTTAAAA? \$\endgroup\$
    Commented Nov 28, 2017 at 1:52
  • \$\begingroup\$ Yeah, essentially. Except that some code golf languages have special character sets that aren't 8 bits, and some trickster out there might use that. \$\endgroup\$ Commented Nov 28, 2017 at 2:10
  • \$\begingroup\$ @JakobLovern Unless there are some computers that can store fractional byte size, that won't be accepted. \$\endgroup\$
    Commented Nov 28, 2017 at 2:53
  • \$\begingroup\$ I have no idea how to convert CATG into amino acids. Challenges should be self-contained. \$\endgroup\$ Commented Nov 29, 2017 at 14:46
  • \$\begingroup\$ I suspect most answers will be of the form "1. get string of source code by standard quine technique" and "2. convert string into dna form", so the first part doesn't add anything to the challenge. I'd suggest to change the task to write a program which translates a given string into your DNA format. \$\endgroup\$
    – Laikoni
    Commented Nov 29, 2017 at 17:16

Create a Flip-Flop Program

Your challenge is simple: write a full program which alternates between two different outputs upon each run.

Your submission can choose which is printed the first time the program is run, but after that it should alternate between these exact outputs.


  • You cannot assume the filename of your program.
  • The values must be distinct.
  • Creating files is allowed - you are allowed to assume a file such as a.txt does not already exist in the directory.
  • Reading and modifying the source is allowed.
  • This is , so the shortest solution (in bytes) wins! Standard golfing loopholes apply.


  • Should I allow assuming the program's filename at an additional bytecount (length of filename)?

  • \$\begingroup\$ Is it neccessary that the first run always produces the same value? (That makes the problem considerably harder, because it requires detecting the first run.) I agree with the full program restriction here, btw; it avoids a lot of dubious rules-bending answers that change something in the execution state. \$\endgroup\$
    – user62131
    Commented Jan 10, 2017 at 16:58
  • \$\begingroup\$ If you want to be really crazy, you can do something like main(){int n = 1 Then change n in the compiled file return n;} \$\endgroup\$ Commented Jan 12, 2017 at 16:12
  • \$\begingroup\$ @FryAmTheEggman is this an explanation of the downvote or was that someone else? \$\endgroup\$
    – FlipTack
    Commented Nov 29, 2017 at 8:02
  • \$\begingroup\$ @FryAmTheEggman see update. \$\endgroup\$
    – FlipTack
    Commented Nov 29, 2017 at 8:14
  • \$\begingroup\$ Why the full program requirement? As far as I can tell, it will be very hard to do this with just functions. Why disallow something that could give interesting answers? Programs would likely just change their own source code, or read a value from a file and then change it (or append a new one). \$\endgroup\$ Commented Nov 29, 2017 at 8:48
  • \$\begingroup\$ Closely related. \$\endgroup\$ Commented Nov 29, 2017 at 14:39
  • \$\begingroup\$ @AdmBorkBork would you say that it's too similar? \$\endgroup\$
    – FlipTack
    Commented Nov 29, 2017 at 16:36
  • \$\begingroup\$ Personally, I think they're distinct enough to not be a duplicate, they're just definitely related. \$\endgroup\$ Commented Nov 29, 2017 at 16:41
  • \$\begingroup\$ I didn't downvote since to me this looked fairly good besides what felt like an arbitrary restriction that would just make gaming the challenge easier. Also, I remembered another related challenge, for reference. \$\endgroup\$ Commented Nov 30, 2017 at 0:25
  • \$\begingroup\$ @FryAmTheEggman that's why I recently helped add the stateful tag, all similar challenges involving storing data between runs and self-modifying code are gradually being added there \$\endgroup\$
    – FlipTack
    Commented Nov 30, 2017 at 7:29
111 112
114 115

You must log in to answer this question.

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