What is the Sandbox?

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

To post to the Sandbox, scroll to the bottom of this page or click on the "Add Proposal" link below, 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. 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, replace the post here with a link to the challenge and delete it.

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

The Sandbox works best if you sort posts by "active".

Add Proposal

Search the Sandbox

Browse your pending proposals

Get the Sandbox Viewer to view the sandbox more easily

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


3113 Answers 3113

45 46
48 49

My Number is Bigger Than Yours: KoTH

The concept of this game is simple; each turn, two bots submit a positive integer (in Python, so no upper bound on its size). Whichever bot submits a larger number wins a certain number of points based on the scoring put forward in the next section. This process is iterated a certain number (100?) times to form the competition, with the bot which has the highest score winning the competition between the two bots.

However, scoring is based on some metric of the difference between the submitted values such that the larger the difference is, the smaller the amount of score gained is. I'm trying to decide some metric which heavily incentivizes making a guess which narrowly beats your opponent's guess, maybe with a metric such as 1/(a-b)**2. However, as the numbers will likely grow throughout the iterations, maybe 1/(a/b)**2 might be better.

Example bot whose goal is to beat opponents who pick a constant number:

def constant_beater(my_score, opp_score, my_numbers, opp_numbers):
    if len(opp_numbers) == 0:
        return 1
    return opp_numbers[-1] + 1

The largest concern I see with this challenge is a bot which just increments much quicker than all other bots so that it wins every game with a minuscule amount every time. Maybe to curb this a score that is below a certain threshold for a game is rounded to zero to encourage more competitive choices.

  • \$\begingroup\$ I feel like this would be a much better challenge if bounded a bit, from maybe 1-100 for example \$\endgroup\$ – Quintec Jan 11 '19 at 22:57
  • \$\begingroup\$ I was thinking of some sort of bounding, but I'm struggling to then find an incentive for a bot to choose anything except for the upper bound. \$\endgroup\$ – Sebastian Mendez Jan 11 '19 at 23:02
  • \$\begingroup\$ Make it a round robin tournament? \$\endgroup\$ – Quintec Jan 11 '19 at 23:19
  • \$\begingroup\$ Numbers from 1 to 100. 100 rounds between 2 bots, higher number wins, can only play each of the 100 numbers 1 time each. Score is the number of rounds won? The play method doesn't work well for difference between numbers. \$\endgroup\$ – fəˈnɛtɪk Jan 13 '19 at 1:43
  • \$\begingroup\$ This sounds extremely abusable, even more if they try to tap into the others' functions. However, it still sounds real fun, reminds me of the Robot Roulette but with much better winning chances. Maybe you could add some restriction like preventing to use the same number X amount of rounds with a maximum number cap (like @fəˈnɛtɪk said but without too much limiting) \$\endgroup\$ – Belhenix Jan 15 '19 at 22:38
  • \$\begingroup\$ Maybe instead of a maximum number cap a maximum sum cap? \$\endgroup\$ – Sebastian Mendez Jan 16 '19 at 21:44
  • \$\begingroup\$ If there's a maximum number cap I don't think there needs to be a maximum sum cap. However, there needs to be an incentive so bots don't go spamming the maximum number 24/7 (or worse, having 2 bots spam max number to infinity and ending in a 0 point tie) \$\endgroup\$ – Belhenix Jan 17 '19 at 23:23
  • \$\begingroup\$ Thinking about this: Perhaps the max is 100, and bots score 100-guess if they win, and -(guess/100) if they lose? \$\endgroup\$ – Spitemaster Jan 31 '19 at 22:20

Drawing \$K_n\$ (complete graph with \$n\$ vertices)

Tags: , ,

In graph theory the complete graph with \$n\$ vertices, often written as \$K_n\$, is the graph where every vertex is connected to every other vertex. For example, \$K_3\$ with \$V = \{A,B,C\}\$ has the edges \$\bigr\{\{A,B\},\{B,C\},\{C,A\}\bigl\}\$ - forming a triangle.


Given an even \$n \geq 4\$ you will generate/display an image of the graph \$K_n\$ as follows:

  • pick an image width \$\texttt{width} \geq 100\$
  • pick two distinct colors \$\texttt{vertex_color}\$ and \$\texttt{edge_color}\$
  • draw \$1\$ vertex with color \$\texttt{vertex_color}\$ in the middle of the image
  • draw the remaining \$n-1\$ vertices evenly distributed on a circle around it
  • connect every vertex with color \$\texttt{edge_color}\$


  • the background color doesn't matter (transparent is fine), but it must not coincide with the colors \$\texttt{vertex_color}\$ and \$\texttt{edge_color}\$
  • the radius of the circle should be \$\texttt{width/4}\$
  • the center of the circle should the middle of the image
  • the shape of the vertices doesn't matter, but they must be at least \$3\$ pixels wide
  • the edges must not overlap the vertices
  • the edges may be dashed, dotted etc.


Example output for \$K_4\$:


Example output for \$K_{12}\$:


Example output for \$K_{32}\$:


  • \$\begingroup\$ "the edges must not overlap the vertices" is incompatible with "draw 1 vertex ... in the middle of the image" when n is odd. \$\endgroup\$ – Peter Taylor Jan 18 '19 at 16:21
  • \$\begingroup\$ @PeterTaylor: Good call, thank you! Restricted the input to only even integers. \$\endgroup\$ – ბიმო Jan 18 '19 at 16:48
  • \$\begingroup\$ a bit too many rules for me but... still very interesting and fun \$\endgroup\$ – don bright Jan 31 '19 at 2:58
  • \$\begingroup\$ @donbright: What do you mean by too many rules? Since it's graphical output, I have to set rules otherwise it'll become an art contest unfortunately. I'm open to less restrictive suggestions though. \$\endgroup\$ – ბიმო Jan 31 '19 at 14:46
  • \$\begingroup\$ its just my personal taste. like i dont care how wide the image is, how wide vertices are or whether edges overlap, etc etc. i upvoted anyways. good luck. \$\endgroup\$ – don bright Feb 2 '19 at 2:55

Chain round the number!

A decimal place is a digit of a number's location in a number. In the number 987654321, each digit corresponds to its decimal place. For example, in the number 16111, the 6 is in the 4th decimal place.

Normally when rounding to n decimal places, one checks the digit at n-1 (heretofore called x). If x >= 5, then the digit at n is rounded up. Otherwise the digit at n is rounded down (stays the same). Then, all digits including and after x are turned into 0.

For example, take the number 158, rounded to the 3rd decimal place. The digit at the 2nd decimal place (3rd decimal place minus one) is 5. Because of this, the 1 at the third decimal place gets rounded up. This results in the number being 258. However, the 5 and the 8 both get turned into 0, and so the final result is 200.

Chain rounding is like normal rounding, except that you do it to every digit starting with the digit at decimal place 2. Once you round to the decimal place 2, then you round to decimal place 3, and so on until decimal place n.

For example:

Input: 24472
24472    (2 < 5, so the 7 rounds down)
24470    (7 >= 5, so the 4 rounds up)
24500    (5 >= 5, so the 4 rounds up)
25000    (5 >= 5, so the 2 rounds up)
30000    (Final answer. Non chain-rounded answer would be 20000)

The challenge here is to chain round a number to the highest decimal place possible for that number.

Test cases: (all inputs will be positive whole numbers)

24472 -> 30000
1999 -> 2000    ("1 9 9 9" -> "1 9 10 0" -> "1 10 0 0" -> "2 0 0 0")
9945 -> 10000
2001 -> 2000
9444 -> 9000
9445 -> 10000
13579 -> 10000
24681 -> 30000
1337 -> 1000
5 -> 10
1 -> 1
  • \$\begingroup\$ Good challenge, but I think this needs more explanation on what is happening. It's probably a good idea to fix an example with digits \$ab\$ and explain how the new rounding works (ie. compare \$b\$ to \$5\$ and so on), at first I did not understand where the \$5\$ comes from. You should also address how carries are treated, it's not clear atm. \$\endgroup\$ – ბიმო Jan 22 '19 at 19:17
  • \$\begingroup\$ @BMO I tried to clarify, is that better? (Thank you for the help). \$\endgroup\$ – Comrade SparklePony Jan 22 '19 at 19:56
  • \$\begingroup\$ Yes, looks good to me. Make sure to make a test-case with carries, eg. when rounding \$9996\$ or the like. And also specify whether numbers can be zero or even negative. \$\endgroup\$ – ბიმო Jan 22 '19 at 20:15

A Turtle Finds a Portal

The turtle wants to move along the grid to get to his food. He wants to know how many moves it will take for him to get there.

As well since he is slow he has teleporters set up around his domain that he will utilize if it shortens his path. Or avoid them if it lengthens his path.

Meet the turtle


The turtle lives on a grid $$\begin{matrix} X&X&X&X&X\\ X&X&X&X&X\\ X&X&🐢&X&X\\ X&X&X&X&X\\ X&X&X&X&X\\ \end{matrix}$$ The turtle can move to any adjacent square... $$\begin{matrix} X&X&X&X&X\\ X&\nwarrow&\uparrow&\nearrow&X\\ X&\leftarrow&🐢&\rightarrow&X\\ X&\swarrow&\downarrow&\searrow&X\\ X&X&X&X&X\\ \end{matrix}$$

However, the turtle cannot move to a square with a mountain $$\begin{matrix} X&🌄&X&X&X\\ X&\nwarrow&\uparrow&\nearrow&X\\ X&🌄&🐢&\rightarrow&X\\ X&🌄&\downarrow&\searrow&X\\ X&🌄&X&X&X\\ \end{matrix}$$

