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

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

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

# Successive operator sequences code-golfmatharithmetic

A successive operator sequence (made up terminology) is a sequence of the form $$\a(n + 1) = a(n) \text{ op } n\$$ where op cycles through a set of operators and $$\a(n)\$$ represents the $$\n\$$th term of the sequence.

For examples, if we set the operators to addition, multiplication and subtraction and $$\a(1) = 1\$$. then we will get the following sequence (which is also A047908):

a(1)                    = 1
a(2) = a(1) + 1 = 1 + 1 = 2
a(3) = a(2) * 2 = 2 * 2 = 4
a(4) = a(3) - 3 = 4 - 3 = 1
a(5) = a(4) + 4 = 1 + 4 = 5
a(6) = a(5) * 5 = 5 * 5 = 25


## Task

Write a program/function to output the $$\n\$$th term of a successive operator sequence given its initial term and operators.

Operators your program/function must support:

• multiplication
• addition
• subtraction
• integer division (rounded towards negative infinity)

## Input Format

The operators are inputted as a string or array of character where each character represents an operator, you may choose your own mapping of character to operator.

## Scoring

This is so shortest bytes wins.

## Testcases

# first term, operators, n  ->  nth term
0,   ["+", "-", "*", "/"], 6   ->  4
1,   ["+", "*", "-"],      1   ->  1
1,   ["+", "*", "-"],      3   ->  4
1,   ["+", "*", "-"],      10  ->  199
1,   ["*", "+", "-"],      7   ->  -1
50,  ["*", "+", "-"],      1   ->  50
50,  ["*", "+", "-"],      4   ->  49
-10, ["*", "/", "-"],      5   ->  -32
-10, ["*", "/", "-"],      3   ->  -5
1,   ["+", "+", "*"],      5   ->  16
2,   ["+", "*"],           5   ->  36
0,   ["+"],                3   ->  3


Inspired by the sequence A047908

• Suggested test cases: only one operation; duplicate operations (like ["+","+","-"]); more than 4 operations. Also, should integer division round toward zero, toward negative infinity, or something else? – Zgarb Jul 18 '20 at 19:10
• Does each string have to be one byte? – fireflame241 Jul 19 '20 at 19:26
• @fireflame, they have to be a single character not a single byte. – Mukundan314 Jul 20 '20 at 15:23
• Why rounding division towards negative infinity? A lot of languages round integer division towards zero and this will add complexity just to do that. Notice that A047908 doesn't use division at all so why add it and make it a problem? Maybe even make it optional which way your answer does it as long as it's stated. – Noodle9 Jul 27 '20 at 17:59

# CoGo Rally

There's a game called Robo Rally, in which players "program" their robots five moves ahead, then simultaneously perform the moves, one at a time. The robots move over a "factory floor" grid, with the aim being to reach certain points on the board, in sequence, before the other robots do the same.

# Game Rules

For the purposes of this challenge, the rules will be simplified as follows:

• Each robot starts with 6 lives
• Each robot has a different, randomly assigned starting position (out of a fixed set of starting positions)
• The aim of the game is to reach all three checkpoints in the assigned order, before any other robot does the same.

## Movement Options

Each turn, your robot can make any one of the following movements:

• Rotate Clockwise 90 degrees
• Rotate Counter-clockwise 90 degrees
• Rotate 180 degrees
• Move Forward One
• Move Forward Two
• Move Forward Three [can only be used once until the next checkpoint is met]
• Reverse One (and stay facing the same way)
• Stay Still and gain 1 life, up to the maximum of 6

Your moves are pre-programmed in blocks of five, so choose carefully! The board may well be in a very different state in five moves time to what you think it will be.

Additionally, each movement is assigned a priority from 1-100. When you choose your block of five movements (you may use each movement any number of times, except the "move forward three", to form your five total movements) and the order they will occur in, you are also given five random numbers 1-100 to assign - one to each movement. Higher numbers will take priority where movements would cause two robots to enter the same space, for example.

## Board Items

The board contains the following items:

• Floor - the default tile on the board. No special effect.
• Walls - block a robot's path. If a robot moves forward or backward into a wall, it wastes that move (i.e. stays still, but doesn't gain a life). If the robot used "Move Forward Two", for example, it may be possible that the Robot can only move Forward One, and then stops infront of a wall, wasting the second part of the movement.
• Laser gun - fire in a straight line in a specific direction until they hit a wall or a robot. If a robot is ontop of a laser gun, it will be hit but the laser won't fire further. While moving forward two or three, a robot may pass over the path of a laser gun without being affected by it.
• Conveyor Belts - at the end of a turn (single movement option), a conveyor belt will move the robot one space in the direction the conveyor is pointing. Doesn't block lasers. Conveyor belts NEVER ROTATE ROBOTS, even if they move the robot in a different direction to the one it is facing. While moving forward two or three, a robot may move over a conveyor belt without being affected by it.
• Checkpoints (1,2,3) - act as a save point on the Robot's path and also heals all of a robot's lives and resets their use of the "Move Forward Three" action, the first time the checkpoint is visited. Checkpoints must be visited sequentially to be activated. Acts as a piece of floor in all other respects. Robots must END THEIR TURN ON THE CHECKPOINT, after interaction with other Robots; and not just pass over it.
• Holes - move the robot back to the previously visited checkpoint, or start position. Robot loses half its remaining life, rounded down. Holes act immediately, as soon as the robot enters the space - it doesn't wait for the "board interactions" part of the turn order.

## Interactions

Objects interact as follows:

• If a Robot moves into a space where another robot already exists, the other robot is shoved (moved) in the direction that the first robot was moving, one space; unless there is a wall or laser in the way. This effect may stack if multiple robots are in a line (i.e. all robots are shoved one space). This may cause a robot to fall into a hole or onto a conveyor belt.
• Moving off the edge of the board has the same effect as moving into a hole
• If a Laser fires and hits a robot, the robot stops the laser beam, and takes one damage.
• If a robot is facing another robot in a straight line with nothing blocking in between (i.e. no walls or other robots), the target robot takes 1 damage
• Therefore If two robots are facing towards each other with nothing blocking in between (i.e. no walls or other robots), both robots take one damage.

## Turn Order

1. determine (program) 5 movement options
2. determine Priorities (1-100) for these five turns
3. The programmed actions occur:
a. The first movement occurs for each player, in priority order from highest to lowest. Holes are acted on immediately (a robot cannot pass over a hole).
b. Robot Interactions are resolved (e.g. if one robot shoves another one)
c. Board Items act (lasers, conveyor belts, checkpoints)
i. If a robot loses all of its lives, it returns to the previous checkpoint (or start) with half lives (rounded up) and must sit out the remainder of the round d. Robots fire
i. If a robot loses all of its lives, it returns to the previous checkpoint (or start) with half lives (rounded up) and must sit out the remainder of the round e. Repeat for the remaining 4 movements
4. Repeat until one robot has reached all three checkpoints sequentially, or all robots have lost their lives

# The Challenge

Your robot must take the board (as a 2D array), and a seed for the Random number generator; and play the game on the given board.

The board is guaranteed to be solveable (there will always be a path from the start to each of the checkpoints)

# Sample Board  The above board would be represented in an array as follows:

[0,0,0,0,0,0,0,0,0,0,0,0]
[0,0,0,0,0,0,0,0,0,0,0,0]
[0,0,0,0,0,0,LU,0,0,0,0,0]
[0,0,0,0,0,LL,2,LR,0,0,W,0]
[H,CL,CL,CL,CL,CL,CL,CL,CL,CL,0,0]
[0,0,0,0,0,CR,CR,CR,CR,CR,CR,H]
[0,W,0,0,0,0,0 ,0,0,0,0,0]
[0,W,0,0,0,0,W,0,W,0,0,0]
[1,W,0,0,0,0,CR,CR,CD,0,W,3]
[0,W,CR,CR,CR,0,CU,H,CD,W,0,0]
[0,LL,CR,CR,CR,CR,CU,CU,CL,0,0,0]
[0,0,S,S,S,S,0,0,W,0,0,0]


Where

Cx = Conveyor (x=Up, Down, Left, Right)
Lx = Laser gun (x=Up, Down, Left, Right)
S = Start
1,2,3 = Checkpoints
W = Wall
H = Hole
0 = Floor



# Sandbox Questions

Should this be , where you implement your robot in the least code possible; or , or something else? If KotH, I've never set one before so some advice would be appreciated!

• (if this is code golf) is it guaranteed that there exists a solution on every boards? Or only boards such that a solution exists are valid input? – user202729 Jul 28 '20 at 10:38
• Whether KotH or codegolf, the board will always be solvable (i.e. In all cases all of the checkpoints will be accessible, and there will be at least one path from any starting point to each of the checkpoints) – simonalexander2005 Jul 28 '20 at 10:40

# Paper folding. Posted HERE

• Now that this has been posted to main, could you delete this proposal to create more space for new answers? – caird coinheringaahing Sep 25 '20 at 0:48

# The Dungeon Number Sequence code-golfnumberbase-conversion

### Introduction

The dungeon numbers are introduced by Numberphile, denoting a chain of base conversions. A dungeon number is denoted in the form $$a_{b_{c_{d_\cdots}}}$$ where all numbers involved are integers with at least two digits. When interpreting the values, each base conversion $$\a_b\$$ is treated as from base $$\b\$$ to base-10.

There are two types of dungeons, one starting from $$\10\$$ to $$\n\$$ from top to bottom, i.e. $$10_{11_{12_{\cdots_n}}}$$ increasing $$\1\$$ for each deeper layer, and one starting from $$\n\$$ to $$\10\$$ from top to bottom, i.e. $$n_{(n-1)_{(n-2)_{\cdots_{10}}}}$$ decreasing $$\1\$$ for each deeper layer. Each dungeon has two interpretations, top down, i.e. $$(((10_{11})_{12})_\cdots)_n$$, and bottom up, i.e. $$10_{(11_{(12_{(\cdots_n)})})}$$, producing 4 dungeon number sequences in total.

### Example

Considering $$10_{(11_{(12_{13})})}$$. The conversion is bottom up. First $$\12_{13}\$$ is converted to $$\15_{10}\$$. Then $$\11_{15}\$$ is converted to $$\16_{10}\$$. Finally $$\10_{16}\$$ is converted to $$\16_{10}\$$, and this is the value for $$\n=13\$$.

### Challenge

Write a program or function, given an integer $$\n>=10\$$ as input, output either the value of the dungeon number sequence at $$\n\$$, or the whole sequence from $$\10\$$ up to $$\n\$$ inclusive. You may choose any sequence from the 4 sequences, but you must state which you have chosen. You must not hardcode the values; your code must work theoretically for all integer $$\n>=10\$$.

### Values

n                                  10  11  12  13  14  15  16  17   18   19    20
---------------------------------------------------------------------------------
Type 1 (((10_11)_12)_...)_n        10  11  13  16  20  30  48  76  132  420  1640
Type 2 10_(11_(12_(..._n)))        10  11  13  16  20  25  31  38   46   55    65
Type 3 (((n_(n-1))_(n-2))_...)_10  10  11  13  16  20  28  45  73  133  348  4943
Type 4 n_((n-1)_((n-2)_(..._10)))  10  11  13  16  20  25  31  38   46   55   110


### Sample IO

• Type 1 ($$\(((10_{11})_{12})_\cdots)_n\$$)

15 => 30
20 => 1640
25 => 19563802363305

• Type 2 ($$\10_{(11_{(12_{(\cdots_n)})})}\$$)

15 => 25
20 => 65
25 => 943

• Type 3 ($$\(((n_{(n-1)})_{(n-2)})_\cdots)_{10}\$$)

15 => 28
20 => 4943
25 => 1092759075796059

• Type 4 ($$\n_{((n-1)_{((n-2)_{(\cdots_{10})})})}\$$)

15 => 25
20 => 110
25 => 3577


### Winning Criteria

This is a challenge, so shortest code for each language wins. No default loopholes.

# Posted: Antisymmetry of a Matrix

• Mathematica: AntisymmetricMatrixQ (of course, a non-built-in solution can be much shorter). – the default. Jul 30 '20 at 13:12

# LaTeX Fractions

Inspired by a TeX SE question.

LaTeX uses \frac{a}{b} to represent a/b, which is very unintuitive. Now you have a piece of paper (as in "research paper") which happens to use the a/b format, and your task is to convert it to the LaTeX format.

[to be continued]

• @RahulVerma Nested fractions? – null Aug 10 '20 at 13:17

# How Many Notches Are On Texas Red's Pistol?

The song, Big Iron, by Marty Robbins, is about an Arizona Ranger who rode into the town of Agua Fria to take the outlaw Texas Red alive (or maybe dead), armed with only the Big Iron (a .45 revolver) on his hip. Texas Red, despite being only 24 years old, is extremely dangerous, having already taken out 20 men who have tried to go after him. As a point of pride, he's carved out a notch on his pistol for each one. The song counts the notches on Texas Red's pistol as "one and nineteen more". After listening to the song a couple times, two questions crossed my mind:

1. What about the other numbers that add up to twenty?
2. What if the Ranger wasn't the 21st person to try?

## The Challenge

Given a positive integer, N, the total notches on Texas Red's pistol, and another number A (also an positive integer), output a number B such that B + A = N. In the context of the song, it should read "A and B more".

## The Catch

The song still has to be intact without sub-dividing any beats. That is, the number of syllables in the phrase "A and B more" must add up to 5. If it doesn't, output the string "oops". You may assume

• 0 < A < N < 20
• 1 < N

## Examples

N   A   B (output)

20  1   19   ("One and nineteen more.")
19  2   oops ("Two and seventeen more" has 6 syllables)
11  7   4    ("Seven and four more.")


## Syllable Counts

The numbers, from one to nineteen, have syllable counts as follows: one (1), two (1), three (1), four (1), five (1), six (1), seven (2), eight (1), nine (1), ten (1), eleven (3), twelve (1), thirteen (2), fourteen (2), fifteen (2), sixteen (2), seventeen (3), eighteen (2), and nineteen (2). No synonyms are accepted, such as "aught more" for "zero more".

## Scoring

: Shortest code in bytes wins. Standard loopholes apply.

### Meta Stuff:

I hope this is interesting enough. I thought just a normal subtraction problem would be too boring.

Is "oops" a good distinguishing output?

# Show an integer, in digits of your choice

## Input

A string representing digit characters, and a nonnegative integer.

## How?

We shall show the integer in positional notation, where the string has the digit characters. Assuming the string is zero-indexed, the $$\n\$$th character shall represent $$\n\$$. The length of the string is the base.

For example, "0123456789" will show the integer in the standard decimal representation.

## Rules

• The string is assumed to have at least 2 characters.

• Invalid inputs fall in don't care situation.

## Examples

Beware of the zero!

### Binary representation

Given "01" as the string:

$$\begin{array}{c|c} 0 & “0” \\ 4 & “100” \\ 8 & “1000” \\ 15 & “1111” \\ 16 & “10000” \\ 23 & “10111” \\ 42 & “101010” \end{array}$$

### Devanagari representation

Given "०१२३४५६७८९" (U+0966 – U+096F) as the string:

$$\begin{array}{c|c} 0 & “०” \\ 4 & “४” \\ 8 & “८” \\ 15 & “१५” \\ 16 & “१६” \\ 23 & “२३” \\ 42 & “४२” \end{array}$$

### Duodecimal representation

Given "0123456789↊↋" (The last two characters are U+218A and U+218B) as the string:

$$\begin{array}{c|c} 0 & “0” \\ 4 & “4” \\ 8 & “8” \\ 15 & “13” \\ 16 & “14” \\ 23 & “1↋” \\ 42 & “36” \end{array}$$

## Ungolfed solution

### Haskell

showIntArb :: String -> Int -> ShowS
showIntArb "" _ = error "showIntArb: No given digit"
showIntArb (d:_) 0 = showChar d
showIntArb ds n = let
appendDigit ints = if length ints <= n
then appendDigit $do d <- ds int <- ints return (d : int) else ints in showString (appendDigit (fmap return ds) !! n)  • so this is a base encoding question, with symbol replacement, right? – Razetime Sep 14 '20 at 17:43 • @Razetime Yes, exactly. – Dannyu NDos Sep 14 '20 at 22:51 # Haiku Quine A haiku is a type of poetry originating from Japan following a simple pattern: 5 syllables on the first line, 7 syllables on the second, and 5 syllables on the third. Traditionally, haikus also include some reference to nature or seasons, but we'll ignore tradition for the sake of this challenge. Your task is to create a quine which has some reasonable pronunciation in the form of a haiku. For example, consider this loophole-abusing (and thus non-competing) Python quine: 0+0 with open(__file__) as fp: print(fp.read())  To be read as: ze-ro plus ze-ro with o-pen file as F P print F P dot read  # Rules and Scoring This is , so the shortest code wins. • Standard rules and banned loopholes apply • Include a reasonable haiku pronunciation alongside your code (yes, this is inherently subjective and open-ended) NOTE: may be better as a • what's the standard for xxd output here? – Razetime Sep 15 '20 at 3:34 # Convert A String To Shorthand Shorthand has been used for hundreds of years to compress and speed up the speed at which someone can write down what is said. It does this using several abbreviating methods; three of which will be used here to compress a sentence. ## Challenge When given a sentence, alongside a set of 'briefs', 'prefixes' and 'suffixes' (defined below), print or return the sentence in its compressed form. ### Definitions • Brief: A word that can be entirely substituted by another string of characters. I.E. Would: D, Be: B, Able: Ab. "I would be able...": "I D B Ab • Prefix: The beginning of a word that can be substituted by another string of characters; the prefix will either be joined or dis-joined. After(Joined): Af. Afternoon = Afnoon. Enter/Inter/Intra(Dis-joined): N. Internet = N-net • Suffix: The ending of a word that can be substituted by another string of characters; the suffix will either be joined or dis-joined. ful/ify(Joined): F. Clarify = Clarf ification(Dis-joined): F. Clarification = Clar-f ### Input Structure 1. The first input will be the sentence to be converted 2. The second input is a collection of the briefs. Each brief is a collection itself, in which the first element represents the shortened form of that brief, while the rest of the elements are all strings that map to the brief. Example: [ [d, would], [m, much, more], [a, at, an] ] 3. The third and fourth inputs are collections of prefixes and suffixes. The first element of each prefix/suffix is the shortened form, the second element is a flag (of your choosing) that represents whether it is joined or dis-joined. Everything else are the strings that match the prefix/suffix. Prefix: [ [af, true, after], [n, false, enter, inter, intra] ] Suffix: [ [f, true, ful, ify], [f, false, ification] ] Sample Input: "a shipment of letters was delivered to the postshop", [["of", "o"], ["t", "to"], ["was", "os"], ["the", "th"]], [["sh", false, "ship"], ["d", true, "de"], ["po", false, "post"]], [["rs", true, "ers"], ["m", true, "ment"], ["d", true, "ed"]]  ## Rules, Assumptions and Freedoms • You may assume all input is lowercase letters. • A brief will always take priority over prefixes and suffixes. • you can indicate a dis-joined suffix/prefix however you wish, as long as you mention how you are indicating it. • The input may be rearranged however you like, as long as you specify how your input is structured • Output may be returned, printed or the nearest equivalent. ## Test Cases "a shipment of letters was delivered to the postshop", [["of", "o"], ["t", "to"], ["was", "os"], ["the", "th"]], [["sh", false, "ship"], ["d", true, "de"], ["po", false, "post"]], [["rs", true, "ers"], ["m", true, "ment"], ["d", true, "ed"]]  a sh-m o lettrs os dliverd t th po-shop "shorthand was once a common skill among woman", [["was", "os"]], [["sh", false, "ship", "short"], ["cm", true, "com"]], [["mn", true, "mon", "man"]]  sh-hand os once a cmmn skill among womn" "the electrician will be able to fix it", [["th", "the"], ["l", "will"], ["b", "be"], ["ab", "able"], "t", "to", "it"]], [["el", false, "electr"]], [["sh", true, "cian", "sion"]]  th el-ish l b ab t fix t • Looks like a nice challenge, I don't think there's much that needs to B clar-f-ed – Redwolf Programs Sep 7 '20 at 14:12 # Keep the symmetry SANDBOX: I am aware that the language in this challenge, as it stands, is quite... fluffy. If anyone could help me firm it up, I would be grateful. Also, would this be better as a cops-and-robbers style challenge, where the cops are trying to make the output more symmetrical, and the robbers make it less symmetrical? Given a 2D array of 1s and 0s, flip a 1 to a 0 and output the resulting array. The output array must be "closer to being symmetrical" than the input. In the case where the array is already symmetrical, it must still flip a 1 to a 0, breaking as little symmetry as possible - e.g for 1,0,1 1,0,1 1,0,1  In the above case, changing the top-left 1 to a 0 will break symmetry in both directions, whereas changing the middle-left 1 will only break symmetry one way. The output must be in the same form as the input (so that your program or function could take it in again). ### What is symmetry? I am talking about reflectional symmetry along both the horizontal and vertical axes. Where the array has an even number of entries in a row/column, the axis is between the two central rows/columns: 1,0,|,0,1 1,0,|,0,1 -,-,-,-,- 1,0,|,0,1 1,0,|,0,1  otherwise it's down the middle of the middle row/column (and the numbers in that row/column count on both sides).  | 1,0,1 -1,0,1- 1,0,1 |  ### Some Examples Each pair of grids below is input .. output, which then becomes the next input, etc. iteratively: 1,0,0,1 1,0,0,1 1,0,0,1 1,0,0,1 1,0,0,0 0,0,0,0 0,0,0,0 0,0,1,0 .. 0,0,0,0 .. 0,0,0,0 .. 0,0,0,0 .. 0,0,0,0 .. 0,0,0,0 .. 0,0,0,0 1,0,0,1 1,0,0,1 0,0,0,1 0,0,0,0 0,0,0,0 0,0,0,0 0,0,0,0  1,1,1 1,0,1 1,0,1 1,0,1 1,0,1 1,1,1 .. 1,1,1 .. 1,0,1 .. 0,0,1 .. 0,0,0 1,0,1 1,0,1 1,0,1 1,0,1 1,0,1  • Is the program supposed to find the shortest path, or any path? Are we supposed to display each step? Should the choice of flipping a 1 to a 0 be random, or can it be calculated? A reference implementation would be very useful in this question. – Razetime Aug 26 '20 at 13:03 • The program is only supposed to flip one, calculated, bit from 1 to 0 and return the new grid. so iterative calls to the program would ultimately lead to all 0s. I guess I'm unclear exactly how I want the concept to be translated into a challenge, which is why I put the sandbox text at the top – simonalexander2005 Aug 26 '20 at 13:38 • The program must be trying to make the array symmetrical This needs to be defined precisely. What does it mean that the program "tries" to make it symmetrical? That repeated application of the program eventaully gives a symmetrical array? That it does it in a "small" (to be defined) number of steps? Same with as easy as possible: this needs to be defined precisely. I'm afraid I don't get the main idea of the challenge, actually – Luis Mendo Aug 26 '20 at 17:21 # Balanced Beams Here are some examples of beams that balance: X Y A | X Y B Y --+-----+---+---+ | | | X X Y Y Y X X --+---- ----+-- + A X X Y | A B Y Y +---+---+-+-----+ | | | | B A | A AAB B A + --+-- --+-- + X Y X X | Y B X +-+-+---+---+---- | | | | Y A X Y Y X X X X + + + ------+----  The diagram will always be 17 characters wide and the top beam always balances in its centre. The other +s on the top beam indicate the point from which a lower beam hangs and the + on the lower beam indicates the point at which it balances. Your input does not need to include the |s if you don't need them. Lower beams with a width of 1 balance by default of course. The balancing of the top beam has to take the total weight of each lower beam into account. As you can see, for each example, there are two positions marked A and B where I have forgotten whether they should be an X or a Y. Please write a program a function which will accept the above diagram as input and output which of X and Y belong in each of the two positions A and B. Your output should be something along the lines of A=X, B=X although any unambiguous output suffices e.g. you could output the diagram with the A and B substituted accordingly or you could modify the input in-place. You do not have to output values for X or Y, although for each diagram they always have a fixed ratio which will allow all beams to balance. Other input formats could be acceptable but they need to get suggested as comments to the sandbox post. This is , so the shortest program or function that breaks no standard loopholes wins! ### Sandbox Question Do people think this is worth posting, given it only really requires a prime check along with getting digit prefixes? There are multiple implementations (possibly including hard-coding in some languages) to consider which might be enough. Please vote! Produce all 83 base-ten right-truncatable primes in as few bytes as possible in the language of your choice. • Order is irrelevant, but the production must terminate. • You may produce a list, a set, or an equivalent object. • You may print them (e.g. space-separated, each on a line, or formatted as a list or set (e.g. {2; 3; 293; 5; ...}) • You may give the numbers themselves as strings. • You may produce an iterator (but evaluating it must terminate). ### Right truncatable primes A right truncatable prime is a prime for which removing any number of trailing decimal digits is also prime. For example, $$\7193\$$ is a right truncatable prime since $$\719\$$, $$\71\$$, and $$\7\$$ are all prime. There are only 83 such numbers in base-ten, when sorted they are: [2, 3, 5, 7, 23, 29, 31, 37, 53, 59, 71, 73, 79, 233, 239, 293, 311, 313, 317, 373, 379, 593, 599, 719, 733, 739, 797, 2333, 2339, 2393, 2399, 2939, 3119, 3137, 3733, 3739, 3793, 3797, 5939, 7193, 7331, 7333, 7393, 23333, 23339, 23399, 23993, 29399, 31193, 31379, 37337, 37339, 37397, 59393, 59399, 71933, 73331, 73939, 233993, 239933, 293999, 373379, 373393, 593933, 593993, 719333, 739391, 739393, 739397, 739399, 2339933, 2399333, 2939999, 3733799, 5939333, 7393913, 7393931, 7393933, 23399339, 29399999, 37337999, 59393339, 73939133]  This is A024770 in the Online Encyclopedia of Integer Sequences. For some mathematician-written* Python see https://youtu.be/f2lEB4nMmyI. * Fair warning, it might well make you cringe. • I don't really mind prime challenges, just that most people who have been here a while have a stigma against it. Related. – Razetime Sep 5 '20 at 14:26 • The code in the link contains what appears to be a partially censored racial slur, so I think you should probably drop the youtube reference. – FryAmTheEggman Sep 9 '20 at 21:32 • Otherwise I think this is probably interesting enough, as these primes have several other non-prime features. It might be problematic if too many answers are just primality checks wrapped in terminating loops, though? – FryAmTheEggman Sep 9 '20 at 21:35 • @FryAmTheEggman Oh wow, I didn't notice; that's pretty sad. – Jonathan Allan Sep 9 '20 at 22:15 # Move the Knight! Your knight is on (0, 0) on an infinite (to all of the four edges, not just two) chessboard, and you need to move it to (a, b). You can use arbitrary (but finite) number of moves to do that. Since the chessboard is infinite, you can use squares with negative coordinates. Since you only have 2 knights (if no promotion occured) to type the program, your program needs to be as short as possible. ## Input The input is two integers, a and b. ## Output You output a sequence of characters, each represents a move. There are eight directions to move, so your output should contain eight distinct characters, each represents one direction. They can be any eight characters, as long as they are all unique. ## Test Cases The characters used here is:  A B C D N E F G H  0 0 -> "" 1 1 -> "GD" or "DEGD" or "DG" etc. 3 3 -> "DDDGGG" (one possible version) 2 3 -> "FGD"  ## Rules • Standard Loopholes are forbidden. • This is , so shortest code wins. • @Razetime I did... "They can be any eight characters, as long as they are all unique." – null Sep 15 '20 at 12:30 • oh, sorry about that. – Razetime Sep 15 '20 at 12:31 • @Razetime I intend to make this challenge have many different, unique, interesting approach, and which one is shorter highly depends on the language. – null Sep 15 '20 at 12:33 # Do my data follow Benford's law or a uniform distibution? ## Background Benford's law, also known as the law of anomalous numbers, describes the distribution of the leading digit in many numerical data sets. Let $$\X\$$ be the leading digit of an observation (in base 10). According to Benford's law, $$\P[X=i]=\log_{10}(1+\frac1i)\$$ for $$\i=1\ldots 9\$$. For instance take the yearly reputation change of the top 1000 users on CGCC. For a user with reputation change 3522, keep only the leading digit, 3. Repeat this for all users, and you get this distribution, which is far from uniform: This has been shown to apply to vary different data sets, from town populations to stock prices, and is used to detect tax and election fraud. On the other hand, for some other data sets, the distribution of the leading digit is a uniform distribution: $$\P[X=i] = \frac19\$$ for $$\i=1\ldots 9\$$. Given some observed frequencies $$\(f_i)_{i=1\ldots 9}\$$, we shall measure the distance to these two distributions using the sum of the errors in absolute value: $$\\sum_i \left|f_i-\log_{10}(1+\frac1i)\right|\$$ and $$\\sum_i\left|f_i-\frac19\right|\$$, respectively. ## Task Take as input a list of non-zero numbers. For each number, keep only the leading digit, which is defined as the first non-zero digit. Compute the observed frequencies of leading digits, and output one of two values, depending on whether the observed frequencies are closer to Benford's law or to a uniform distribution. ## Input Input format is flexible. Note that input may include negative values, as well as non-integers. ## Output Either two consistent values, one for Benford's law and one for the uniform, or a truthy/falsey value. ## Test cases To be added This is , so shortest answer in bytes wins. # Finding the densest crossword puzzles I love crosswords, and nothing beats a super densely packed puzzle. But how dense can the puzzles get? Here's a sample puzzle I made a few years ago: Certainly not great, but can we do better? Given any list of characters, a crosswordification of that list is a crossword puzzle consisting of characters from that list. For example, given the list ['b','a','d','a','d'], the following is a valid crosswordification: but this isn't Clearly, the order of the list is irrelevant. Given a valid crossword, the area of the crossword is the area of the smallest rectangle containing the crossword. In the above examples, the smallest rectangle containing the crosswords are 3x3 squares, which have area 9. # Challenge In this challenge, you must write a function which takes two arguments • A list-like structure containing english characters • A list-like of valid words consisting of english characters and outputs an integer, representing the minimal area of a crosswordification of the list of english characters, where the second input defines the set of valid words. I will be using this english dictionary for my test cases. Any code that is used to import/parse the dictionary into a list-like structure won't be counted in the byte-count, just the function. # Test Cases More to be added: ['d','a','a','a','t','n','m'] -> 7 (adamant is a word) ['k','a','s','a'] -> 6  • Here's what I understand: Our programs need to calculate the smallest possible corssword from the given characters, display the size alone. correct? – Razetime Sep 17 '20 at 5:04 • @Razetime correct – Don Thousand Sep 17 '20 at 13:51 • Do you suspect there is any other way to do this apart from brute forcing all possible arrangements and picking the minimal area one that meets the requirements? – Sisyphus Sep 18 '20 at 4:40 • @Sisyphus yes, but not revealing, as thats part of the challenge – Don Thousand Sep 18 '20 at 11:17 • "one or more of the options for the longest palindromic run of digits in its binary representation can be removed" Does this mean I can remove several runs? For example, 945770 = 11100110111001101010_2 has 110011 as the longest palindromic run, it occurs twice and if I remove both occurrences, the result is 10101010. On the other hand, 944522 = 11100110100110001010_2 has 110011 and 001100 as longest palindromic runs, and removing both gives 10101010. – Zgarb Sep 12 '20 at 10:25 • Don't forget Dennis, Dennis 2.0 or Calvin numbers :P – caird coinheringaahing Sep 12 '20 at 15:37 • @Zgarb No; you should only remove a single run before splitting the remaining digits. I've clarified this in the challenge text. – sporeball Sep 13 '20 at 0:50 ## The ASCII character countdown! answer-chainingrestricted-source Your task is simple: Choose any printable ASCII character that's not chosen in the previous answers. And then, you need to print your chosen character in your program to standard output. (You can ONLY print your chosen character, without printing other garbage to STDOUT) ## The catch Let's say you picked x as your chosen character, and your answer is the answer numbered y. You have to insert y x's into the previous source code, at any position you like. For the first answer, the previous answer is the empty program. ## An example Answers have to start with the number 1. So for example, I chose the character #, and I posted a 1 byte answer in /// that prints the # mark. #  And then, the second answer (numbered 2) has to insert 2 of their picked x character into the previous source code, such that the modified code will print their x character. So assume this is written in Keg: x#x  And then, the third answer has to do the same, and so on, until 95 is reached. ## The winning criterion & other rules • The first user whose answer stays without a succeeding answer for a month wins the challenge. If that's not satisfied, the first person who reaches the number 95 wins the challenge. • You are not allowed to put any other character in your code other than printable ASCII characters. • You need to wait for an hour before posting a chaining answer. • You need to wait 2 answers before you post a new answer after your submission. • Please make sure your answer is valid. If yours is not valid, chaining answers aren't allowed to be posted. • The answers are allowed to be in different languages. • Each submission doesn't have to be in a unique language. • You could only insert y x's into the source code. • Can the answers be in different langauges? – fireflame241 Jul 20 '20 at 4:03 • What is the motivation for the number 95? – fireflame241 Jul 20 '20 at 4:03 • This isn't a radiation hardening challenge, as those require programs to still work / do something different if any single character is removed. – Lyxal Jul 21 '20 at 9:15 • @fireflame241 Because there are 95 ASCII characters of course... – user202729 Jul 21 '20 at 12:50 • Must we only insert y xs, or may we also insert other (printable ASCII) characters apart from our chosen character? If the latter, are the additional characters limited to those not already used in previous answers? – Dingus Jul 21 '20 at 15:02 • "I chose the character ?" -> "I chose the character #"? – user202729 Jul 22 '20 at 6:10 • "has to insert their picked x character into the previous source code," -> edit this part too. – user202729 Jul 22 '20 at 6:11 • @Dingus Now you may only insert y xs. – user92069 Jul 23 '20 at 0:56 • "I chose the character ?" has crept back in. Other than that it's clear now. (Seems difficult too, but maybe not in the golfing langs - I don't know.) – Dingus Jul 23 '20 at 2:18 # Bit delivery in Bin Citycode-golfbinary posted • It could help a lot to add an illustration for small test cases (how to move each bit in the input to the output), and some test cases with more bytes (both even and odd). Other than that, looks good to me. – Bubbler Mar 31 '20 at 1:57 • @Bubbler Thanks for the feedback. How's it now? – Noodle9 Mar 31 '20 at 14:32 • Perfect, and +1 for reference implementation. – Bubbler Mar 31 '20 at 23:00 # TPK Algorithm The TPK Algorithm was designed in 1977 Donald Knuth and Luis Trabb Pardo to show off the various functionality of languages at the time. Your task is to implement the most common version of the TPK algorithm. The pseudocode goes as follows (adapted from Wikipedia): ask for 11 numbers to be read into a sequence S reverse sequence S for each item N in sequence S call function F on N if the result is greater than 400 print "TOO LARGE" else print result F(N) results in sqrt(abs(N)) + 5 * pow(N,3)  F should be implemented as a function in your code, that is, there should be some subsection of you code which consists of a function that takes an input and outputs the result of F for that input. It is acceptable to round the square root operation down to the nearest integer. Notes: if using decimal square roots, the first value greater than 400 is ~4.301. For integer square roots, the first value is ~4.302. Your program does not need to support non-integer inputs. This is , so fewest bytes wins! ### I have abandoned this challenge. If you would like to take it over, feel free to take the idea, and maybe leave a comment so people know you've taken over. # Will it rain? image-processingpopularity-contest (See revision history) • If you have to ask if pop-con is appropriate here I think this challenge is already doomed as a pop-con. But why don't you use it as a test-battery-challenge and use the percentage of correct ones as a criterion? – flawr Aug 8 '17 at 21:40 • This challenge rests on the test cases, if the skies have distinct features in them when it rains to when it won't i.e. darker it should be fine. If they all look similar it will never work. – TheLethalCoder Aug 9 '17 at 10:44 ### I have abandoned this challenge. If you would like to take it over, feel free to take the idea, and maybe leave a comment so people know you've taken over. # Make a program run infinitely code-golf (See revision history) • I don't really understand what 'push' and 'pop' mean thus the operator section is a little confusing to me. Also I think you need to include ; in the list of characters that one can make a bijection from. Also, would it make sense to swap the \  and / commands? If you do the characters would represent mirror planes (or plain mirrors) but now they seem a little counterintuitive to me. – dylnan Nov 16 '17 at 19:45 • @dylnan 1. push and pop are stack operations meaning put a value onto the top of the stack and remove the top of the stack and return its value, respectively. So for example, push pop + pop means pop a value off the top, pop another value off, add them, and push it onto the top of the stack. Also, yes, I missed ;, thanks for noticing. Also, I got confused by my own wording so yes, \/ should be swapped. Thanks for the comments! – hyper-neutrino Nov 16 '17 at 20:07 • So, if I understand, the submissions will take code in the 2D language as input, and the output will be values that, when fed into the input code, would cause it to run infinitely? – Kamil Drakari Nov 16 '17 at 20:30 • @KamilDrakari Yep. – hyper-neutrino Nov 16 '17 at 20:43 • How would the conditionals ! and ? deal with the stack? In your second test case, if the stack is 01 (say the right is the top) and the first ? sees the 1, wouldn't the stack have to be popped in order for the second ? to see the 0 and move into the infinite loop? – dylnan Nov 17 '17 at 1:21 • Also, I think is too hard due to the halting problem. Even with the busy beaver Turing machines it becomes very difficult to determine whether a machine will halt with machines of only a few states. Maybe if you somehow restrict the possible modes of running infinitely (e.g. program will only run infinitely if it gets into <^>v or <v>^ loops) and restrict the length of the program but even then I think it might be too hard but I'm not sure – dylnan Nov 17 '17 at 1:44 • @dylnan It theoretically shouldn't be too impossible because you can just go through all possible states and if it ends up in the same state as before, it will loop infinitely (because there are no non-deterministic commands). It will be horribly inefficient, but eh, it's code-golf, efficiency is not the priority :P – hyper-neutrino Nov 17 '17 at 1:59 # dimensional flipper maze test-battery (need a better name) You're stuck in a maze in one corner, and you want to get to the other corner. However, this maze is unfortunately one dimension higher than you (for simplicity of explanation, you are 1D and it is 2D). Thus, you can only see along one hyperplane of the maze. However, you were granted the magic ability to rotate yourself to see along a different axis (for the 1D-2D explanation, you are on a grid only able to see one row/col, but you can switch which you see). You want to figure out how to get to your destination as fast as possible, but it's hard to devise an optimal strategy when you can't see the whole room, so you'll have to do your best. ## Challenge Requirements Your program needs to be in one of two forms. In the first form, it needs to be interactive; that is, you will be given what you can see, and then you output your move, and your program remains running until the simulation completes. In the second form, it needs to be stateful; that is, you will be given what you see and a memory object, and you output your move and a new memory state, and your program will be run once per step. This is a challenge, so the score will be determined by the number of moves total on the official test data, and a lower score is better, no tie-breaker as I will not accept any solution. ## Input Each step, if you are interactive, you need to read one line of input, and if you are stateful, you need to read two lines of input. The first line of input will be two space-separated integers representing the distance along your row/col to the closest barrier/wall on either side. Note that when you start, at least one of these values will always be 0 because you start in a corner. The second line of input in the second case will be the string representation of a JSON object. This is your memory object. ## Output After receiving input, you must output either one line if you are interactive and two lines if you are stateful. The first line of output represents your move. You may output any distinct values for "move towards right" (this will increase the first gap value and decrease the second gap value both by one), "move towards left" (same, but opposite), "rotate clockwise", and "rotate counterclockwise" (technically, you only need to be able to rotate one way, but for quality of life I'll allow rotating both ways even though you could just invert your moves). By default, these are R, L, C, A, but you can change these in the interactor, just specify what you're using (I recommend just using the defaults; this isn't code-golf anyway). The second line of input, if applicable, represents your memory object. It must be a valid JSON object; if not, your memory object will be discarded and you will be given an empty object the next time. If you are interactive, remember to flush after outputting all necessary information, otherwise the interactor may never receive your output and just wait indefinitely. If you output a move that puts you on square (64, 64), your program will be killed / not called again. ## Scoring A total of 10 random maps have been selected. Note that every map is 64x64. Your score is the number of moves you output to get from square (1, 1) to square (64, 64), totaled across each map. If anyone doubts my selection, you may request me to publicly release the data, or if anyone suspects any solution of specific optimization, you may request me to regenerate test data. The lowest score wins. # Meta • I think this is my first time doing ; is this appropriate? • does this challenge really have any solution/strategy, or is a random brute force always going to be considerably competitive? • is it a duplicate? I will generate sample inputs and the test data and post a checksum if this challenge seems well-received, as well as create an interactor. # Three points on Poincaré disk ## What is Poincaré disk? Poincaré disk is a projection of 2-dimensional hyperbolic geometry to the 2-dimensional Euclidean plane, or more precisely, onto the open disk $$\\{(x,y): x^2 + y^2 < 1^2\}\$$. ## Objective It is well-known that three distinct points on the Euclidean plane are either on a unique line or on a unique circle. Let $$\S\$$ be that line/circle. The inverse image of $$\S\$$ is one of line, circle, horocycle, or hypercycle. Determine which. ## Classification The points are assumed to be on the disk. • If $$\S\$$ is a circle that lies on the disk, the inverse image is a circle. • Otherwise, if $$\S\$$ is a circle that shares a tangent with the boundary of the disk, the inverse image is a horocycle. • Otherwise, if $$\S\$$ crosses the boundary of the disk orthogonally, the inverse image is a line. • Otherwise, the inverse image is a hypercycle. ## Input The cartesian 2-dimensional coordinates of the points. A coordinate can be given as either two real numbers or one complex number. Other than that, the input type and format doesn't matter. This includes: • A tuple of size 3 • A list of size 3 • A set of size 3 Invalid inputs fall in don't care situation. This includes: • Not exactly 3 points • Non-distinct points • A point not on the disk ## Output Output type and format doesn't matter either. This includes: • Enumeration type of 4 possible values • Bit field of size 2 ## Example Assuming there were no floating-point errors: • $$\\{(-½,0),(0,½),(½,0)\}\$$ must give a circle. • $$\\{(-½,½),(0,0),(½,½)\}\$$ must give a horocycle. • $$\\{(-½,0),(0,0),(½,0)\}\$$ must give a line. • $$\\{(1-\sqrt{¾},½),(1-\sqrt{½},1-\sqrt{½}),(½,1-\sqrt{¾})\}\$$ must also give a line. • $$\\{(0,½),(¼,¼),(½,0)\}\$$ must give a hypercycle. • $$\\{(0,0),(¾,0),(0,¾)\}\$$ must also give a hypercycle. • Can the coordinates $(x,y)$ be represented as a complex number $x+yi$? – caird coinheringaahing Oct 11 '20 at 16:43 • @cairdcoinheringaahing Yes. – Dannyu NDos Oct 11 '20 at 21:02 • It looks like solutions might have trouble with the line and horocycle cases due to float precision, if either they take values like sqrt(2) to finite precision or introduce imprecisions in the calculations. Can some allowance be made for this? I'm not sure how though. – xnor Oct 12 '20 at 2:09 • @xnor If the input is IEEE floating-point numbers, they are in $\mathbb{Z}[½]$ anyway and must be regarded as such. If your language is able to do symbolic computation, you may go ahead. – Dannyu NDos Oct 12 '20 at 3:15 # Compactify the real numbers to a group (WIP) ## Objective Let $$\X = \mathbb{R} \cup \{\infty\}\$$. The $$\\infty\$$ is the point at infinity and doesn't have a signature. Let $$\Y = \{\exp(i\theta) : \theta \in [0,2\pi)\}\$$, which is the unit circle on the complex plane. Make $$\X\$$ a group by giving $$\X\$$ a binary operation, so there will exist a function $$\f : X → Y\$$ that is both an isomorphism and a homeomorphism. Your code shall implement the binary operation. $$\f\$$ doesn't need to be implemented to a code. ## Group A set $$\G\$$ endowed with a binary operation $$\*\$$ is a group iff: • For every $$\a,b,c \in G\$$, $$\(a * b) * c = a * (b * c)\$$ • There exists the identity element $$\e \in G\$$ such that for every $$\a \in G\$$, $$\e * a = a * e = a\$$ • For every $$\a \in G\$$, there exists $$\b \in G\$$ such that $$\b * a = a * b = e\$$ $$\Y\$$ is a group, where the binary operation is the multiplication. ## Isomorphism Let $$\*\$$ denote the binary operation given to $$\X\$$. A function $$\f : X → Y\$$ is an isomorphism iff: • $$\f\$$ is bijective • For every $$\x,y \in X\$$, $$\f(x*y) = f(x) × f(y)\$$ Note that once appropriate $$\f\$$ is identified, $$\*\$$ can be automatically defined as $$\x * y = f^{-1}(f(x) × f(y))\$$. ## Topology A subset $$\A \subset X\$$ is open iff, for every $$\x \in A\$$: • If $$\x \in \mathbb{R}\$$, there exists $$\P \subset A\$$ such that $$\x \in P\$$ and $$\P\$$ is an open interval • If $$\x = \infty\$$, there exists a subset $$\P \subset A\$$ such that $$\x \in P\$$ and $$\P\$$ is the union of two open rays to the opposite directions A subset $$\B \subset Y\$$ is open iff, for every $$\y \in B\$$, there exists a subset $$\Q \subset B\$$ such that $$\y \in Q\$$ and $$\Q\$$ is an open arc. ## Homeomorphism A function $$\f : X → Y\$$ is a homeomorphism iff: • $$\f\$$ is bijective • For every open subset $$\A \subset X\$$, its image $$\f[A]\$$ is open in $$\Y\$$. • For every open subset $$\B \subset Y\$$, its inverse image $$\f^{-1}[B]\$$ is open in $$\X\$$. ## Rule You may represent $$\\mathbb{R}\$$ as a floating-point number. Every floating-point error will be tolerated in this regard. ## Example An example of $$\f\$$ is: $$f(x) = \exp(i × 2 \arctan \frac{x}{2})$$ where $$\\arctan \infty = \frac{\pi}{2}\$$, and we identify $$\*\$$ as: $$x * y = 2 × \tan (\arctan \frac{x}{2} + \arctan \frac{y}{2})$$ where the identity element is $$\0\$$, and the inverse element of $$\x\$$ is $$\-x\$$ when $$\x \in \mathbb{R}\$$, or $$\\infty\$$ if $$\x = \infty\$$. ## Ungolfed solution ### Haskell This implementation abuses the fact that IEEE floating-point numbers can encode infinities. Both positive infinity and negative infinity will be treated the same in this regard. import Data.Semigroup import Data.Monoid import Data.Group newtype CompactR = CompactR Double deriving (Eq, Show, Read) instance Semigroup CompactR where CompactR x <> CompactR y = CompactR$ 2 * tan (atan (x/2) + atan (y/2))