The turtle wants to eat his straw berry, and would like to know how long it will take to get to his strawberry $$\begin{matrix} X&🌄&🍓\\ 🐢&🌄&X\\ X&🌄&X\\ X&X&X\\ \end{matrix}$$ This example would take the turtle \$5\$ turns $$\begin{matrix} X&🌄&🍓\\ \downarrow&🌄&\uparrow\\ \searrow&🌄&\uparrow\\ X&\nearrow&X\\ \end{matrix}$$ To get around mountains the turtle uses his teleporter. There are two teleports on the grid that map to each other. Stepping on the teleporter immediately moves the turtle to the corresponding teleporter. $$\begin{matrix} 🔵&🌄&🍓\\ 🐢&🌄&🔴\\ X&🌄&X\\ X&X&X\\ \end{matrix}$$ It is now faster for the turtle to move up twice. Now the turtles shortest path is \$2\$ $$\begin{matrix} 🔵&🌄&🐢\\ \uparrow&🌄&🔴\uparrow\\ X&🌄&X\\ X&X&X\\ \end{matrix}$$

The challenge

Given an initial grid configuration output the number of moves it will take the turtle to reach his strawberry.


  • You may assume that the input grid has a solution

  • The input grid may be entered in any convenient format

  • The shortest path does not need to make use of the portal

  • The turtle cannot pass into mountain tiles

  • The turn that the turtle moves onto a teleporter square he is already on the corresponding teleporter. He never moves onto a teleporter and stays there for a move

  • You may use any ASCII character to represent mountains, turtle, empty gird square, strawberry.

  • You may use either the same character or two different characters to represent the teleporter pairs

  • A grid can have more than one path with the same shortest path length

  • Each grid will only have one strawberry and two portals

  • This is .

Test Cases formatted as lists

[ ['T', 'X', 'X', 'S', 'X'], ['X', 'X', 'X', 'X', 'X'], ['X', 'X', 'X', 'X', 'X'] ] --> 3
[ ['T', 'M', 'X', 'S', 'X'], ['X', 'M', 'X', 'X', 'X'], ['X', 'X', 'X', 'X', 'X'] ] --> 4
[ ['T', 'M', 'X', 'S', 'O'], ['O', 'M', 'X', 'X', 'X'], ['X', 'X', 'X', 'X', 'X'] ] --> 2
[ ['T', 'M', 'X', 'S', 'X'], ['O', 'M', 'X', 'X', 'X'], ['O', 'X', 'X', 'X', 'X'] ] --> 4
[ ['T', 'M', 'S', 'X', 'O'], ['X', 'M', 'M', 'M', 'M'], ['X', 'X', 'X', 'X', 'O'] ] --> 7

Test Cases formatted for humans

X X X X X --> 3

O X X X O --> 4

X X X X X --> 2

O X X X X --> 4

X X X X O --> 7


Design and structure via: Hungry mouse by Arnauld

Proposed Challenges Edit Advice: Kamil-drakari, beefster

  • 1
    \$\begingroup\$ How many teleporters at most? \$\endgroup\$ – Quintec Jan 18 '19 at 0:33
  • 1
    \$\begingroup\$ @Quintec Since they say pairs, then... only two at most, because there's no way to represent multiple pairs \$\endgroup\$ – ASCII-only Jan 18 '19 at 3:28
  • \$\begingroup\$ @Quintec. Yea one at most. I'll add to the rules. \$\endgroup\$ – akozi Jan 18 '19 at 10:13
  • 1
    \$\begingroup\$ You should clarify how diagonal moves work near mountains. The first diagram showing the basic movement options includes diagonal moves, but the example with the strawberry would only be two moves regardless of portals if a diagonal move was used. \$\endgroup\$ – Kamil Drakari Jan 18 '19 at 19:29
  • \$\begingroup\$ @kmail. Very true. Will add condition when on computer. \$\endgroup\$ – akozi Jan 19 '19 at 15:16
  • 1
    \$\begingroup\$ I would suggest taking the "gun" out of the title because "portal gun" suggests being able to place your own portals. I would also allow input to be in any convenient format rather than requiring it to be a list of lists with a predefined key. I think for your examples, you should use space and newline separated grids. And one last thing: rather than "The grid must have a possible solution to reach the strawberry", you should state "You may assume that the input grid has a solution". Good challenge though. Just a couple tweaks will make it a great challenge. \$\endgroup\$ – Beefster Jan 24 '19 at 17:46
  • 1
    \$\begingroup\$ I would like a testcase where the portal is in the way of the turtle, meaning that the turtle has to use the portal twice. Something like "TOSMO","MMMMX", "XXXXX" or "TOSXX", "MMMMX", "OXXXX" (both evaluate to 4 moves) \$\endgroup\$ – Black Owl Kai Feb 3 '19 at 20:50
  • \$\begingroup\$ @BlackOwlKai I'm considering making portals single use? Thoughts? \$\endgroup\$ – akozi Feb 3 '19 at 21:31
  • \$\begingroup\$ This is also an option and could allow some more interesting golf approaches. Also, the single-use option would make brute-force algorithms more lengthy, because they need to keep track of whether the portal has been used. Either way, it should be clarified in the rules. But I still would like to add a testcase "XXXMO", "XMXMX", "XOXMX", TMSMX", where the portal is between the turtle and the strawberry, even if portals are single-use. \$\endgroup\$ – Black Owl Kai Feb 3 '19 at 21:53
  • \$\begingroup\$ Will do. I'll add this to rules aftter I get off my bus ride. As I won't have internet to edit. Cheers, Thanks for the suggestion. \$\endgroup\$ – akozi Feb 3 '19 at 22:36
  • \$\begingroup\$ Support for the emoticons is not guaranteed, and they aren't in the fonts on my Linux system. IMO an image would be preferable. \$\endgroup\$ – Peter Taylor Feb 4 '19 at 14:36
  • \$\begingroup\$ @PeterTaylor Will do. I'll do this once home from work. If you want to try doing it now I would approve the edit. Cheers. \$\endgroup\$ – akozi Feb 4 '19 at 14:52
  • \$\begingroup\$ You have a typo on rule 6: "empty gird square" should be "empty grid square". Also, why does it need to be an ASCII character value? Why can't I use an int? \$\endgroup\$ – Beefster Feb 4 '19 at 17:33
  • \$\begingroup\$ Will fix the spelling. As far as I'm aware integers are ascii characters? \$\endgroup\$ – akozi Feb 4 '19 at 17:37
  • \$\begingroup\$ @Beefster I'll specify in the post though. \$\endgroup\$ – akozi Feb 4 '19 at 17:38

Playing Pickomino

  • \$\begingroup\$ A worked example or 2 would be useful; I missed, on my first readthrough, that we must take the highest available tile <= the score rather than any tile <= the score and was therefore confused by a couple of the test cases. Although, I'm still confused by the 3rd last one - either the output is wrong or (more likely!) I'm too tired/drunk to figure it out. Nice challenge, though :) \$\endgroup\$ – Shaggy Feb 1 '19 at 1:18

SLIPpery Packets

The Serial Line Internet Protocol is an early internet protocol, used to essentially escape any "packet END" bytes that may appear in a packet. It has since been replaced by the more sophisticated Point-to-Point protocol, however it is still preferred on microcontrollers and low-level devices due to its simplicity.

Your goal is to implement simplified encoding and decoding functions following this protocol as a function/program/subroutine/etc.

The following table lists the special bytes used:

Hex    Dec   ISO 8859-1   Abbrev  
0xC0   192   À            END      
0XDB   219   Û            ESC
0xDC   220   Ü            ESC_END
0xDD   221   Ý            ESC_ESC

(The ISO 8859-1 characters are for visualizing where non-ASCII bytes are in the string.)

Encoding follows this system, iterating through each byte:

  • If the END byte appears in the packet, write ESC, ESC_END instead
  • If the ESC byte appears in the packet, write ESC, ESC_ESC instead
  • Otherwise, write byte verbatim
  • At the end, an END byte is appended to the message, and it is returned

Some implementations, such as the reference C implementation from RFC 1055, prepend an END byte to the string to be sent. This is omitted here for simplicity.

Decoding follows in reverse:

  • If ESC, ESC_END appears in the packet, write END instead
  • If ESC, ESC_ESC appears in the packet, write ESC instead
  • Protocol violations that involve ESC followed by a "bad byte" that isn't ESC_END or ESC_ESC should be handled by writing the "bad byte"
  • The first END byte seen (not following ESC) is interpreted as the end of the packet. The decoded packet should be returned without the END byte. You are guaranteed to have at least one such END byte appear.


For encoding, input is a packet (string of bytes) and output is the encoded packet (string of bytes).

For decoding, input is a "byte stream" (string of bytes) and output is the (first) decoded packet (string of bytes).

Test cases


''                --> 'À'
'test\n'          --> 'test\nÀ'
'testÀ'           --> 'testÛÜÀ'
'teÛst'           --> 'teÛÝstÀ'
'À'               --> 'ÛÜÀ'
'ÛÜÛÝÀÛ'          --> 'ÛÝÜÛÝÝÛÜÛÝÀ'


'À'               --> ''
'testÀblah blahÀ' --> 'test'
'teÛÝstÀ'         --> 'teÛst'
'testÛÜÛÜÀ'       --> 'testÀÀ'
'ÛÀÀ'             --> 'À'
'ÛµÀ¶'            --> 'µ'


Your score is the sum of the number of bytes in your encoding and decoding functions (or programs, etc.)

I have also considered requiring functions to take a length of packet in bytes which is used in encoding and decoding (similar to RFC 1055), not requiring handling protocol violations (ex. RFC 1055), and not testing decoding packets that have an END byte as not the last byte. Your opinions on how restrictive this challenge should be are appreciated.

  • \$\begingroup\$ regex would not be too hard actually. \$\endgroup\$ – qwr Jun 20 '19 at 14:42

One circle, two inputs, eight outputs