instance Monoid CompactR where
mempty = CompactR 0

instance Group CompactR where
invert (CompactR x) = CompactR (negate x)


You implement only <>. The others are just details.

# Sandbox questions

This challange turned out to be too easy.

What if I asked about one-point compactification of $$\\mathbb{C}\$$ instead of $$\\mathbb{R}\$$?

• I think even just f(x,y)=(x+y)/(1+xy) works for the real case – xnor Oct 14 '20 at 8:01

# Convert hexadecimal to decimal

We have a lot of base conversion challenges. Surprisingly, aside from one closed challenge, there aren't any where the goal is purely to convert hexadecimal to decimal. This is different from challenges like converting hexadecimal to binary, because many languages have features like hexadecimal literals (0x, \$, etc.) which can do this in a much shorter or more interesting way.

I/O:

You should create either a program or function, which takes input and output through one of the allowed methods. The input will be a hexadecimal number, consisting of the characters /[0-9a-f]/ (you may choose the capitalization rules).

Scoring:

This is code golf, shortest answer per language wins.

• Feedback is of course useful. If the downvote is because this is a dupe or is unnecessary, that would be useful to comment on. Otherwise, I can't fix any issues without knowing what they are. – Redwolf Programs Oct 17 '20 at 21:11

# Recolour my Table (Abandoned)

• Maybe try limiting the table format. Is it top down or sideways? Also can we assume that the original table color (or slight variation to a certain HSL difference, maybe) is the majority of the image? – Roman Gräf Feb 6 '20 at 19:50

# Is a coincident point in a pair of rotated hexagonal lattices closest to the origin? code-golf

I've deleted from here because I agree it is takes too much time to understand at the moment.

## Preface

This is a question where the technique must search or exclude from search all possibilities. As soon as I figure out how to pose it, there will be a separate question for mathematical techniques other than a simple search, so please don't use them here.

Below is quoted from Math SE determining if a coincident point in a pair of rotated hexagonal lattices is closest to the origin?:

A pair of hexagonal lattices with one scaled by the square root of a rational number $$\r = \sqrt{\frac{m}{n}}\$$ and then rotated will produce a variety of different hexagonal lattices of coincident points.

For the first lattice let

$$x, y = i+\frac{1}{2}j, \ \frac{\sqrt{3}}{2}j$$

and for the second

$$x, y = r\left(k+\frac{1}{2}l\right), \ r\left(\frac{\sqrt{3}}{2}l\right).$$

Per this and this helpful answer the squares of the distances to unit lattice points are given by Loeschian numbers (A003136) equal to $$\i^2+ij+j^2\$$ so in this case a point $$\i, j\$$ on the first lattice will coincide with a point $$\k, l\$$ on the second lattice once rotated by some amount if