Given the values of only two quantities from the following eight quantities ​​(the rest is unknown):

  1. Radius of circle: \$\displaystyle R\$
  2. Diameter of the circle: \$\displaystyle D=2\times R\$
  3. Circumference of the sector: \$\displaystyle C=2\times\pi\times R=\pi\times D\$
  4. Area of the circle: \$\displaystyle A=\pi\times R^2\$
  5. Angle of the sector: \$\displaystyle\alpha\$
  6. Length of arc: \$\displaystyle LA=\frac{C\times \alpha}{360°}\$
  7. Area of the sector: \$\displaystyle AS=\frac{A\times \alpha}{360°}\$
  8. Perimeter of the sector: \$\displaystyle PS=LA+2\times R=LA+D\$

compute the rest of quantities if possible, else put special output (-1, False,...) if at least one of the quantities can not be computed.


Two quantities with there values (non negative integers)


The values of the eight previous quantities (decimal with any precision or rounded integer).


In this example the inputs is the ordered list of the previous quantities. Values are integers, angles in degrees, and outputs as rounded integers.

[16, ?, ?, ?, 100, ?, ?, ?]   --> [16, 32, 100, 804, 100, 27, 223, 59]
[24, ?, ?, ?, ?, ?, ?, 58]    --> [24, 48, 150, 1809, 23, 10, 120, 58]
[28, ?, ?, ?, ?, ?, ?, 188]   --> [28, 56, 175, 2463, 270, 132, 1848, 188]
[?, 18, ?, ?, ?, ?, ?, 41]    --> [9, 18, 56, 254, 146, 23, 103, 41]
[?, 28, ?, ?, ?, ?, ?, 808]   --> [14, 28, 87, 615, 3191, 780, 5460, 808]
[?, 88, 220, ?, ?, ?, ?, ?]   --> False
[?, ?, 88, ?, ?, 84, ?, ?]    --> [14, 28, 88, 616, 343, 84, 588, 112]
[?, ?, 220, ?, ?, 66, ?, ?]   --> [35, 70, 220, 3851, 108, 66, 1155, 136]
[?, ?, ?, 50, 50, ?, ?, ?]    --> [3, 7, 25, 50, 50, 3, 6, 11]
[?, ?, ?, 254, ?, ?, 18, ?]   --> [8, 17, 56, 254, 25, 4, 18, 21]
[?, ?, ?, 707, 75, ?, ?, ?]   --> [15, 30, 94, 707, 75, 19, 147, 49]
[?, ?, ?, ?, 99, 24, ?, ?]    --> [13, 27, 87, 606, 99, 24, 166, 51]
[?, ?, ?, ?, 140, ?, 175, ?]  --> [11, 23, 75, 450, 140, 29, 175, 53]
[?, ?, ?, ?, 324, 85, ?, ?]   --> [15, 30, 94, 709, 324, 85, 638, 115]
[?, ?, ?, ?, 324, ?, 3465, ?] --> [35, 70, 219, 3850, 324, 197, 3465, 267]
[?, ?, ?, ?, ?, 66, 88, ?]    --> False


  • The input and output can be given in any convenient format.
  • Specify in the answer the special output when quantities can not be computed all.
  • Specify in the answer whether the angle is in degree or radian or other unit.
  • π can be set to 3.14 or 22/7 or 355/113 or any more precise value.
  • No need to handle invalid input values.
  • Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
  • If possible, please include a link to an online testing environment so other people can try out your code!
  • Standard loopholes are forbidden.
  • This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

Gregorian-Hijri(Islamic) Calendar Conversion


The Hijri, or Islamic calendar is a lunar calendar used in the Islamic countries to determine the dates of traditional events. The year in the Hijri calendar is usually denoted AH xxxx. The Hijri calendar has an epoch on 16 July 622 on Julian calendar.

Like other lunar calendars, in the Hijri calendar a year consists of 12 months, each month consists of 29 or 30 days. A year is thus 354 days, or in leap years there are 355. On average there are 11 leap years every 30 years.

There is a tabular variant which uses arithmetic calculations in place of astronomical observations to determine the dates. There is also a solar version of the Hijri calendar, which is used in Iran and Afghanistan.

In this challenge, only the tabular variant will be discussed.

The tabular Hijri calendar

All western dates below will be shown in (possibly proleptic) Gregorian even if the date is before 15 October 1582.

There are 12 months in each year in the Hijri calendar, with alternating 29- or 30-day periods. The odd months have 30 days, and the even months have 29 days (except for the 12th month Dhu al-Hijjah in leap years which also has 30 days). The month names are as follows (according to this Wikipedia template):

#    Name              Number of days
1    Muharram          30
2    Safar             29
3    Rabi' al-awwal    30
4    Rabi' al-Thani    29
5    Jumada al-awwal   30
6    Jumada al-Thani   29
7    Rajab             30
8    Sha'ban           29
9    Ramadan           30
10   Shawwal           29
11   Dhu al-Qidah      30
12   Dhu al-Hijjah     29 / 30 (in leap years only)

There are 11 leap years every 30 years. There are 3 versions to determine the leap years, but the most common version is to set the years with \$y\in\{2,5,7,10,13,16,18,21,24,26,29\}(\text{mod }30)\$ as leap years. (Be reminded that the calendar stars from year 1.)

The Hijri calendar has its first day (i.e. 1 Muharram 1) on 19 July 622.

As an example, we now convert the date 8 February 2019 into Hijri (Here we define a cycle to be 30 years):

  1. Date: 8 February 2019
  2. Dates from the Epoch: \$1396 \times 365 + 339 + 166 + 38 = 510083\$
    • There are 1396 (\$2019 - 623\$) full years, so \$1396 \times 365\$ days
    • There are 339 (\$349 - 14 + 4\$) leap years between 2 dates
    • There are 166 days between 19 June 622 to 1 January 623, and 38 days between 1 January 2019 to 8 February 2019
  3. Cycle: \$510083 \div 10631 = 47\text{ (cycles) and }10426\text{ (days)}\$
    • One ordinary year is 354 days and there are 11 leap years in a 30-year cycle, so total days in a cycle is \$354\frac{11}{30} \times 30 = 10631\$
  4. \$10427 - (354 \times 29 + 11) = 150\$, so this this is the 150th day of the 30th year in the 48th cycle, which is \$47 \times 30 + 30 = \text{(AH) }1440\$.
    • The subtraction has 18 \$354\$s and 11 \$355\$s, but there is not enough space to write it all.
  5. \$150 - 30 - 29 - 30 - 29 - 30 = 2\$, so this is the 2nd day of the 6th month in the year AH 1440.

As a result the complete Hijri date of 8 February 2019 is 2 Jumada al-Thani 1440.


Write a program or function that converts the (Gregorian) input date into the corresponding Hijri date.

The program or function may receive the input date in any reasonable format, but it must output the Hijri date in the format of [date] [month name] [year]. The italics above shall be ignored.

The input month and day may be 0-indexed for convenience, but you must state so if you use this convention.

You may assume that the input is always a valid Gregorian date, and is always not earlier than the Gregorian epoch of the calendar, 19 July 622.

Sample I/O

Input:  "19 July 622" / "622-7-19" / [622, 7, 19] / (622, 6, 19) (0-indexed month)
Output: "1 Muharram 1" (The epoch date)

Input:  "8 February 2019" / "2019-2-8" / [2019, 2, 8] / (2019, 1, 8) (0-indexed month)
Output: "2 Jumada al-Thani 1440" (The example date)

Input:  "12 August 2019" / "2019-8-12" / [2019, 8, 12] / (2019, 7, 12) (0-indexed month)
Output: "10 Dhu al-Hijjah 1440" (The start date of Eid ul-Adha in AH 1440)

Input:  "9 August 2021" / "2021-8-9" / [2021, 8, 9] / (2021, 7, 9) (0-indexed month)
Output: "30 Dhu al-Hijjah 1442" (The next leap day)

Winning Criteria

As this is a , shortest answer of each language wins. Standard loopholes are banned by default.

  • \$\begingroup\$ What is "47 R 10426"? \$\endgroup\$ – Adám Feb 8 '19 at 8:16
  • \$\begingroup\$ @Adám The quotient is 47, with remainder 10426. When I was in primary school I was taught like 5/3 = 1...2 and heard in western countries it'd be written as 5/3 = 1 R2 \$\endgroup\$ – Shieru Asakoto Feb 8 '19 at 8:17
  • 2
    \$\begingroup\$ This starts off really well, explicitly addressing the usual ambiguities with Gregorian calendar-related questions and the particular complications of the Islamic calendar. But for me it starts to fall apart at the example, which has a lot of unexplained magic numbers and introduces new terms like cycle. I suggest that you should take the example slower: which number in step 2 is the number of leap days? Define a cycle as (I assume) 30 Iunar years. \$\endgroup\$ – Peter Taylor Feb 8 '19 at 21:34
  • \$\begingroup\$ I also suggest that you reconsider the requirement to output month names. That really makes it two barely related challenges (a calendar conversion and a kolmogorov-complexity for an array of 12 strings) packaged as one. \$\endgroup\$ – Peter Taylor Feb 8 '19 at 21:35

Unique Skittle Pairs

This is my first question, so hopefully it's OK.

I like to eat Skittles. However, I only like to eat them in pairs, and and those pairs must not have two Skittles of the same color. Your task is to find the most pairs that you can that match these requirements.


Input (taken from standard input) is a set of Skittles formatted like so: pyyyggoooorr, where p is purple, y is yellow, g is green, o is orange, and r is red. The number of letters for each color corresponds to the number of Skittles that are that color. The only colors used in this challenge are purple, yellow, green, orange, and red. The input will always be even in length and lowercase.