$$n(i^2+ij+j^2) = m(k^2+kl+l^2).$$

For example if $$\m, n = 13, 7\$$ then both $$\(i, j) = (5, 6)\$$ and $$\(6, 5)\$$ will coincide with $$\(k, l) = (5, 3)\$$ at rotation angles of about 5.2 and 11.2 degrees as given by.

$$\theta = \arctan\left( \frac{\frac{\sqrt{3}}{2}l}{k+\frac{1}{2}l} \right) - \arctan\left( \frac{\frac{\sqrt{3}}{2}j}{i+\frac{1}{2}j} \right)$$

However, while the first solution is part of the hexagonal superlattice built on the much closer point $$\(i, j), (k, l) = (1, 3), (1, 2)\$$ the second point represents the shortest possible coincident distance and therefore a far lower density coincident lattice. plotting script: https://pastebin.com/pZFCGXbE

## Task

Given the rational number (m, n) e.g. (13, 7) and pairs of known coincident lattice points, e.g. (5, 6), (3, 5) or (6, 5), (3, 5) (besides the origin) we want to find out if this is one of the six closest coincident lattice points, or if it is a member of a coincident lattice with points closer.

• If it's one of the six closest: return some flag letting us know there wasn't anything closer. You may also return either the same point, or one of the other five of identical distance.

• If it isn't: return one of the six points that was closest along with (but not only) a flag letting us know that a closer point was found and the original point wasn't one of the closest. Reminder that this will be a closer point in a coincident lattice that also contains the original input.

Do this by some combination of searching/testing all possible pairs of lattice points (one from each lattice) to see if they are coincident and closer and potentially excluding blocks of combinations that don't need searching. The problem is finite because one only searches points that aren't obviously farther from the origin.

Feel free to use tricks to exclude large fractions from search as long as they rely on simple rules, for example a point near the origin in one lattice will never be coincident with a point near a distant point in the other.

But if you find yourself considering computations like matrix division or using Eisenstein integers or Euclid's algorithm in the complex plane please save that for the follow-up question.

This is so shortest code wins.

## Input

• Input will have six integers $$\(m, n), (i, j), (k, l)\$$ as described above, but can have any order or hierarchy, or additional (but uninformative) place holders (e.g. zero padding, blanks...)
• $$\(m, n)\$$ will be positive, but the other four can be positive, negative or zero, excluding a $$\(0, 0)\$$ pair (the origin).

## Recipe for making test cases

In addition to the two mentioned above (13, 7), (5, 6), (5, 3) and (13, 7), (6, 5), (5, 3) you can roll your own:

1. Pick two Loeschian numbers $$\L_1\$$ and $$\L_2\$$ and find some integer pairs (i, j), (k, l) that can make them. (Find all integer pairs that produce a given Loeschian number)
2. Make new pairs by choosing two nonzero integers $$\a, b\$$, then:

\begin{align} i' & = ai - bj\\ j' & = aj + b(i+j)\\ k' & = ak - bl\\ l' & = al + b(k+l). \end{align}

If $$\i, j\$$ and $$\k, l\$$ were coincident, then $$\i', j'\$$ and $$\k', l'\$$ will be as well.

(This just says that the coincidence lattice between two hexagonal lattices is also a hexagonal lattice.)

As a Web Frontend developer, I feel out of place most of the time coming here. And that is despite the existence of established challenges like One Div in the field of web development. But they aren't here, because objective criteria are hard to do. (Sparing more unkind reasons.)

Maybe the following would be a way to draw others. It's not a One Div challenge, but a way to set different web technologies against one another in a sort of code golf.

To give you an idea, compare these two Codepens:

(To be fair, thebabydino doesn't know at the time of writing there is a challenge, it was a spontaneous idea after seeing her code.)

It was rightly pointed out to me that capturing the idea of good coding practice will probably fail. But let me give you a vision: What if the challenges were not only about learning new coding tricks, but also about identifying the "cheats"?

There is a whole industry out there that tries to make objective rules to ultimately measure code quality. Their work is mostly to tilt against windmills. Maybe there is a way to make a playfull challenge a tool to identify new features for linters.

If good coding wins, so much better for it. If everyone thinks the winner was going squarely against the spirit of good coding practice, professionalism gains a discussion.

(Somehow this reminds me of the discussion about doping in sports.)

I hope to make the playing field understandable also to non-web people, so please bear with me if I add comments that would be obvious to everyone in the profession.

One goal here is performance. There are a lot of champions for the approach to minimize external dependencies loaded into the browser. I am trying to capture this with a "no external request" rule. This is not only about the size of files loaded but also the debt of interpreting extensive JS frameworks. Look at current discussions about web site performance, and you will understand what I am talking about.

## Challenge: Recreate the image with web technologies

A real question would contain a raster image in any format. Most likely, they will be PNG or GIF (to show animations).

### The code must be runnable on Codepen

You must create a pen and post its URL here. Your own authorship should be on a honors base. Anonymous pens are acceptable, but if your nick is the same here as there, you must use your account.

There are a good number of web development environments around, but they all offer different features. The criterium for selection was the ease to enforce the "no external resources" rule - and popularity, of course.

In addition, the code must be posted in its entirety here.

### No external code

The pen must not include any external sources.

• No import statements in any language
• no statements that trigger any external requests
• no external stylesheets or scripts imported via the pen settings

An important case here is the use of JS frameworks that offer server-side rendering, or template languages like JSX. Should their source code be made legal? This sort of code is mostly undistinguishable from code used client-side, with the difference that it must be compiled before it is delivered to the client.

### No base64-encoding

No part of the code should be unreadable at first glance. So neither HTML, nor CSS, nor JS are allowed to contain any base64-encoded strings

• No data: URI that contains the base64 option
• The use of atob() and btoa() in JS is ok, provided there is no string literal containing a base64-encoded string
• The use of <canvas> and/or URL.createObjectURL() is certainly ok, provided there is no string literal containing a base64-encoded string
• The use of Blob or ArrayBuffer to construct images is certainly ok.

### The use of preprocessors is allowed

Any preprocessor that is offered by CodePen can be used. What counts for the solution is the source code in that language.

Using Babel as a preprocessor inside CodePen is ok, but the "no imports" rule applies just the same.

Currently the Babel preprocessor offered by CodePen has a fixed configuration. If that changes in the future, it might be valid or not to use an URI to an external config file or npm module or not. That is in the future. The basic idea here is "if it is executed on the server side, or by native browser code, go for it"

### Linting must pass

To give languages a fair chance that rely on fixed indents, and to maintain readability, the Javascript part must pass ESLint without any warning or error.

1. Which preset does the best to enforce good code quality? It was pointed out that there will probably remain a number of loopholes, but I would like to try to get them as few and obscure as possible.
2. I am not so fluent with linters for other languages. Proposals?

### No minification

All code should be pretty.

• Running prettier must not change the code formatting

This might not cover all languages. Please review and propose other/additional formatters.

• No code line can be longer than 80 columns

### Matching the source image

I have still to research that. My first instinct is to use ImageMagicks magick compare and set a cutoff value to account for antialiasing and rounding differences, but that does not solve how to capture animations. Maybe capture all frames with Lighthouse?

### Wining criterium: aggregated Number of lines of code

The number of lines of source code in markup, stylesheet and script are added. The least number of lines wins.

• Numbers are counted using sloc. Only the Source output value is relevant. For example on the command line

  sloc pen.css | grep Source


is there a sensible way to scrape the code lines directly from Codepen? Or is this available on the site and I am simply not aware of it?

Please give your answer a header that qoutes the number of lines in each language separately.

• While giving 'languages a fair chance' by enforcing no base64 and counting lines of code only is admirable, I think you will find that there are too many ways to cheese it. For example, I could write every line as eval('...' + '...' + '...') to escape minification. It might be better just to use a more conventional scoring criteria (bytes) and drop the base64/formatting requirements. – Sisyphus Oct 22 '20 at 2:56
• I am not giving up on this so easily. If there is to be a challenge, it should be on the basis that is done with good coding practice. Otherwise, it just makes no sense. Linters should be able to catch a lot of the loopholes, and if not, at least this would be a way for others to learn about them. Isn't this also the goal of this community? My vision would be that if this gains popularity, Linter manufactureres look at "cheating" solutions for improvements to their product. – ccprog Oct 22 '20 at 12:06
• @ccprog Unfortunately, "good coding practice" is a subjective thing, and we strive for objective scoring criteria. Most answers on the site will happily sacrifice things such as readability and good practice in order to reduce their score. – caird coinheringaahing Oct 22 '20 at 13:00
• @cairdcoinheringaahing Did you see my latest edit? Maybe this can be a productive goal in itself. – ccprog Oct 22 '20 at 13:01
• @ccprog I was mainly responding to your comment, I was still reading through the full spec as I wrote that. I do very much like the idea of this challenge, and I think it should be fully able to do while still fitting within our site rules (objective scoring criteria etc.). I'm not too familiar with the topic of web technologies, so forgive any mistakes I may make, but one thing sticks out to me as needing improvement when reading this challenge: the attempts to cover things in all languages. Usually, we tend to avoid language-specific challenges on the site, but I think this would be a (cont) – caird coinheringaahing Oct 22 '20 at 13:05
• (cont) good example of where limiting the language would help rather than harm the challenge. From my understanding, it looks as though restricting answers to Javascript would allow you to make the challenge much more objective with the rules about minification and base64, as you won't have to worry about edge cases in esoteric languages such as Jelly or ><> that are commonly used on the site. – caird coinheringaahing Oct 22 '20 at 13:07
• That, on the other hand is unrealistic. Most Javascript code nowadays is somehow cross-compiled, either from other languages (for example the Typescript superset) or through the use of frameworks (Angular, React). I'll have to think more about th "no imports" rule here, as one of the banes of current web development is that a lot of devs loose the sight of whether their code is executed server or client side. – ccprog Oct 22 '20 at 13:15
• As far as esoteric languages are concerned, there is an implicit stop gag: Forcing Codepen as execution environment. If the language isn't supported there,, the answer fails. And believe me, Codepen is an industry tool, not just any website. Every post there is considered to be a showcase for the developer and counts for his/her professional reputation. – ccprog Oct 22 '20 at 13:21
• @ccprog I actually have no problem with the challenge as specified. I just think that the winning solutions will cheat the tool(s) you use to score. But if that's ok with you, I don't mind this challenge at all, and will look forward to see the answers. – Sisyphus Oct 23 '20 at 1:07