Output is the most possible pairs of Skittles that I like to eat given the input. Different outputs don't matter as long as they are valid, i.e. for an input of pygo, both py go and po gy are valid outputs. Output for invalid input doesn't matter.

The output must be in the same format as the test cases.

Examples/Test Cases

Permutations of these solutions are valid. You do not have to output all valid outputs. Multiple output lines here means multiple valid outputs.

> ppyy
py py

> yggooo
yo go go

> pyygorrr
pr yr yg or
py yr gr or

> yggoor
yg go or
yo go gr
go go yr

> yggor
(anything, including no output/errors)

> gygoro
yg go or
yo go gr
go go yr

> ygoOor
(anything, including no output/errors)

> ggorrrrr
gr gr or

> pppyyygggooorrrr
py py py ro ro ro rg
po po po ry ry ry rg
py po py ro ry ro rg

Least bytes wins.

  • \$\begingroup\$ Thanks. I'd forgotten about that. \$\endgroup\$ – CG One Handed Feb 27 '19 at 19:16
  • \$\begingroup\$ I believe this is a dupe. The only differences are the slightly more inconvenient input/output of this challenge and the different group size. However, forcing the output to be the actual pairs prevents using the most dominant strategy of simply calculating the number of groups. Personally I think they are too close anyway, but some people may disagree. \$\endgroup\$ – FryAmTheEggman Mar 1 '19 at 20:14

Sort according to cyclic order

Cyclic order on a set is a function f taking three distinct elements of a set, returning bool and having following properties:

  1. If f(a, b, c) then f(b, c, a)
  2. If f(a, b, c) then not f(c, b, a)
  3. If f(a, b, c) and f(a, c, d) then f(a, b, d)
  4. One of f(a, b, c) and f(c, b, a) is true

Values of f when arguments are not distinct don't matter. You are given a list of dictinct numbers and a function f posessing the above properties when arguments are taken from the list. Your task is to arrange the numbers in such an odrer that

f(a, b, c) if and only if k > j > i or i > k > j or j > i > k

(i.e. numbers a, b, c come in that order modulo cyclic permutaion)

Score is the total number of calls to the function f on some dataset.

It's not very clear to me how to create the dataset and how to count calls to f across different languages. Is it better to just give a list of n*(n-1)*(n-2) values of f as input (and score by bytes)?

  • 1
    \$\begingroup\$ Hi and welcome to PPCG. Thank you for using the Sandbox. Please don't specify a challenge using a specific (and unstated) programming language, as many people will have a hard time understanding that. At the very least, explain the notation. \$\endgroup\$ – Adám Mar 5 '19 at 23:49
  • \$\begingroup\$ @Adám Thank you for your comment. I've removed all language-specific notation \$\endgroup\$ – Nikita Mar 6 '19 at 0:09
  • \$\begingroup\$ Is 4. OR or XOR? \$\endgroup\$ – Adám Mar 6 '19 at 5:51
  • \$\begingroup\$ @Adam 2. says that one of f(a, b, c) and f(c, b, a) is false, 4. says that one is true. Maybe it would be best to combine them into just 2. Exactly one of f(a, b, c) and f(c, b, a) is true \$\endgroup\$ – Nikita Mar 6 '19 at 20:49
  • \$\begingroup\$ Neat challenge idea. For the scoring, maybe you can ask for the expected number of calls to f on a random n-element set. It should be easy to Monte Carlo simulate scores, as long as they're different enough. One issue is that people can pick an element e and then only do queries of the form f(e,x,y), to reduce this to a standard sorting problem. \$\endgroup\$ – Lopsy Apr 2 '19 at 20:31

Data.List.nub :: Eq a => [a] -> [a]

Tags: , ,

O(n^2). The nub function removes duplicate elements from a list. In particular, it keeps only the first occurrence of each element. (The name nub means `essence'.) It is a special case of nubBy, which allows the programmer to supply their own equality test.

> nub [1,2,3,4,3,2,1,2,4,3,5]


If you ever golfed in Haskell and you kind of needed to deduplicate a list, chances are that you chose a different route or were annoyed that there seems to be no solution shorter than importing Data.List.

In this challenge you will write a function [a] -> [a] (unnamed or named) which removes duplicates from a list, the order does not have to be preserved.


Since I don't think it's possible to get something shorter than 20 bytes and Haskell sometimes is really annoying to golf with if you want to use lengthy functions, the scoring mechanism will count tokens, please use this program to count the tokens and use the generated template.

  • If your solution is a named function or operator, it must not be defined in another file/module (ie. banning imports).

  • Each solution may impose type constraints, each set of type constraints counts as its own language, compiler flags can be used without any restrictions.

  • Your solution may not assume that the input is non-empty, however if you have an elegant solution which fails on empty input, feel free to include it in your post.

How are tokens counted?

Tokens are counted by using GHC's lexer which you can import Language.Haskell.Extes.Lexer, except that newlines will count as a token too.

White space is ignored, every token of the language will count as one, no matter how long it is so ma >>= f will count as the three tokens ma, >>= and f the same holds true for string or number literals (eg. "abc" or 1.0 each count as 1).

Test cases

[] -> []
[1] -> [1]
[1,1,1] -> [1]
[3,1,1,2] -> [1,2,3]
[1,2,3,3,2,1] -> [1,2,3]
  • 1
    \$\begingroup\$ I think I'm missing something, but what stops the import Data.List;nub solution from winning with score 4? \$\endgroup\$ – xnor Mar 16 '19 at 1:26
  • 1
    \$\begingroup\$ @xnor: No you didn't, my bad. Fixed, I hope. \$\endgroup\$ – ბიმო Mar 16 '19 at 2:49
  • 2
    \$\begingroup\$ Hmm, this way it's still no good. Using nubBy (==) is still going to be hard to beat. Guess I need to ban imports completely :( \$\endgroup\$ – ბიმო Mar 16 '19 at 2:53
  • 2
    \$\begingroup\$ Yeah, I think banning imports is the way to go. I know past token-counting challenges have had "exploits" where the code payload is put into a huge string or number payload, the decompressed and executed by a general-purpose program. I don't see offhand a good way to do that in Haskell without imports though -- do you? \$\endgroup\$ – xnor Mar 16 '19 at 3:03
  • \$\begingroup\$ I tried writing a solution and the best general-type solution I got is the same as the one I'd use for golfing with imports banned, with 17 tokens. I'm unfortunately not seeing a way to take advantage of long built-ins like the scoring encourages. I see a shorter approach for a restricted type that feels both optimal and hard-to-improve to me. If you don't have some clever better method up your sleeve, I'd suggest a more complex task. Nice token-counting script by way, the number labelling makes it very clear. \$\endgroup\$ – xnor Mar 16 '19 at 3:36
  • \$\begingroup\$ @xnor: Without imports one could still embed an interpreter, I guess. I was thinking earlier about this and I think there's nothing wrong with counting literals as multiple tokens. However yeah, probably it's best to come up with a more complex task. Thanks for your feedback. \$\endgroup\$ – ბიმო Mar 16 '19 at 3:59
  • \$\begingroup\$ I don't really see how counting tokens is too much better, and it makes the challenge language specific. \$\endgroup\$ – dfeuer Mar 19 '19 at 22:26

Make a markdown Table of contents parser

A simple Code Golf challenge in the likes of the Markdown parser.

The parser should ignore normal text and other markup (without an # before it).

Some valid headers are: ### Header 3, # Header1, Text # Header

Sample input:

# Hello
Lorem # Hello2
Hi this is normal text

## This is a subheader
Lorem ipsum

### Subsub
Solor di amet

# Hello again
This is more text!

sample output:

- This is a subheader
--- Subsub
Hello again
  • 1
    \$\begingroup\$ What about ```[linebreak]# text in code[linebreak]```? Or with indentation? What about where there is no space (still formats) : #no space? Or inside quote: > # header/spoiler: >! #header? Please specify these and any other edge cases. \$\endgroup\$ – Artemis Apr 12 '19 at 15:45
  • 1
    \$\begingroup\$ I'd personally recommend trying to avoid so many edge cases. If you give a precise list of all of the cases that the parser has to care about and then just say something like "ignore any other markup" I think your challenge will be better. \$\endgroup\$ – FryAmTheEggman Apr 15 '19 at 16:10

Growth of the Jackpot (Tentative Name)

(Gauging interest)

There is a money pot that gains $1 for every player currently in the game each turn. At any time, a player can decide to take the money and run or stay in the game hoping for a larger pot. If more than one player decides to leave at the same time, the money will be divided evenly among them, rounded down, with the remainder being put back in the pot. If after 100 rounds, there are still players left in the game, they will split whatever is in the pot at that time. Whoever has the most money at the end of the game wins.

Write a bot to play this game. You will always know the size of the pot, how many players are currently playing, how many were initially in the game, and the current first place amount of money.

On the surface, the optimal strategy is to bail out on turn \$\lceil{100n \over {2n - 1}}\rceil\$ (where \$n\$ is the number of players) because that turn guarantees that nobody can do better than you. But then if everyone does that, they'll split the pot and lose, so the best action to take is not immediately obvious.

One possible variant to round limits would be to have it cost each player $1 per turn they stay in the game, with each player starting with $100 and being forced to take the money and run when they have none left to contribute. Then the game could be run for several rounds.

  • \$\begingroup\$ Kind of a one-shot form of Reaper \$\endgroup\$ – Veskah Apr 17 '19 at 19:47
  • \$\begingroup\$ I like this. It allows for multiple simple strategies, but has a lot of depth and an interesting metagame aspect. To encourage complicated answers, I would recommend having bots play a few games in a row, to allow a bot to learn optimal timings vs given opponents. \$\endgroup\$ – MegaTom Jun 23 '19 at 4:59
  • \$\begingroup\$ If a bot may play several games, is the object to win as much money as possible, or to win as many games as possible? \$\endgroup\$ – Rosie F Aug 1 '19 at 15:08

Hungry Monster 9

My first challenge. Feedback is appreciated.

A monster shaped like 2 is hungry and wants to become a 9. To do so he will eat food, that is shaped like the number 1, seven times.



It starts with a grid filled with 0, containing the digit 2, and seven times the digit 1. The 2 (aka the monster) needs to move to the closest 1. Upon "eating" the number, 2 will change to 3, and continue to move to the next closest number.

Write a program that outputs the next correct state.

Input specifications

  • The input grid is a rectangle and can be of any size. It doesn't need to be a square.
  • The input can be at any state. For example a grid with a 6 and three times 1 left.
  • The grid will contain exactly one digit higher than or equal to 2 (the "player").
  • The grid will contain seven times or less the number 1.


  • When the monster gets on the position of where a 1 is, its digit increases by 1.
  • The monsters previous position becomes 0.
  • When the monster is 9, it does not move.
  • The monster can move in 8 directions (horizontally, vertically, diagonally).
  • The monster moves to the closest 1. If there are multiple closest, you may choose any of those. It is not required to be random.

Example Input and Output

This is an example of the first 4 states (and example inputs/outputs):


The output is allowed to be an array of lines. ["0000000000", "0100000000", "0000080000"]

  • \$\begingroup\$ If there are multiple closest, it can choose any of those. Does it have to randomly choose, or can it (for example) always take the north-most? \$\endgroup\$ – AdmBorkBork Apr 19 '19 at 13:27
  • \$\begingroup\$ @AdmBorkBork It does not have to be random. Your example is allowed. Thanks, I'll make that more clear. \$\endgroup\$ – Sheepolution Apr 19 '19 at 16:45

Low diversity quine.

A low diversity quine is a quine (program that outputs it's source code) that uses a low amount of distinct characters.


As a code-golf challenge the program with the lowest score wins.

Score is calculated as: NumberOfDistinctCharacters x ByteCount


Standard quine rules apply. Most notably: No source code reading

  • 2
    \$\begingroup\$ Whitespace and brainfuck have a clear advantage :P. Also, the standard quine for a lot of languages is optimal here. Notably V. \$\endgroup\$ – Beefster Apr 20 '19 at 18:02
  • \$\begingroup\$ Pretty sure we've had (something very close to) this before, but I could be wrong. \$\endgroup\$ – Shaggy Apr 20 '19 at 23:21
  • \$\begingroup\$ @Shaggy I thought the same, but I'm not so sure anymore. I'm probably confusing it with Eww, those bytes are gross, where answers use the least amount of distinct bytes as well, but when the input contains any of the bytes in your source code, they should remain in the output. So it's related to the source code and distinct bytes, but not a quine. Alternatively I could've confused it with Write a Quine Suite, where answers contain multiple quines that share none of the same characters \$\endgroup\$ – Kevin Cruijssen Apr 23 '19 at 15:47
  • 2
    \$\begingroup\$ that uses a low amount of distinct characters usedthat uses a low amount of distinct characters or with a low amount of distinct characters used \$\endgroup\$ – Artemis Apr 23 '19 at 21:32

A Note On Frequencies

In western music, we denote "musical notes" as a letter A-G, optionally followed by a or . An "octave" is a collection of 12 notes, beginning at C, such that the frequency of any given note is double that of the same note in the octave below, and half that of the same note in the octave above. With this in mind, notes are usually denoted as /[A-G][♯♭]?\d+/, which is a "note" (letter plus optional sharp or flat) and an octave number.

In physics however, musical notes are measured as a frequency of oscillation, typically in hertz (Hz). These days, the international standard is that "Middle A" (The A note of the 4th octave) is 440hz, and all other notes are tuned relative to that.

The frequency of note \$n\$ can be calculated as such:

\$\begin{equation}f(n)=\left({\sqrt[{12}]{2}}\,\right)^{n-49}\times R\end{equation}\$

Where \$n\$ is the index of the note (A0 being 1) and \$R\$ is the frequency of A4

Calculating note indices

Indices within an octave:

C     - 1
C♯/D♭ - 2
D     - 3
D♯/E♭ - 4
E     - 5
F     - 6
F♯/G♭ - 7
G     - 8
G♯/A♭ - 9
A     - 10
A♯/B♭ - 11
B     - 12

The note index of a note (including octave) can be calculated as:

\$n + (o*12) - 9\$

Where \$n\$ is the note index as indicated by the above table, and \$o\$ is the octave number

The Challenge

Given a musical note as input, in the following format: /[A-G][♯♭]?\d+/ output the frequency of the note in hertz to at least 3 decimal places.


  • You may optionally take #b in your input as opposed to the unicode ♯♭
  • You may optionally provide the calculated frequency in millihertz (mHz), removing the need to directly handle real numbers.
  • For the purposes of this challenge, \$R = 440\$


This is so fewest bytes in each language wins!


  • Is this a dupe?
  • Is it a good challenge?
  • Should I bother requiring answers to first parse the note (eg B#7) to a note index, or just require answers take \$n\$ directly?

Sort a list using a stack and a queue

Consider an unsorted list of length n, containing the integers 1 through n. Your job is to sort them using a stack (FIFO) and a queue (LIFO) and a single register. To do this, you have access to six commands

i    Input the next integer onto the register
o    Output the value of the register
Q    Place the value of the register at the tail of the queue (enqueue)
q    Place the value of the head of the queue in the register (dequeue)
S    Place the value of the register at the top of the stack (push)
s    Place the value of the top of the stack in the register (pop)

A few examples (sorting in ascending order):

 [1 2 3 4] 

 [3 2 4 1]


Write a program or function that, given some (unsorted) list, returns a sequence of commands that outputs an ordered list. However, the number of commands should grow as \$o(n^2)\$, i.e., strictly smaller than \$\mathcal{O}(n^2)\$. That is, for sufficiently large \$n\$, you must always use less than \$cn^2\$ commands (with \$c\$ some positive constant) to sort the list.

  • The input is flexible. The list of size \$n\$ may start from \$0\$ or from \$1\$ and will always contain all integers from \$0\$ to \$n-1\$ or from \$1\$ to \$n\$ respectively. You may take \$n\$ as a separate input if desired.
  • The output is flexible. You may choose a different set of unambiguous command identifiers instead of ioQqSs. You may output as a string (which is allowed to contain superfluous characters such as delimiters, linebreaks, etc), or as an array or list of commands.
  • Your entry must indicate the worst-case output size, e.g., \$\mathcal{O}(n)\$, \$\mathcal{O}(n\log(n))\$, which must of course be strictly smaller than \$\mathcal{O}(n^2)\$.

A few notes:

  • Things like ii, qi, oo should never happen. You only have one register, and overwriting it would mean you can no longer output the full sorted list.
  • A naive approach would be to put the entire input in the queue iQiQiQ... and then cycling through the queue qQqQqQ... until the register contains the next integer in order. However, this approach would mean you have \$\mathcal{O}(n)\$ cycling commands for \$\mathcal{O}(n)\$ numbers, which would be \$\mathcal{O}(n^2)\$ and thus does not meet the complexity requirement.
  • \$\begingroup\$ The restricted-complexity tag means that your code must have a restricted complexity in at least one aspect, not that the output has a restricted growth rate. As it is, I can simply brute force and find the optimal output in all cases, but I don't think that's what you want. \$\endgroup\$ – Erik the Outgolfer Apr 29 '19 at 12:28
  • \$\begingroup\$ @EriktheOutgolfer Thanks for raising that point. I'm not sure if brute forcing will always be the shortest in byte count, so I would like to think that different approaches are still competitive. Perhaps I could change it such that the entire algorithm must run in o(n^2) (which would automatically disqualify O(n^2) output)? Or perhaps o(n^2) for the output, O(n^3) for the algorithm. What are your thoughts? \$\endgroup\$ – Sanchises Apr 29 '19 at 13:04
  • \$\begingroup\$ Unfortunately, most of the time, brute-forcing ends up being the shortest approach. :( Also, yeah, requiring the algorithm to run in o(n^2) but still managing to get O(n^2) output means the answer is... weird. However, the other problem is that your code doesn't know which commands to execute from the beginning, and I'm half-confident that o(n^2) will be enough, but not really confident. I don't think the output can really be o(n). As for the specific complexity, well... no specific opinion yet. :P \$\endgroup\$ – Erik the Outgolfer Apr 29 '19 at 13:38
  • \$\begingroup\$ Are you sure this is in \$O(n^2)\$? Something tells me the complexity might be bigger than that when all you have is a stack and a queue. You should also use LaTeX to format your big-O notation: \$O(n)\$ \$O(n \log n)\$ \$O(n^2)\$ \$\endgroup\$ – Beefster Apr 30 '19 at 0:26
  • \$\begingroup\$ @Beefster Like explained in the notes, you can do this in \$\mathcal{O}(n^2)\$ by just using the queue, but I'll have to check if \$o(n^2)\$ is possible; I'll of course check before posting. Thanks re. MathJax, I forgot this was turned back on. \$\endgroup\$ – Sanchises Apr 30 '19 at 11:27
  • \$\begingroup\$ I think you need to work out \$c\$- i.e. you should probably put a hard cap on the number of commands. The worst-case naive approach comes out to \$n(n-1) \over 2\$ cycle commands for a total of \$n(n-1) + 2n\$ total commands. You can definitely always do better than that since the naive queue-only approach worst case is a reversed sequence, which is handled trivially by the stack. \$\endgroup\$ – Beefster May 1 '19 at 19:12
  • \$\begingroup\$ BTW, I came up with the formula by noticing that it is a shrinking queue and you therefore need at most \$l-1\$ cycle commands to get to the correct element from any point in the queue. (where \$l\$ is the queue length) \$\endgroup\$ – Beefster May 1 '19 at 19:19
  • \$\begingroup\$ Also I think I have the formula off by a bit: It should be \$n(n-1) + 4n\$ since you need \$2n\$ commands for both filling and emptying the queue. \$\endgroup\$ – Beefster May 1 '19 at 19:21
  • \$\begingroup\$ In addition, skipping the queue for the first element cuts it down to \$(n-1)(n-2) + 4n - 2\$ total commands. \$\endgroup\$ – Beefster May 1 '19 at 19:25
  • \$\begingroup\$ Following this mental thread, I suggest the following rule: "For any input sequence with length \$n \geq 3\$, you must output fewer than \$n^2 + n\$ commands." \$\endgroup\$ – Beefster May 1 '19 at 19:40
  • 1
    \$\begingroup\$ Your queues work back to front compared to mine: I enqueue to the tail and dequeue from the head. Perhaps it would be cleanest to just talk about pushing to the queue, popping from the queue, pushing to the stack, and popping from the stack. \$\endgroup\$ – Peter Taylor May 2 '19 at 11:28
  • \$\begingroup\$ I'm beginning to suspect that the worst case is linear. For \$4 \le n \le 8\$ the worst case is \$4, 5, \ldots, n, 2, 3, 1\$ at cost \$6n - 10\$. \$\endgroup\$ – Peter Taylor May 2 '19 at 13:55
  • \$\begingroup\$ @PeterTaylor I was thinking the same, but I didn't have time yet to verify this. And... have you never heard about left-hand-drive queues? \$\endgroup\$ – Sanchises May 2 '19 at 15:59

Performance-Based Resource Gathering/Trading

In this KoTH, the goal is to be the bot with the highest amount of money by the end of the game. Bots perform actions to earn money in turns. There are a set number of rounds in a game, and each round allows each bot to play. In a play, bots have set number of milliseconds to run as many turns as possible, growing their crops/trees/animals, mining for materials, or harvesting materials.

Earning Money

There are four basic "professions", though bots are not bound to a specific profession. These professions require land to collect resources, and land is zoned by its owner as one profession:


Farming uses turns to plant, grow, and harvest crops. There are three crops: wheat, carrot, and cotton. Each unit of land zoned for farming can hold up to 40 crops simultaneously. There is no randomness in farming. The crops are:

  • Wheat: The most basic crop, wheat, takes 40 turns to grow. It is planted with 1 wheat seed, and grows into 2 wheat
  • Carrot: Carrots are the fastest growing crop, taking only 16 turns to grow. Carrots are planted with one carrot, and grow into 4
  • Cotton: Cotton grows very slowly, but is a valuable item in the economy. It is planted with 1 cotton seed, and produces 3 cotton in 96 turns.


Ranching uses land to raise animals, which can be used to produce meat and other goods. Ranching is only very mildly randomized. There are three animals: chickens, cows, and sheep.

  • Chickens: A chicken takes up 2.5% of the land it occupies. Chickens lay eggs once every 8-10 turns, and an egg can be hatched into a chicken in 64 turns. Chickens last 192 turns before they stop producing eggs. Chickens can be harvested for 1 meat
  • Cows: Cows do not produce items until they are harvested. A cow takes up 5% of the land it occupies, and are "mature" 144 turns after being bought. Mature cows can be harvested for 6-8 meat and 2 leather
  • Sheep: A sheep takes up 6.25% of the land they occupy. Sheep last indefinitely, and produce wool every 112-132 turns. They can be sheared for 2 wool each time this happens. Sheep do not produce anything when harvested, and never stop producing wool


Land zoned for woodcutting contains 12 spaces for trees. Woodcutting is a moderately random-based profession. There are three types of trees available:

  • Oak: Oak saplings take 120-132 turns to grow, and produce 8-16 wood
  • Cedar: Cedar saplings take 84-96 turns to grow, and produce 5-9 wood
  • Hemlock: Hemlock saplings take 240-280 turns to grow, and produce 14-22 wood


Mining is a completely random-based profession. Each turn in which the bot mines produces one of three materials:

  • Stone: Stone has a 65% chance
  • Iron: Iron has a 30% chance
  • Gold: Gold has a 5% chance

Economy/Raw Materials

You may be wondering: What do the bots do with all these materials? Well, factories can be built on land, and used to make new items. These items can be sold to NPC traders, or used by bots to improve their efficiency at a profession.

Wood: Wood is used for the creation of tools, construction of factories, and as a fuel source

Stone: Stone is used for construction and tools

Iron: Iron is used for the creation of tools and factories

Gold: Gold is highly sought after by traders

Wheat: Wheat is necessary to feed cows and sheep, as well as the creation of bread

Carrot: Carrots are necessary to feed chickens

Cotton/Wool/Leather: The Loom factory converts these materials into cloth, which is sold to traders or used to make clothes

Eggs: Eggs are necessary to make bread


There are three factories, each for a specific type of good:

Loom: The loom converts cotton, wool, and leather into cloth, and cloth into clothes. Clothes increase the amount of time to run turns by 20% per piece equipped, up to 3, for the next 5 rounds.

Bakery: The bakery converts wheat into flour. Flour and eggs are then converted into bread, which can be sold or equipped. When consumed, bread increases time to run turns by 25% for the next 2 rounds. Meat can also be consumed, but increases the time by 40% for 3 rounds.

Smithy: The smithy creates tools. These tools are: plow, trough, axe, and shovel. Each tool doubles the time for ticks in the round it is used.


This is not complete, and many numbers still need to be added or changed to make things more equal between professions. Things like land still need to be figured out, but that's what the sandbox is for I suppose. This seems a little complicated, but each bot will probably stick with either a single profession or just be a factory owner.


Dining philosopher problem

This question is motivated by the lack of concurrency related puzzles on PPCG. The goal of this question is to solve the Dining Philosophers Problem.

What is the dining philosophers problem (DPP) ?

The DPP is one of the most famous concurrency problem, used to illustrate what is a deadlock for instance.

n philosophers are dining together at a circular table. Between each philosopher, there is a fork. In order to eat, each philosopher should have two forks (one in each hand).

The problem is that, if all philosophers try to take the fork on their right, then wait until the one on their left (taken by the philosopher on their left) is available, they will wait forever.

Solving the problem is finding a strategy so that no philosopher waits forever.

Your program

Takes an input n, the number of philosophers (and the number of forks). Run n philosophers in parallel, each philosopher output its dining events.

There are 4 different dining events possible:

  1. Philosopher i takes the fork j;
  2. Philosopher i tries to take the fork j, but fails (the fork is already taken);
  3. Philosopher i release the fork j;
  4. Philosopher i eats (and leave the table/release the forks and do not compete anymore).

A trace is correct if:

  • A fork is taken by at most 1 philosopher at any time (between two events 1 for the same j, there must be an event 3 for that j).
  • A philosopher only interacts with neighbourgs forks (in events 1, 2, 3, j is i or (i+1)%n).

The output format is a sequence of events. You can choose how to represent each event, but the following is suggested:

  1. i+j
  2. i!j
  3. i-j
  4. i

A (non-golfed) C version is available here, with output in plain english. Try it online!


This is . You should, in addition, consider the following points:

  • You must solve the problem concurrently, i.e. create one thread per philosopher and use usual atomic operations. Said otherwise, you should output a trace of an execution, not compute a possible scheduling.
  • You can not rely on time to solve the problem (no such thing as: philosopher 1 waits 1 sec, philosopher 2 waits 2 sec, etc..). To generalise, you can not use the identifier of the philosopher to do something else than finding the neighbourg forks.
  • If you add a TIO link in addition to your code, you can add any thread yield (or equivalent in your language) in the TIO version, in order to emphasize non-determinism.
  • If you add a TIO link in addition to your code, you can add use an extra lock to avoid concurrency artifacts on standard output, on the TIO version. You can not use that lock to solve the problem (i.e. if we remove this lock, the solution must remain correct). In particular, you can use this lock to atomically do an event and output it.

Example: the TIO version of:

try = try_lock(fork_1)
if (try is success)

can be :

try = try_lock(fork_1)
if (try is success)

Example run

for n = 4, the following are possible outcomes (notice that both are traces generated from the same program, it happened that the scheduling was not the same on both runs):


Questions to be answered:

  • The goal is to have a concurrent implementation of the problem (i.e. the scheduling of events should not be fixed, there should be a thread per philosopher, etc.). How to emphasize that in an understandable manner ?
  • Concurrency leads to problems, such as interleaving in stdout. Here, what I have in mind is that when the philosopher thread takes a fork, it can atomically output it on stdout, in order to reflect what actually happens. Said otherwise, I'd like to propose a way to assume that the output reflects locks behavior. Another problem is that, for small n, the output is likely to be deterministic (thread i finishes before i+1 is even started). Hence I'd like to allow the programmer to add any thread_yield() (or sleep, or anything that introduce non-determinism) to break that.
  • This kind of puzzles, intended to be solve by distributed algorithms, is quite unusual on ppcg. Codegolf is a possible scoring system, but maybe there are better systems (like, the less synchronisation, etc.).
  • 1
    \$\begingroup\$ You have a typo in the introduction: each philosopher should have to forks \$\endgroup\$ – Artemis May 2 '19 at 14:20
  • 1
    \$\begingroup\$ As a puzzle this isn't interesting: the solution is too well known. Concurrency is of dubious observability: certainly it can't be determined from the output or the timing, because that can equally be done by simulating green threads with a random number generator to select which state machine advances, and that's probably golfier than using semaphores or similar. IMO this isn't a good fit for the site. \$\endgroup\$ – Peter Taylor May 3 '19 at 10:05
  • \$\begingroup\$ @PeterTaylor I don't agree with your first argument : ppcg contains a lot of problem which solution is known. Concerning the second part, I agree: not using concurrency probably leads to a shorter code. However, the point of this question is to illustrate that concurrent programming is ignored on ppcg, while it is, in everyday programming, a real problem. That is why, I think, we should find a way to integrate problems based on concurrency. Surely code-golf is not the best rule, but not all problems on ppcg are code-golf (e.g. popularity). We should suitable rules for such programs. \$\endgroup\$ – Bromind May 3 '19 at 13:32
  • 2
    \$\begingroup\$ (1) Emphasis on "As a puzzle". The presentation of this question seems to me to present it as a puzzle to be solved, and while there are questions like that on this site they tend not to be the best ones. If nothing else, once the first person solves it and posts an answer, everyone else can just copy that answer. (2) PPCG is almost the opposite of real world coding, where clarity is the most important criterion. If you can find a good winning criterion then that's great, but shoehorning a problem into a criterion which doesn't fit is to no-one's advantage. \$\endgroup\$ – Peter Taylor May 3 '19 at 17:38
  • 2
    \$\begingroup\$ I don't know much about concurrency, so I'll comment from the view of a general site member. It's weird to me that we're printing the trace which is easy to generate non-concurrently, with the hard-to-define requirement of it being generated concurrently buried underneath. I think it would make more sense for our code to implement each of the philosophers, under the requirement that simulating philosophers all running our code results them in all eating. This would mean explicitly specifying what input each philosopher gets at each step and what they can do, in a way that forces concurrency. \$\endgroup\$ – xnor May 3 '19 at 22:09

Given a position of a chess piece and another square, determine if the chess piece attacks that square


Input would be in the form

Qe4 c6

Where the first term denotes the piece and its position and the second term is the square we're interested in.

Labels for pieces are:
K - king
Q - queen
R - rook
B - bishop
N - knight
P or empty - pawn

In fact, the input could be left to be decided by the programmer, to make them creative in coming up with the most efficient input method, for example any of these could be valid, if the programmer decides so:

Qe4, c6
[Qe4, c6]

Even the order could be reversed if that makes parsing easier. Basically the input could be left completely to the programmer's liberty.


So in the above case the input

Qe4 c6

would give an output


Because the queen on e4 indeed attacks c6. Outputs like 1 or any other boolean outputs would also be allowed.

An input like

Nc3 a3

would produce


because a knight on c3 doesn't attack a square on a3.

Possible problems

There are some invalid inputs possible, like:
1. Wrong letter for a piece, like "Te2"
2. The coordinates which don't exist, like "k9"
3. The second square being the position of the piece itself, for example "Qa3 a3"

Should this be included in the rules or better not to not make it too complicated?

  • \$\begingroup\$ At least for code golf, all inputs are assumed valid because adding input validation tends to inflate scores significantly. \$\endgroup\$ – Benjamin Urquhart May 28 '19 at 17:35

Randomly produce a (name of a language) source file that is possibly a quine

Write code in any language that randomly generate a (name of a language) (Java?) source file, meeting the two criteria:

  • It must always (with probability 1) compile successfully in a (language) compiler and version of your choice.
  • It must have non-zero probability to be a quine in (language).

You don't have to make it able to generate all possible programs, and the probability doesn't have to be uniform. The objective is to write a generator shorter than the shortest possible quine in (language) compressed. Technically your code could be deterministic and generate only one program, that is a quine. But it isn't supposed to be competitive.

Your code must not have the potential to damage the computer. But it doesn't matter what the generated (language) program does when it is not the quine that qualifies your answer.

(Restrictions about compiler flags to be added.)

You could either use the built-in random functions and assume they generate true random numbers, or request random information from the input (details to be added). Your code only need to have probability 1 to terminate.

Shortest code wins.

Possible rule

You may not call any (language) compiler or anything else that could check (language) syntax.

I was thinking about C++, but there are short patterns to execute any binary machine code. The language should also have a verbose structure, and not a too short quine.

Candidates: Java, Haskell, Shakespeare Programming Language, Mornington Crescent, SQL, ferNANDo.

Or: Generate a PNG file that is possibly this image. But that may depend to much on a PNG library, and the other part is trivial.

  • \$\begingroup\$ @trichoplax The objective is to write a generator (in any language) shorter than the shortest possible quine (in a specific target language) compressed. \$\endgroup\$ – jimmy23013 May 26 '19 at 8:26
  • \$\begingroup\$ @trichoplax Yes, unless we argue about the case that is possible but has probability 0 to not terminate. \$\endgroup\$ – jimmy23013 May 26 '19 at 8:58
  • \$\begingroup\$ Do I understand it correctly that we can print a normal-ish quine, but with all its strings replaced with random strings without quotes, newlines and other offending characters? \$\endgroup\$ – the default. May 26 '19 at 9:15
  • \$\begingroup\$ As of currently, yes. I hope there are better solutions, but I'm worrying about that this is actually the best solution, and makes it trivial. \$\endgroup\$ – jimmy23013 May 26 '19 at 9:18
  • \$\begingroup\$ Is it possible to somehow restrict a Java program from destroying the computer with a finite amount of code? If so, generating all strings, trying to compile them and running them parallelly until any happens to be a quine might or might not be even shorter. \$\endgroup\$ – the default. May 26 '19 at 9:22
  • \$\begingroup\$ @someone The generator should not destroy the computer. But as of currently it doesn't disallow trying all strings. Maybe I'll forbid calling the Java compiler or syntax checker. \$\endgroup\$ – jimmy23013 May 26 '19 at 9:29
  • \$\begingroup\$ Curiously, this seems similar in concept to Solve Subset-Sum in polynomial time (…if P = NP). \$\endgroup\$ – xnor May 27 '19 at 2:38
  • 1
    \$\begingroup\$ I'm actually having trouble imagining how to beat a hardcoded quine. Generating nontrivial valid code seems hard. Maybe I'm missing something. \$\endgroup\$ – xnor May 27 '19 at 2:43
  • \$\begingroup\$ @xnor I think hardcoding a quine except for a string is most likely going to win. So I'm looking for a language that potentially allows more approaches. I may also change it to generate a program for a task other than quine. \$\endgroup\$ – jimmy23013 May 27 '19 at 2:54

Finding distinct road sections

I was recently working on a grid-based road procedural generator, and thought of a neat idea for a new challenge:

The Task

Given a square (equal width and height) 2d array in which each item is one of 2 distinct values (of your choice): grass and road (I will use _ and # in examples), output the grid modified such that each distinct segment of road tiles has had its values changed to a unique value.

Two road tiles are considered to be part of the same segment if they neighbor each other in at least 1 cardinal directions.
Diagonal neighbors are not considered to be part of the same segment (unless they are connected cardinally elsewhere)
A single road tile with no connections is considered to be its own distinct segment.

You may choose the 2 input values used, and all output values used.
"Grass" tiles must remain unchanged.

You may assume there will always be at least 1 road segment, and that the array dimensions will be no larger than 64 by 64




_ is "grass" and # is "road"




This is so fewest bytes in each language wins

Test cases



  • I feel like the task is poorly worded, but can't think of a better way to word it.
  • \$\begingroup\$ This seems really familiar, but I can't seem to find a dupe... \$\endgroup\$ – AdmBorkBork May 30 '19 at 19:55
  • \$\begingroup\$ I'm worried about the numbering - is there a defined numbering scheme? The way you have it, it starts from the bottom left and reads to top right. But most (read: ALL) programming languages read from top left to bottom right. \$\endgroup\$ – mackycheese21 Jun 6 '19 at 1:14
  • \$\begingroup\$ I would specify either the numbering relation, or that it doesn't matter. \$\endgroup\$ – mackycheese21 Jun 6 '19 at 1:14
  • \$\begingroup\$ @mackycheese21 You may choose the 2 input values used, and all output values used. \$\endgroup\$ – Skidsdev Jun 6 '19 at 2:10

Draw a regular prism


The input is a single integer i between 3 and 8.


The image of a regular prism with the two regular polygonal faces having i edges each. For example, if i=3 your code should draw a triangular prism using two equilateral triangles.


The diameter of the polygonal (i.e. triangular if i=3) faces must be at least 200 pixels as should the distance between the regular faces. You can show the image at any angle you like as long as at least two faces of the prism are visible, including one of the two regular polygonal faces.

The edges of the prism that are visible should be in black and the edges that are not visible should be drawn with dotted black lines, a dotted line being a line where in at least 3 distinct, non-connected places (meaning separated by black) there's an absence of black color.


enter image description here

enter image description here

enter image description here

  • \$\begingroup\$ You have your examples with the bases aligned. Is that required for output? \$\endgroup\$ – AdmBorkBork May 30 '19 at 19:35
  • \$\begingroup\$ @AdmBorkBork No. Unless you think it should be? \$\endgroup\$ – user9207 May 30 '19 at 20:29

Moved to Make Gimbap cutter

  • \$\begingroup\$ I don't understand how your last test case follows your rules (and other test cases), since I only see two valid Gimbap, @) and @))) in the input. \$\endgroup\$ – AdmBorkBork Jun 7 '19 at 12:55
  • \$\begingroup\$ @AdmBorkBork There is two valid Gimbap, @) and @))), than split them to @) and @) @) @). So output is @) @) @) @). I'm not that good at English, though. Can you suggest me the way to make question clearer? \$\endgroup\$ – LegenDUST Jun 7 '19 at 13:01
  • \$\begingroup\$ Oh, so the output is only the valid Gimbap? That makes more sense. Will the input ever contain anything other than @ or )? I would recommend it doesn't. \$\endgroup\$ – AdmBorkBork Jun 7 '19 at 13:04
  • \$\begingroup\$ @AdmBorkBork Input is made with only @ and ). \$\endgroup\$ – LegenDUST Jun 7 '19 at 13:06
  • \$\begingroup\$ Would )))@) be a valid input? \$\endgroup\$ – Luis felipe De jesus Munoz Jun 7 '19 at 20:43
  • \$\begingroup\$ @LuisfelipeDejesusMunoz It would. Then output will be @). I'll add that to example. \$\endgroup\$ – LegenDUST Jun 8 '19 at 4:14
  • \$\begingroup\$ So in other words: count all )s which occur after the first @ and output that many @) separated by spaces? \$\endgroup\$ – Peter Taylor Jun 12 '19 at 13:51
  • \$\begingroup\$ @PeterTaylor Yup. But I moved it into main site. \$\endgroup\$ – LegenDUST Jun 12 '19 at 13:56
  • \$\begingroup\$ When you do that you should edit the sandbox post to just be a link to the question on the main site, and then delete it, as described in the second paragraph at the top of this page. \$\endgroup\$ – Peter Taylor Jun 12 '19 at 14:11
  • \$\begingroup\$ @PeterTaylor Thanks you. I'll edit my posts. \$\endgroup\$ – LegenDUST Jun 13 '19 at 5:37

Draw an Image on the screen efficiently

Imagine you have a special rectangular screen made of square pixels. It consists of \$n\$ rows and \$m\$ columns. For every row and every column there is one swich (so \$n + m\$ switches in total). To turn a certain pixel on - let's say at position \$(i,j)\$ - we can press switch \$i\$ (of the row switches) and switch \$j\$ (of the column switches) at the same time.

As soon as some pixel has been turned on, it stays on, even if we press the same combination of switches again. META: Is this a good idea? Or should we say that each pixel should be turned on exactly once and may not be activated again?

But we can also press an arbitrary number of switches at the same time: Lets say we press switches \$0,2,3\$ of the row switches and \$1,5\$ of the column switches, then all the pixels \$(i,j)\$ with \$i \in \{0,2,3\}\$ and \$j \in \{1,5\}\$ will get turned on, so all the pixels \$(0,1),(0,5),(2,1),(2,5),(3,1),(3,5)\$.

If we now want to draw a picture on the screen you could do that pixel for pixel, and we'd need \$n \cdot m\$ actions in the worst case - that is, when we have to turn on every pixel. But as we can press an arbitrary number of switches at the same time, we can do better than that. We can for example do row by row: This means we select one switch for the current row, and all necessary column switches to activate all the pixels we need for this row, so in total we would need \$\min\{n,m\}\$ actions. But can we do better than that?

The task is now to write a program that given some black and white image computes a shortest sequence of actions (=simultaneous switch activations) that turns on exactly all the white pixels of the given image.


  • You can also take a matrix/list of lists as input, or a list of the coordinates of the active pixels.
  • You can additionally take the size \$(n,m)\$ as an input (or \$(n-1,m-1)\$ if you prefer.
  • The output is also flexible: You can represent every action as a list of two lists with the corresponding indices of the switches where each of the indices are in \$\{0,1,\ldots,n-1\}\$ or \$\{0,1,\ldots,m-1\}\$ respectively (or also 1-based indexing is fine), or alternatively you enumreate all switches as \$\{0,1,2,\ldots,n+m-1\}\$ and use just one list to represent this action.

    Alternatively you can also just use lists of size \$n\$ and \$m\$ (or one of size \$m+n\$) with truthy and falsey values representing the switches that get activated.

Related: Matrices Generated Using Rectangles

  • 1
    \$\begingroup\$ It may be worth clarifying that the switches don't stay on after an action (i.e. we don't spend actions deactivating them). I'm not sure if it was the use of the word "switch" over "button" that made me think this would be the case but it may be worth running it past some other people. \$\endgroup\$ – FryAmTheEggman Jun 4 '19 at 19:07
  • \$\begingroup\$ @FryAmTheEggman Thanks a lot for the effort of going through this draft! Is "button" used more for switched that just make a momentary contact? To be honest the alternative challenge that include also switching off the switches would maybe be even more interesting! \$\endgroup\$ – flawr Jun 4 '19 at 19:19
  • \$\begingroup\$ There are probably quite a few variations of this that would be fun (I'm still thinking about your meta question)! In any case, where I live I think that is the case in that most people would say my laptop has a power button, but the room I'm in has lights controlled by a switch. \$\endgroup\$ – FryAmTheEggman Jun 4 '19 at 19:27
  • \$\begingroup\$ Maybe add restricted-complexity, if this is even possible in polynomial time? \$\endgroup\$ – lirtosiast Jun 16 '19 at 8:05

Cumbersome IO format

The cops' task is to write a program in language A to solve (task about integer lists 1) and a program in language B to solve (task about integer lists 2). The second program must be able to use the output of the first program.

Others could golf your programs. Highest (C + total length of your programs) / (C + minimum total length of the programs without the restriction) wins. (C is a fixed constant to be chosen.)

(Details to be written. The format would be similar to The Bowlers-Golfers Fraction War. Minimum lengths of the two parts would be taken from other challenges.)

  • \$\begingroup\$ Would a pair of languages that both implicitly eval input and uneval output (and since it's a integer list, pretty much all golfing languages I know of work like that for lists) work as a optimal (besides the program itself) solution? What does "program length" in the score formula stand for? The score seems to always be 1 to me. \$\endgroup\$ – the default. Jun 13 '19 at 15:17
  • \$\begingroup\$ @someone Highest score wins. This is a bowling challenge to find two languages which work the worst with the other one's IO format. But I think this may not work well, as there isn't much to do after you finds the languages. \$\endgroup\$ – jimmy23013 Jun 13 '19 at 16:40

Moved here

  • 3
    \$\begingroup\$ It would be good to include the words "diameter" and "graph". I don't think this particular graph statistic has been the subject of a question before, but it could well come up again in the future and then those search terms would make it easier to use this as a dupe target. \$\endgroup\$ – Peter Taylor Jun 19 '19 at 11:53

Digit Sum of Sum of Digit Sums

Input: An integer from 1 to 1000 (known as N) Expected behavior: The code will go through the first N integers, and work out the digit sum for each integer, the code will then take these digit sums and add these together. The code will then take this total and work out the digit sum for that number. The final number is the expected output.

Example 1:

Input: 12

Output: 6


1) Numbers
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12
2) Digit Sums
1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3
3) Sum of Digit Sums
4) Digit Sum of Sum of Digit Sums

Example 2:

Input: 20

Output: 3


1) Numbers
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20
2) Digit Sums
1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 2
3) Sum of Digit Sums
4) Digit Sum of Sum of Digit Sums

There are no restrictions on language type as long as the standard loopholes are avoided. Please demonstrate your code using the last three digits of your current reputation score.

This is code-golf, the shortest number of characters in code will be deemed the winner. In the event of a tie, the one with highest popular answer will be crowned the winner. If both answers are tied in terms of popularity and size, a fight to the death will be used to declare the winner (just kidding...)

  • 1
    \$\begingroup\$ Why would anyone want to do this? Motivation is part of a good question. \$\endgroup\$ – Peter Taylor Jun 20 '19 at 8:01

Gitify a graph

Given a undirected connected graph, create a git repository with a commit graph that is isomorphic to the input graph.


  • This is just a rough idea: I first should think about what kind of graphs can actually be represented in a git repository. (the input format could be flexible: take an adjacency matrix or e.g. a list of edges or maybe some native graph structure)
  • another idea would be following: given some \$n =1,2,3,\ldots\$ create complete graph of \$n\$ nodes
  • \$\begingroup\$ Should adjecency read adjacency? \$\endgroup\$ – Jonathan Frech Jun 19 '19 at 22:38
  • \$\begingroup\$ @JonathanFrech yes, thanks a lot! \$\endgroup\$ – flawr Jun 20 '19 at 12:33


When dealing with data in two dimensions, data scientists looove to see straight lines emerge, as they can use a simple linear regression to model it - meaning we assume it is in the form of y=mx+b, and all that's left is to find the best m and b to describe the data.

There are several ways to fit a line to any data (I saw there was a challenge with Ordinary Least Squares once), however one of the most flexible one is gradient descent.

When given vectors X and Y, we start with an initial guess of m and b, then iteratively update them, and hopefully we get a better fit when we're done.

We give a "grade" to our current fitted line with mse (the lower the grade - the better the fit):

loss = mean((y - (m * x + b)) ** 2 for x, y in zip(X, Y))

And in each iteration we change m and b using the gradient of that same grade:

b -= 2 * alpha * mean((m * x + b) - y for x, y in zip(X, Y))
m -= 2 * alpha * mean(((m * x + b) - y) * x for x, y in zip(X, Y))

Here alpha is the learning rate (usually smaller than 1), used to keep the steps small enough to advance towards the minimum grade, rather than overstepping it.

The last question asked is when should we stop these iterations. We (a bit arbitrarily) impose two conditions:

  1. The absolute relative change in the grade between two iterations abs(grade1 - grade2)/grade1 is changed by less than some given epsilon, and/or
  2. A given number of iterations N has been performed already.

p.s. I started by assuming the data is just y(x), however this method may be easily extended to an arbitrary number of free variables and one dependent variable.


Write a program that accepts inputs: X, Y, m, b, epsilon, N and returns the updated m and updated b after performing gradient descent as described.

corner cases:

  • X and Y may be empty, in which case m and b are returned unchanged.

This is code golf, so shortest code in bytes wins.

  • \$\begingroup\$ This is in need of a woked example and a fee test cases. \$\endgroup\$ – Shaggy Jun 22 '19 at 22:17
  • 1
    \$\begingroup\$ What does mean mean? What does zip mean? Those should be made clear, just like you made alpha clear. \$\endgroup\$ – AdmBorkBork Jun 25 '19 at 12:44
45 46
48 49

You must log in to answer this question.

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