# Sandbox for Proposed Challenges

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

Sandbox FAQ

## Posting

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

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

## Discussion

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

• Parts of the challenge you found unclear
• Problems that could make the challenge uninteresting or unfit for the site

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

If you think one of your posts needs more feedback, but it's been ignored, you can ask for feedback in The Nineteenth Byte. It's not only allowed, but highly recommended!

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

## Other

Search the sandbox / Browse your pending proposals

The sandbox works best if you sort posts by active.

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

Get the Sandbox Viewer to view the sandbox more easily!

# Introduction

The fast inverse square root algorithm is a function developed in C for Quake III. It was at the time the fastest way to compute the inverse square root of a function, which is needed for most vector operations.

The code as written in 1999, from the quake 3 source, is as follows:

float Q_rsqrt( float number )
{
long i;
float x2, y;
const float threehalfs = 1.5F;

x2 = number * 0.5F;
y  = number;
i  = * ( long * ) &y;                       // evil floating point bit level hacking
i  = 0x5f3759df - ( i >> 1 );               // what the fuck?
y  = * ( float * ) &i;
y  = y * ( threehalfs - ( x2 * y * y ) );   // 1st iteration
//  y  = y * ( threehalfs - ( x2 * y * y ) );   // 2nd iteration, this can be removed

return y;
}


# Challenge

Given a floating-point number in any form you wish, calculate its inverse square root and return it as a float to at least 4 decimal places.

Input:

3

Output:

0.5773502691

# Judging

This is a challenge for creativity as well as code size.

For example, I would rate a 1:1 copy in c# about a 3/5, but a brainfuck copy 5/5 for the challenge and creativity.

• I think this could be a cool challenge, it'll need some work though. I see you deleted the one you posted on main, if you want we can work through the problems it had here, then undelete it and edit it. I can tell you put a lot of work in to this, and it could be a good first draft of a great challenge! Sep 17 at 2:24
• The precision requirement "to at least 4 decimal places" isn't a good requirement since to verify it one would need to test the algorithm on every floating point number. Usually, a simpler way to handle floating point accuracy is to just give a large number of test cases and require that submissions meet all of them. Sep 17 at 14:48
• The "judging" section is extremely unclear at the moment. You mention that code size is important, but your examples make no mention of it. The examples you give are also for copying the algorithm, which I can't reasonably conclude to be creative. I'm not sure where you want to take this, but what you have now won't work. Sep 17 at 14:53
• might be one of the few that Rust does well in compared to other compiled languages, fn s(x:f64)->f64{1./x.sqrt()} Sep 27 at 7:08

# Apply gravity to this matrix

• I'm pretty sure this has been done, but I can't seem to find it right now.
Sep 17 at 12:58
• FWIW, this is a fairly simple challenge (transpose, sort each row, transpose in most languages, some may even have a way of sorting each column directly) Sep 17 at 13:10
• Are the brackets required? Sep 18 at 0:27
• No, that was just to visualize Arrays. Input and output can be in any reasonable form. Sep 18 at 9:18

# A *character*-less quine

Similar to “What did we forget?

## Output

Your program must be a quine - that is, print its own source code with no input or unused input.

Although this is , you are allowed to read your own source code. Assume the file is named “q” and that no extension is needed. There is no bonus for not reading the source code.

If you remove all occurrences of a character that is in your program, it should print the character removed. It is allowed to then raise an error; however, there is no bonus for this either.

To the sandbox: do I need this? => Your program must have at least 3 different characters.

Lowest number of bytes wins (this is , after all)

## Sanbdox things

• Anything I should change?
• This used to be “Numberless” (see edit history) - should I change it back?
• I'm afraid it's a duplicate of this challenge. PS: these type of challenges were characters are removed are tagged radiation-hardening. Sep 22 at 7:20
• Duplicate no longer…? The original source code must now be a quine.
– W D
Sep 22 at 8:14
• Yep, seems to be no longer a duplicate. :) There are some radition-harderning + quine challenges, but most require to output the original program or current program after removing a single character. Sep 22 at 9:57
• Why are programs allowed to read their own source? This rule seems a little disconnected to the rest of the challenge.
– Grain Ghost Mod
Sep 22 at 21:44
• So it’s a little easier, I don’t want to be too harsh - it’s much harder if you can’t read your own source
– W D
Sep 23 at 0:18

Find out if a function always returns its input.

# Input/Output Information

Input is a math expression as a string with operators + - ( ) /.
The multiplication symbol is *, or x if you specify.

The input will always will only contain whitespace spaces, decimal points, numbers (0123456789), math symbols (+ - ( ) / and one of the following: * or x) and one lowercase letter that is the variable.

Whitespace in the input must be ignored.

Output is whether the function will always return its input.

The expression will never have a division by a polynomial with its degree >1.
Example: x*x*x/x*x <= this will never be input.

# Example Input/Output

Input: n /3 + 2*n/3 + 175 - 175*(n+ 1-n)
Output: truthy
Explain: Simplifies to "n"

Input: f
Output: truthy
Explain: Any variable is allowed

Input: j*(j-3.1)/(j-   3.1)
Output: falsey
Explain: In normal math, this evaluates to j
However, when j is 3.1, it is undefined
Therefore, it doesn’t ALWAYS return its input
This is because when j is 3.1, the output is not 3.1

Input: 1j
Output: truthy
Explain: 1j = j which is the input

Input: n/2 + n/2
Output: truthy
Explain: Simplifies to 2n/2 = n which is the input


# Scoring

This is , so lowest amount of bytes wins!

## Sandbox Questions

I brought this back from a long time ago.

• There's some inconsistency in the examples: the first one is being treated as if it's a maths expression whereas the third one is not. Suppose the input is n/2 + n/2. Should the output be true? In some languages the output will not necessarily be the same as the input: / might get you floor division or conversion to a float. You can avoid these issues by treating the input as maths. But in that case, example 3 should simplify to j. Jan 5 at 9:38
• Why is there an x in your first test case? Right now it'll become n-175(x-1) (n/3+2*n/3 becomes n and 175-175x(n+1-n) becomes -175(x-1)).. I assume that x either should be gone or a *? Also, you may want to clarify what's in the input. You mention +-*/ and whitespaces, but all the lowercase letters and parenthesis aren't mentioned anywhere. And assuming that first test case was a mistake, is the input guaranteed to not contain more than one unique lowercase letter? Sep 22 at 7:14
• Thanks @KevinC, I clarified that just now
– W D
Sep 22 at 8:20
• Looks good, +1 from me. As for the */x, I would just put the * in the string with the other operators, and just mention something like "if your language is using a different operator character (i.e. x instead of *), you are allowed to use it instead. If you're unsure whether a character is allowed, leave a comment.", or something along those lines. The operator characters used aren't too relevant for the core of the challenge, and some languages might use */x/×/· for multiplication or //÷ for division. Or just ASMD for add/subtract/multiplication/division. Sep 22 at 8:36
• Then again, most answers will probably do something along the lines of: replace the lowercase letter with the input; eval; check if it equals the input. 🤷 Sep 22 at 8:37
• No, that wouldn’t work because n*n/n, or maybe n*((n+149485)/(n+149485))
– W D
Sep 22 at 8:39
• What would be the domain and range of these mathematical functions? Sep 22 at 8:58
• Depends which mathematical function you are talking about…?
– W D
Sep 22 at 9:21

# Alternating Digit Divisibility

TODO: Could use a better title..

## Challenge:

Given a list of at least two positive integers, output a pair of lists of digits. Both inner lists in the output are the digits which evenly divide each number in the alternating converted lists. The first converted list will be [sum(digits(n)), n, sum(digits(n)), ...], and the second will be [n, sum(digits(n)), n, ...].

Step-by-step example:

Input: [611,44,381]

Step 1: Convert it to the two alternating lists:

[[sum([6,1,1]),44,sum([3,8,1])],    →    [[8,44,12],
[611,sum([4,4]),381]]                    [611,8,381]]


Step 2: Check for each number which digits evenly divides it:

[[[1,2,4,8],[1,2,4],[1,2,3,4,6]],
[[1],[1,2,4],[1,3]]]


Step 3: Leave the digits present in each of the inner lists of lists, which is our output:

[[1,2,4],
[1]]


Output: [[1,2,4],[1]]

## Challenge rules:

• I/O is flexible. Input can be a list of strings, integers, 2D list of digits, etc. Output can be a list of lists of digits, a single flattened list of digits (i.e. [1,2,4,1] in the example above), two lists printed on separated lines, each digit printed separated, a string or single (big) integer (i.e. 1241), etc. etc.
• You're allowed to swap the order of the alternation if it's convenient in your language of choice (i.e. the example above would output [[1],[1,2,4]]/[1,1,2,4]/1124/etc. instead).
• 0 will never be in the output.

## General rules:

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

## Test cases:

Input:                      Output:

[611,044,381]               [[1,2,4]], [1]]
[200,32000,4000]            [[1,2], [1,5]]


TODO: More to come, including some larger ones

• Isn't it two challenges in one? The alternating digits lists and then extracting common divisors of two lists? Sep 22 at 11:58

# Draw me a circle

Given a radius $$\r\in\mathbb{N}\$$ and $$\r\geq 3\$$, draw an ASCII circle for me, using $$\x\$$'s. Your circle does not have to look perfect, it just has to be identifiable as one. To make the circle look good, you have to use a $$\2:1\$$ ratio for width and height of the circles. This is due to characters being taller than wide.

One thing that is required though is an appropriate angle increment. I reccomend $$\r\times3\$$.

You do not have to account for float rounding errors!

Given the radius $$\5\$$, your output should look similar to this:

     x x x x x x
x           x
xx               xx
x                 x
x                   x
x                 x
xx               xx
x           x
x x x x x x


## IO

Input and output can be in any reasonable form.

## More test-cases

Note that these don't have to be an exact match!

3 ->
x x xx
xx       xx
x           x
xx       xx
xx x x

7 ->
xx x x x x xx
x               x
x                   x
xx                     xx
x                         x
x                         x
x                           x
x                         x
x                         x
xx                     xx
x                   x
x               x
xx x x x x xx

• what does "appropriate angle increment?" mean? does it rule out drawing a circle without using angles? Sep 27 at 2:09
• how many percent of it should match? i could fill the entire board and say it match. I recommand giving a fixed shape and enlarge it with size increase.
– okie
Sep 28 at 1:02

# Drop down the numbers

• What happens when two non-zero entries ought to go to the same place? For example" What if a column is 2, 1, 0? What does that column become?
– Grain Ghost Mod
Sep 22 at 21:34
• Also what if a number can't move down far enough? e.g. a 1 in the bottom row, or a 2 in the bottom two rows.
– Grain Ghost Mod
Sep 22 at 21:35
• @WheatWizard Edited to clarify. Sep 22 at 22:06
• what do you mean by big number decide? Can you give out a simple example to explain it? thanks :D
– okie
Sep 23 at 5:36
• @okie Explained Sep 23 at 13:08
• Thanks for the explanation, it's much clearer now, anyway, i think the second example's 4th row is wrong?
– okie
Sep 24 at 0:09
• @okie Fixed. Any other problems with the test cases? Sep 24 at 0:12
• @AlanBagel I think it's good to go now! just remember to add rules and any extra stuff that you want to mention. For example: standard rules applys and such
– okie
Sep 24 at 0:20
• I've edited this down to a stub now that it's been posted to save space Sep 26 at 14:03

# Irreducibile Polynomials

## todo, add several test cases. and figure out how to deal with verifying answers. figure out how references work, not just using plain hyperlinks.

As you may know, Polynomials are mathematical expressions of the sum of a variable raised to various powers and multiplied by various coefficients. For example consider the variable $$\x\$$

$$\begin{array}{11} 3x^2 & \mbox{ exponent is 2, leading coefficient is 3 } \\ 3x^2 + 16x & \mbox { add a term with exponent = 1, coefficient = 16 } \\ 3x^2 + 16x + 7 & \mbox { add another term, with exponent = 0, constant coefficient = 7 } \\ \end{array}$$

In general we can write a polynomial named $$\P\$$ as a function of $$\x\$$ as follows: $$P(x) = a_mx^m + a_{m-1} x^{m-1} ... + a_1 x^1 + a_0 x ^ 0$$

Polynomials are somewhat similar to integers in that they can be factored into smaller polynomials that when multiplied together give the original polynomial. This process can be repeated until the integer or polynomial cannot be factored anymore. For integers this smallest factor is called a Prime, but for Polynomials it is called Irreducible. For integer polynomials over the integers, which is what this challenge is limited to, we have the following examples:

$$\begin{array}{11} \mbox{polynomial} & \mbox{irreducible factors} \\ x^2-1 & (x-1),(x+1) \\ x^5-x^4-2x^3-8x^2+6x-1 & (x^2 - 3x + 1),(x^3 + 2x^2 + 3x - 1) \\ 6x^2 + 243x - 378 & (x+42),3,(2x-3) \\ \end{array}$$

How do we know a polynomial is irreducible? We could do trial polynomial-division on all possible smaller polynomials, but it turns out that there are several algorithms that can quickly tell us if a polynomial is irreducible.

This challenge is to write a program that returns True if a given Polynomial meets any of the four irreducibility criteria given below.

This is Code Golf - fewest number of bytes wins!

## Criteria 1: Gotthold Eisenstein

First your program should determine if the input polynomial meets the irreducibility criteria of Gotthold Eisenstein. This criteria looks for the existence of a special number $$\q\$$ such that the following are true:

• $$\q\$$ is prime
• $$\q\$$ is not a factor of the Leading Coefficient
• $$\q\$$ is a factor of all the non-Leading Coefficients
• $$\q^2\$$ is not a factor of the Constant Coefficient

For example:

$$P(x) = 3x^3 + 15x^2 - 25x + 10$$

has a $$\q\$$ of 5, where

• 5 is prime
• 5 is not a factor of the leading coefficient 3,
• 5 is a factor of the non-leading coefficients 15, -25, and 10
• 5 squared is not a factor of the constant coefficient 10

Therefore $$\P\$$ is irreducible, and your program should return True

## Criteria 2: Oskar Perron

In 1907 Oskar Perron's paper describes a criteria that does not require factoring the coefficients. Recall that polynomial P can be written as

$$P(x) = a_{m}x^m + a_{m-1} x^{m-1} ... + a_1 x^1 + a_0 x^0$$

• Assume $$\P\$$ is monic, which means the leading coefficient $$\a_{m}\$$ is $$\1\$$.
• Assume $$\a_0\$$ is not $$\0\$$
• If the absolute value of $$\a_{m-1}\$$ is greater than the sum of all the other coefficient's absolute value, then $$\P\$$ is irreducible
• In more mathy language:

$$|a_{m-1}| > \sum_{\substack{i=0\\i\neq{m-1}}}^{m} |a_i| \implies P \mbox{ is irreducible}$$

Example:

• $$\P(x)=x^{38797389} - 55x^2 + 2x - 9\$$
• $$\a_m=1\$$ and $$\a_0 \ne 0\$$
• $$\|a_{m-1}| = 55\$$
• Sum of other coefficients absolute value is $$\1+2+9 = 12\$$
• $$\55 > 12\$$

Therefore $$\P\$$ is irreducible, and your program should return True

## Criteria 3: Michael Filaseta 1988

Next we visit Michael Filaseta's 1988 paper in which he describes the following wonderful criteria: If $$\P(x)\$$ is an integer polynomial of degree $$\<= 31\$$ which has non-negative coefficients, and $$\P(10)\$$ is prime, then $$\P\$$ is irreducible.

For example:

• $$\ P(x) = x^8+2x^4+23 \$$
• $$\P\$$ is of degree 8, which is less than or equal to 31
• $$\ P(10) = 100020023 \$$
• $$\100020023\$$ is prime

Therefore $$\P\$$ is irreducible, and your program should return True

### Criteria 4: Filaseta and Gross

In 2014 Filaseta and Samuel Gross published the following remarkable criteria, which doesn't depend on the degree of the polynomial:

• Consider $$\P(x)\$$ an integer polynomial with coefficients between $$\0\$$ and $$\49598666989151226098104244512918\$$.
• If $$\P(10)\$$ is prime then $$\P\$$ is irreducible

For example

• $$\ P(x) = 54x^{38} + 78783x^{33} + 035033459404x^{21} + 1190354877x^{11} + 56007093177 \$$
• all coefficients are between $$\0\$$ and $$\49598666989151226098104244512918\$$
• $$\ P(10)= 5478783035033459404119035487756007093177 \$$
• $$\5478783035033459404119035487756007093177\$$ is prime

Therefore $$\P\$$ is irreducible, and your program should return True

### Input format

The input format can be whatever is easiest for your language, and if your language has built-in polynomials, that is allowed. The test-case polynomials can be converted to your chosen format before processing into your program. You can take input as an argument to a function, as standard input, or whatever is easiest for your language.

If your language has no built-in polynomial format, one suggestion is to look at the PolyNumber format - that is, an array listing the coefficients, and the position within the array indicating the exponent. Lowest powers come first. For example

$$x^2+1 \mbox { is } [1,1]$$ $$2x^3+5x^2+7x+4 \mbox { is } [4,7,5,2]$$ $$x^4 + 5 \mbox{ is } [ 5,0,0,0,4 ]$$

### Extra notes

First, please note these criteria are sufficient but not necessary. This means that if a polynomial meets the criteria, then it is irreducible. However, just because it doesn't meet the criteria, that doesn't mean it's not irreducible. For the challenge, your program just needs to return True if an irreducibility criteria is satisfied. Returning a non-True value will simply indicate the criteria were not satisfied, it won't necessarily mean that the input polynomial is or isn't irreducible.

Second, a quick glossary of terminology, for polynomial $$\P\$$ we have the function

$$P(x) = a_mx^m + a_{m-1} x^{m-1} ... + a_1 x^1 + a_0 x ^ 0$$

• Leading Coefficient - the coefficient of the highest power term: $$\a_m\$$
• Constant Coefficient - the coefficient of the 0th power term: $$\a_0\$$
• Degree - The value of the highest exponent: $$\m\$$
• Integer Polynomial - a polynomial where all coefficients are integers
• Monic Polynomial - a polynomial with Leading Coefficient of 1

For example let us create an integer polynomial with degree 9, a leading coefficient of 42, and a constant coefficient of -7, as follows:

$$42x^9-7$$

## Refs

Filaseta, M. (1988). Irreducibility Criteria for Polynomials with non-negative Coefficients. Canadian Journal of Mathematics, 40(2), 339-351. doi:10.4153/CJM-1988-013-6

https://bigprimes.org/

https://www.sciencedirect.com/science/article/pii/S0022314X13002539

• It's clear that a lot of work has gone into this, but I question whether asking for solutions to test against multiple rigid criteria (one of which includes a 32 byte constant) isn't pulling in the opposite direction to code golf. It's unclear to me how much scope there is for creativity here, since each criterion includes a prescribed set of conditions that are mostly independent of each other. Have you considered just asking whether a given polynomial is irreducible? Oct 12 at 5:43
• well its a good point but... but i was hoping that these four techniques are not as independent as they appear to be at first glance. Also asking "is this irreducible" only has one answer, to fully factor the polynomial, which systems like Mathematica automatically will win. Oct 14 at 8:10

# Hearts KotH

Your challenge, should you choose to accept it, is to write a Java bot to play a simplified version of hearts.

Hearts is a four-player trick-based card game. To start a round of hearts, each player is dealt 13 cards. The player who has the two of clubs starts by playing the two of clubs. Going around the circle each player plays another card, in the same suit as as the first card if possible. Once every player has played one card, the trick is complete, and goes to the player who placed the highest valued card in the original suit (aces are high). The player who takes the trick is responsible for all of the points contained in the trick, as well as leading the next trick. This continues until all players are out of cards, at which point the hand is complete.

During a hand, each heart taken is worth 1 point and the queen of spades 13 points. If during the course of a hand one player receives all 26 points, they shoot the moon and receive zero while everyone else receives 26 points. The game ends once a player clears 100 points, at which point the player with the lowest score wins.

## The Challenge ​

Write a Java 11 bot extending a (todo) abstract class. A new bot will be instantiated for each hand. Every combination of 4 bots will play one game with each other. After all of the games are complete, the bots will be scored on the total number of wins (higher is better), with the tiebreaker being the average score per game (lower is better).

Tampering with the controller, tampering or instantiating other bots, damaging my computer, taking an excessively long time to complete a turn, failing to compile, violating standard loopholes, or throwing a runtime Error is strictly prohibited and will result in disqualification. Throwing an exception will result in a 1 point penalty and the controller playing for you in an unspecified manner. Nondeterministic bots and storing data between both Hands and games are permitted.

## Meta:

Is this clear enough?

I haven't written the controller yet, is there any data in particular that you would like to see the bots receive (among other things, a way to determine the legality of the move, as well as cards played are already passed in)?

• How are the cards distributed? If it's random, I'm worried there won't be much strategy possible and it'll mostly just be a random outcome. Oct 5 at 17:22
• @RedwolfPrograms the plan right now is random, but it doesn't have to be. My theory was that since there are typically 5-10 hands per game in real life, the law of large numbers would win out. In real life, while the game is slightly more complicated all strategies boil down to card counting and probability-based heuristics anyway, and you can get quite good at it. Oct 5 at 17:33
• It seems like card counting and probability based heuristics would both make for a pretty boring KotH, since while they'd be challenging to keep track of as a human, a bot could be optimized without too much work being necessary. Oct 5 at 19:04
• @RedwolfPrograms the way things are set up currently, the relatively boring task of counting cards is mostly handled by the controller. Also, most KotH challenges have been probability based heuristics, like the various rock paper scissors challenges and the various prisoner's dilemma based challenges. Still, if the consensus seems to be that this won't do very well I will head back to the drawing board. Oct 5 at 20:35

# Optimize my Cruise Control

My cars cruise-control functionality has 4 different methods of adjustment, all using a single stalk. They are as follows:

• Hard press up (press until you feel the click): +5 mph
• Soft press up (press lightly, but not to the click): +1 mph
• Soft press down (press lightly, but not to the click): -1 mph
• Hard press down (press until you feel the click): -5 mph

If your current speed is not a multiple of 5, a hard press will take you up/down to the nearest 5 multiple.

The challenge is to write a function that takes your current speed and target speed as parameters, and outputs the shortest sequence of stalk inputs to get from current -> target speed.

Rules:

• Take 2 integers as input
• Return a list/iterable/whatever of the minimum actions needed to get to target speed

Examples: (U is hard up, u is soft up, d is soft down, D is hard down)

[5, 6] -> [u]
[20, 37] -> [U,U,U,u,u]
[42, 45] -> [U]
[16,23] -> [U,u,u,u] or [U,U,d,d]


## currently known issues

• needs more examples
• similar to the Optimal Change problem.

## Other possible improvements

• Maybe make it a more generalized function that takes 4 inputs [v_current, v_target, delta_small, delta_large]. This would have the effect of complicating the logic and making the problem a bit less trivial.

# Write an interpreter for "MathScript"

I had an idea for a new language, it's called MathScript! I got the idea from Mathematica.

Basically, this is how it works:

• Functions are called by using the following syntax: FunctionName{some, arguments, separated, by, commas}
• The builtin functions are Display, Add, Sub, Mul, IntDiv, FloorDiv, Pow, Factorial, FibN, and OddEvenQ

The first few function names are pretty descriptive. IntDiv and FloorDiv calculate the integer division and floor division, respectively. FibN calculates the N'th Fibonacci number, and OddEvenQ returns 1 if a number is even and 0 if it is odd.

• Variables are created as so: <Name> :: <Value>
• The syntax for changing variables is the same as the syntax to change variables.
• The syntax for for loops are as following: LoopN{<n>} :: [some, statements, separated, by, commas]

# Test Cases

---
---

---
a :: 1
LoopN{3} :: [a :: Add{a, 1}, Display{a}] => 2 <newline> 3 <newline> 4 <newline>
---

---
odd_or_even0 :: OddEvenQ{num}
num :: Factorial{num}
odd_or_even1 :: OddEvenQ{num}
Display{odd_or_even0} => 0
Display{odd_or_even1} => 1
---


# Scoring

This is , so the fastest answer wins. The testing will be on an i7 processer Windows 10 machine. The test case will be LoopN{10} :: [LoopN{10} :: [Display{Add(2, Pow{3, 4})}]].

# Some clarification

Whitespace is ignored. Trailing commas in function arguments is allowed. You can assume that the input will always be correct. Display outputs something to stdout. Case is significant. (e. g Loopn != LoopN) If there are multiple statements, they can be separated by newlines or nothing at all. Blank lines can be anywhere.

# Language types

The types are the string (specified between double quotes or single quotes), the integer, and the float. Integers can be specified using normal numbers like 5 and 7383. The integer limit is [-232, 232] (32-bit). Floats can be specified using normal math notation, so these are all valid floats:

2.0
3.4
3.141592653
.8
2.


The LoopN function's first argument can be a integer literal, or a predefined variable.

# One Final Note

Compilers are allowed.

# Meta

• Any suggestions?
• Anything to clarify?
• Is whitespace significant, or only used to separate tokens? Are trailing commas allowed? Will the input ever have a syntax error? What does display do? I assume it prints out something, but how does it print it out? Is case significant? If so, shouldn't your second test case should read LoopN? In your first test case you use Print, did you mean Display? The second test case seems to have multiple statements; how are statements separated? Are they always separated by newlines, or can it be any token separator? If they're always separated by newlines, can newlines appear anywhere else? Sep 26 at 21:28
• Every challenge has to have an objective scoring criterion; what is it for this challenge? Consider code-golf or fastest-code. Sep 26 at 21:29
• I see that you've tagged this fastest-code; this scoring criterion often involves a bit more work for the author, as all answers have to be scored on the same machine for fairness. If you use this scoring criterion, you should specify what machine you'll be running submissions on, as well as what test cases the input will be run on. Sep 26 at 21:33
• Some feedback re the language itself: there's no obvious conditional construct, though one can use LoopN{<cond>} :: [ <body> ] if cond is known to be either 0 or 1, and Pow{0, Pow{0, Pow{<cond>, 2}}} to convert <cond> to 1 if non-zero, or 0 if 0. Additionally, there's no obvious way to check for equality, other than using something like Pow{0, Pow{Sub{A, B}, 2}}, and no obvious way to check for greater than or less than. Sep 26 at 21:42
• More questions re the challenge: What are numbers? Are they all ints? All floats? What's the difference between IntDiv and FloorDiv? What are all of the valid ways to specify a number? What precision should be supported for numbers? Possible options include arbitrary precision (this would be helpful towards making the language turing-complete), implementation-defined (e.g. whatever your language supports), or something specific like IEEE-754 double precision floats. Sep 26 at 21:46
• How does LoopN work? Can you pass it a computed value, or does it have to be a number literal? If it's a computed value, is it recomputed every time, or stored after the first time? If it's recomputed, you could create while loops, which would be helpful for turing-completeness. Sep 26 at 21:48
• How many arguments do each of the functions take? What happens if a function is called with an incorrect number of arguments? Can that be assumed not to happen, or should some kind of error be outputted? Sep 26 at 21:50
• Does FibN support a non-positive index? If not, can it be assumed to not be called with that, or should an error be outputted? What happens if you divide by zero? Sep 26 at 21:52
• What happens if you call Factorial with a negative number? Does Factorial support an input of 0? (it probably should) Sep 26 at 21:53
• If floats exist in the language, what does OddEvenQ do if you pass it a non-integer? Sep 26 at 21:54
• Are compilers allowed? Sep 26 at 22:07
• The second test case are looking weird, isn't the output should be 2 \n 3 \n 4 \n?
– okie
Oct 4 at 4:59
• I feel like you should add more MathScript programs to test with. An answer could optimize solely for the single test case you've given.
– rues
Oct 6 at 1:01

# Balanced Bracket Sequence

## Iterative Quine

• Welcome to Code Golf and Coding Challenges, and thank you for using the sandbox! Could you give a rough example of what a submission might look like?
– rues
Oct 8 at 21:42
• @user hi! sorry for taking so long, heres my rlly rough example, obvs i can write it better for the actual challenge but i just wanted to get the point across. lmk any feedback u have :) Oct 9 at 0:41
• Thanks for the example (it's alright if it's rough, a lot of challenges do that). Unfortunately, as hyper-neutrino said in chat, this feels like two challenges in one: one about simply printing a string, and the other about making a quine, and we already have challenges to do that. Instead, could you spice up this challenge somehow? Maybe you could make people print programs that print larger programs that print even larger programs or something like that?
– rues
Oct 9 at 12:38
• @user Oh that is a good point, hmm. Well ok, i have two ideas then: note to self: there is no newline on mobile, hitting return just posts... 1. Have the program in lang A print a larger program in lang B, which prints a larger program in lang A.. and then get scored in iterations and how short the original code is? or 2. Lang A prints a program in Lang B which prints a program in lang C which is a quine, and youre scored on iterations and total size of all of the code? those are my ideas, pls lmk any feedback :) i may check out the chat later as well but i want to stay here just for now Oct 9 at 15:54
• i guess variation 1 could technically go on forever via simple tricks where each one extends the other by 1. id have to workshop that part hmm Oct 9 at 15:59
• Well, to the chat I go. I do have a new, probably better idea for this that stays within the spirit Oct 11 at 18:30

# Pattern in Prime

Given a positive integer less than 100 with no preceding zeros we have to find all 12 digit primes that contains the maximum number of time the given pattern.

Note: Pattern's occurance can overlap. For example 11 occur 6 times in 1111111

Example:

pattern = 1 , count = 13 the maximum occurance is in 111111110111, eleven, and those 12 digit primes are {101111111111,111011111111,111111011111,111111110111,111111111101,111111111511,111111111611,111111211111,111113111111,111211111111,111511111111,116111111111,311111111111}

pattern = 22 , count = 1 {522222222229}

pattern = 69, count = 162

pattern = 37, count = 151

Output format: first line should be count of such primes, and then print the primes in sorted order

If possible while answering please write a short explanation of what you did. This is , so the shortest answer in bytes per language wins.

# Best Rotation

If we rotate a raster image by some angle that is not a multiple of $$\90°\$$, we will have to use some kind of interpolation. Depending on what kind of interpolation method we use, we get a better or a worse quality. This is especially apparent if we repeat the rotation multiple times. In the following image we se the original on the top left, and then the result of different interpolation methods when used to rotate the original $$\360\$$ times by $$\1°\$$.

$$\\renewcommand\phi\varphi\$$

# Challenge

Given some angle $$\\phi\$$ Your task is to find a method to find a (deterministic) function $$\f_\phi\$$ that takes some image $$\I\$$ and rotates it by $$\\phi\$$.

# Scoring (not solved yet)

META this is the issue. Ideally we'd like to have some objective criterion. But so far I have not managed to find one that cannot be gamed:

1. If we just let the participants rotate an image by some angle $$\\phi\$$ how can we then compare it to the "exact" solution? Maybe their method is better than the best standard method, even if they have to apply it repeatedly. So it seems we can only truly check against a total rotation that is a multiple of $$\90°\$$.

2. Let's say we say we use an angle of $$\\phi = 2\pi/n\$$ and let them apply their "rotation" $$\n\$$ times to measure e.g. the $$\l^2\$$-error $$\E = \Vert I - f_\phi(\ldots f_\phi(I)\ldots)\Vert_2\$$ . This means they could just use $$\f_\phi = id\$$.

3. If we instead use a total rotation of e.g. $$\\pi/2\$$ (that is $$\\phi = \frac{\pi}{2n}\$$, with $$\n\$$ rotations). Then the participants could just use some permutation of pixels that just happens to rotate the image after $$\n\$$ rotations exactly (or maybe exactly except for some pixels).

So does anyone have another suggestion of how to objectively measure it without introducing any hand-wavey rules?

• My gut feeling is that if this problem were phrasable in an objective manner it would basically already be solved.
– Grain Ghost Mod
Oct 14 at 21:50
• @WheatWitch Maybe it is solved but I don't think the objective "rules" matter - I'm just trying to make rules that don't have loopholes. For instance for the approach of measuring the error of repeted rotations totalling 90° I'd like that the intermediate images also look very much like the original. Any "sane" algo would obey that, but I just struggle to find a way to enforce this without any hand-waveyness. Oct 15 at 11:48
• As an alternative I'm considering actually dropping the idea of seeking "sane" algorithms and encouraging pathologic algorithms that manage to do great 90° rotations while having visually nonsense intermediate images. But I think that this is trivial, as I outlined in (3.). Oct 15 at 11:50
• A third idea would be some kind of king-of-the-hill where each submission will be paired with every other submission to rotate the image a total of 90° and then find some kind of average score. Oct 15 at 11:51

# Halve Code Regen

TODO: This is a horrible title.

Your challenge is to write a program, and when I half the program, the output must stay the same. Then, I will halve it and add the last two characters, and the output should be the same with the program's last two characters at the end.

Sometimes the code can't be halved evenly, and when that happens, I will do something similar to floor division:

blahy => bl
horse => ho
meddle => med (regular halving)
oof => o


#### Example for "the output should be the same with the program's last two characters at the end"

Let's say we have this code:

q|w_a2e(o+2ei2ere


and the output is

q|w_a2e(o+2ei2ere


when I change it to

q|w_a2e(o+2ei2erere


by adding the last two characters (re), the output should look like

q|w_a2e(o+2ei2erere


(Note the extra re at the)

# Rules

• The program must have at least 2 characters.
• Standard loopholes apply
• The output cannot be empty.

# Scoring

This is , so the answer with the least bytes wins.

#### How I came up with the random code in the example two sections ago

q means quine. | is a separator. w_a2e means when the last two characters are added to the end. (o+2e means add the last two characters to the end. i2ere means ignore a repeated 2e at the end.

# Meta

• Is this even possible?
• If so, any other suggestions?
• I think this would be more interesting if multiple halves of the program had to work. Otherwise it's just output something (or nothing since it doesn't look like you've ruled that out.) and then pad the program out with comments.
– Grain Ghost Mod
Sep 27 at 13:30
• @WheatWizard Fixed. Any idea for a better title? Sep 27 at 13:34
• That's not quite what I meant. I mean that splitting the same program in half multiple ways ought to preserve the output.
– Grain Ghost Mod
Sep 27 at 13:39
• Also you should definitely restrict the output further. At the very least it should have to be non-empty. You should also require the programs to be at least 1 or 2 bytes long.
– Grain Ghost Mod
Sep 27 at 13:39
• @WheatWizard Fixed. Sep 27 at 13:43
• I still can't decide on a better title, though. Sep 27 at 14:17
• I don't understand what the "the output should be the same with the program's last two characters at the end" part means. Can you show a full example of what you do to the program? Oct 16 at 19:05

Integer points on Hyperspheres

Given two non-negative integers $$\r\$$ and $$\d\$$, write a program that will output the number of integer points that lie on all hyperspheres of dimension $$\d\$$ or lower with radius $$\r\$$ or lower.

For example, given $$\r = 5, d = 2\$$, the program would do something like this:

The hypersphere of dimension 2 is a circle. The radius is 5. There are 12 integer points on this circle, as follows: $$(5,0),(4,3),(3,4),(0,5),(-3,4),(-4,3),(-5,0),(-4,-3),(-3,-4),(0,-5),(3,-4),(4,-3)$$

If the radius is 4, there are 4 integer points: $$(4,0),(0,4),(-4,0),(0,-4)$$

If the radius is 3, again it's 4 integer points. If the radius is 2, again 4. Radius 1 - again, 4. Radius 0 has only 1 integer point. If we add all these up it's 12 + 4 + 4 + 4 + 4 + 1 , or 29 points total for the 2 dimensional hyperspheres with radius $$\<=5\$$.

Now if we take the dimension 1 hypersphere, it is interpreted as 2 points in a one dimensional space, distance r from the origin. For example the 1 dimensional hypersphere with radius 5 has only two points, $$(5),(-5)$$ and their coordinates are only single dimensional. So, the dimension 1 hypersphere with radius 5 has two integer points. The dimension 1 hypersphere with radius 4 also has 2 integer points, and so on. The total integer points on all 1 dimensional hypspheres with radius 0 to 5 is 2 + 2 + 2 + 2 + 2 + 1, or 11.

The dimension 0 hypersphere is defined for this challenge to have 0 points.

So the final output of a program with input $$\r = 5, d = 2\$$ will be 29 + 11 + 0, or 40.

• You may assume that r and d will be low enough so that the integer type of your language will be large enough so that it can represent the answer. In other words if your language has only 16 bit integers, then you can write a program that assumes r and d will be low enough so that the final answer is between 0 and 65535.

• This is Code Golf, lowest # of bytes wins

• This is essentially Pythagorean triples but generalised to d-tuples, right? (and allowing 0) Oct 18 at 10:42
• i think so, yes, that sounds correct... Oct 19 at 2:11

# Same String Regardless of Repetition

## Challenge

Write a full program that prints a string that has a length of at least 1. When the source code is repeated any amount of times, that string should still be outputted. For example, if my source code is ABC and it prints Hello, World!, then ABCABC will still print Hello, World! and ABCABCABC will also print Hello, World! and etc.

## Rules

• It has to be a full program that takes no input (or have an unused input if this is impossible) and prints the string to STDOUT.
• The program and the string have to be at least 1 byte long.
• The strings that are outputted with each repetition have to be exactly the same. Trailing or leading spaces make the strings different.
• There must be only one output.
• There is no code between repetitions.
• This is code-golf, so programs are scored in bytes, with less bytes being better.
• I’m not too sure if “comments are not allowed” is an easy rule to enforce… everything else seems fine, +1 from me
– W D
Oct 22 at 2:47
• Maybe require the program to print a number alongside the Hello, World! to enforce that the code has to account for the repetitions? so ABC => 1. Hello, World!, ABCABC => 2. Hello, World! etc., and just make sure to specify that code can't read itself? This way, if you just comment out the rest of the code, it will fail. Oct 22 at 12:47
• To avoid comment abuse and answers along the lines of print('Hello, World!');exit; you could require the program to be irreducible. However I suspect this challenge will still be really easy in most golfing languages. Here is an example (2 byte program repeated 3 times), and I don't even know Japt. Oct 24 at 3:26

# Make an ASCII Quasi-Golden Rectangle

While this challenge does involve making a golden rectangle, we're going to do something a bit different.

Given an input n, using three distinct, non-whitespace characters (+s, |s, and -s will be used in examples) as well as spaces and newlines, generate a grid of n squares that form a rectangle.

## Rules

• Each square of your rectangle must use one character for corners, one for vertical lines, and one for horizontal lines.
• Within each square, there must be an x by x region of whitespace, where x follows this sequence (Fibonacci sequence, but with 1s added to account for the border).
• Besides the first two 1 by 1 squares, no two squares may be the same size.
• Your output must include exactly n squares (or n + 1 if you're 0-indexing, which is allowed).
• Adjacent squares must share their borders.
• Orientation does not matter, so reflections and rotations are OK.
• Leading/trailing whitespace per line or at the end of the output is OK, so long as it doesn't disrupt the rectangle.

## Correct Examples

Examples are 1-indexed, but bear in mind that you are allowed to 0-index. n = 1: (Note that this is the only valid output for n = 1, save for any trailing whitespace.)

+-+
| |
+-+


n = 2:

+-+-+
| | |
+-+-+


The other valid answer would be

+-+
| |
+-+
| |
+-+


n = 3: (Note the internal +, as it is still at a corner)

+---+
|   |
|   |
|   |
+-+-+
| | |
+-+-+


n = 4:

+-----+---+
|     |   |
|     |   |
|     |   |
|     +-+-+
|     | | |
+-----+-+-+


## Incorrect examples

Extra borders

+---++-+
|   || |
|   |+-+
|   || |
+---++-+


Missing corner

+---+-+
|   | |
|   |-+
|   | |
+---+-+


Wrong size

+-----+--+
|     |  |
|     |  |
|     +--+
|     |  |
|     |  |
+-----+--+


Disruptive whitepsace

+-+

| |

+-+



## Scoring

Code golf. Shortest wins.

# Meta

Is the part with the OEIS link phrased ok? And the parts about indexing?

In general, is this clearly written?

• If you measure border to border, then your square sizes are 2, 2, 4, 6, 10...
– Neil
Oct 22 at 9:16
• @Neil oh, so it is Fibonacci-like. I can work with that, thank you. Oct 22 at 12:27

In 1960 Andrey Kolmogorov conjectured that any algorithm to multiply two integers would require $$\\Omega(n^2)\$$* steps.

Within a week of presenting this conjecture it was proven false by graduate student Anatoly Karatsuba. Karatsuba's algorithm is an algorithm to multiply two numbers which takes in the worst case $$\O(n^{\log_2 3})\$$ time.

Your task will be to implement this algorithm. You will receive as input two binary strings. These can be lists of ints, arrays of bools etc.

You should then output the binary representation of their product in the same format.

It's hard to say in precise terms what it means to implement a particular algorithm. So here we will require only that your algorithm have asymptotic time complexity of $$\O(n^{\log_2 3})\$$ and $$\\Omega(n^{\log_2 3})\$$ where $$\n\$$ is the total number of bits in the input. Which is to say that it is neither better nor worse than Karatsuba's algorithm up to a constant factor.

This is so answers will be scored in bytes with lower bytes being the goal.

* In this challenge we will use $$\f\in \Omega(g)\$$ to mean that $$\\displaystyle\limsup_{x\to \infty}\dfrac{f(x)}{g(x)}\$$ does not converge to $$\0\$$. Also stated as $$\f \in \Omega(g) \iff \exists k.\forall x.\exists x'.f(x')\geq k\cdot g(x')\$$. This is the Hardy-Littlewood definition.

• Python is known to use the exact algorithm under the hood, and it may be true for some other langs as well. Is it OK to use such built-in? Also, is it OK to use even faster multiplication and just slow it down with dummy recursion? Oct 26 at 5:24
• As bubbler mentioned, I would suggest remove the lower bound from the question, as the answer may implement a better algorithm (I don't know if it exist or not) and then slow it down by appending some dummy operations.
– tsh
Oct 26 at 6:28
• Also, you should explain what does $n$ means in the formula (length of input). As it is not very clear to readers.
– tsh
Oct 26 at 6:29
• @tsh is "where n is the total number of bits in the input." unclear? I'm not sure how I can explain it more directly than that.
– Grain Ghost Mod
Oct 26 at 7:50
• @Bubbler RE builtins: I don't ban builtins, I don't think it makes challenges better and only leads to confusion. It's up to the user whether they want to have fun. RE faster algos: The point of this challenge to implement this algorithm, not faster ones. The lower bound is there to encourage the algo. If you use a faster algorithm you are going to have to pay the cost to pad it out to the correct run time.
– Grain Ghost Mod
Oct 26 at 8:33
• I guess it could be better to further specify "the total number of bits of the two input numbers". Also probably move it closer to the first use of n. Oct 26 at 8:52
• @Bubbler Technically the $n$ in the initial statement is a little more complex. It's just a explainer so I don't think it's worth getting into all the details when in basically works like the default meaning of $n$.
– Grain Ghost Mod
Oct 26 at 9:07

# Solve linear equations over the integers

All variables in this question are integer valued.

# Input

4 integers w, x, y, z. They can be positive or negative and will be less than 1048576 in absolute value.

# Output

The general solution to the equation.

$$\ aw+bx+cy+dz = 0 \$$.

The variables $$\a, b, c, d\$$ must all be integer values.

# Output format

Your output should consist of three tuples each with four parts, one for each of the values a, b, c, d. Let me explain by example:

Input: -118, 989, 918, -512

c = 9 n_0 + 256 n_1 + 81 a
d = 20 n_0 + 459 n_1 + 145 a


Explanation: n_0 and n_1 are integers that you can set to anything you like. The solution says: a can also be set to any integer value, b must be twice whatever you set n_0 to. This means that a can be set to any integer, c can now be calculated in terms of three variables we have already set and so can d.

The format of your output should be 3 tuples (#,#,#,#), (#,#,#,#), (#,#,#,#). We can assume three free integer variables n0, n1 and n2 and so (a,b,c,d) = (#,#,#,#)n0 + (#,#,#,#)n1 + (#,#,#,#)n2. In the example above the output would therefore be:

Output: (0, 2, 9, 20), (0, 0, 256, 459), (1, 0, 81, 145)


# Examples

Example one:

 Input: -6, 3, 7, 8

Answer:  c = 2a + 3b + 8n
d = -a - 3b - 7n
n is any integer

Output: (1, 0, 2, -1), (0, 1, 3, -3), (0, 0, 8, -7)


Example two:

Input: -116, 60, 897, 578

Answer: c = 578 n + 158 a + 576 b
d = -897 n - 245 a - 894 b
n is any integer

Output: (1, 0, 158, -245), (0, 1, 576, -894), (0, 0, 578, -897)


Example three:

Input: 159, -736, -845, -96

Output: (1, 0, 27, -236), (0, 1, 64, -571), (0, 0, 96, -845)


# Discussion

To understand this challenge further it is worth looking at this possible general solution which does not work [(z, 0, 0, -w), (0, z, 0, -x), (0, 0, z, -y)]. The problem with this is that there are solutions to the problem instances above which are not the sum of any integer multiples of those tuples. For example: take input -6, 3, 7, 8 from Example 1. The proposed solution would give the tuples:

(8, 0, 0, 6), (0, 8, 0, -3), (0, 0, 8, -7)


Why doesn't this work?

There is a solution for this instance with a = 1, b = 1, c = 13, d = -11 because -6+3+7*13-11*8 = 0. However there are no integers n_0, n_1, n_2 to make n_0 * (8, 0, 0, 6) + n_1 * (0, 8, 0, -3) + n_2 * (0, 0, 8, -7) = (1, 1, 13, -11) .

• I expect the most common form of outputs would be (a,b,c,d) = (#,#,#,#)x + (#,#,#,#)y + (#,#,#,#)z, where #s are some integer constants and x,y,z are free variables. In this case, may I simply output the three vectors of length 4? Oct 26 at 2:35
• @Bubbler. The inputs are labelled w,x,y,z. I assume your x,y,z are not those?
– user7467
Oct 26 at 3:32
• I mean, (a,b,c,d) = (#,#,#,#)n0 + (#,#,#,#)n1 + (#,#,#,#)n2 if it reads better. Or in four separate equations: a = #n0 + #n1 + #n2; b = #n0 + #n1 + #n2; .... Oct 26 at 3:34
• @Bubbler what worries me slightly about that formulation is that it might force the coefficients to be really large. You seem to get much smaller coefficients if you express the variables in terms of previous ones and some free variables.
– user7467
Oct 26 at 3:37
• No, the coefficient size is irrelevant. Your example output in my format is a = 0*n_0 + 0*n_1 + 1*n_2; b = 2*n_0 + 0*n_1 + 0*n_2; c = 9*n_0 + 256*n_1 + 81*n_2; d = 20*n_0 + 459*n_1 + 145*n_2, or (a,b,c,d) = (0,2,9,20)n_0 + (0,0,256,459)n_1 + (1,0,81,145)n_2 in short. I'm only asking about the output format here. Is outputting [[0,2,9,20], [0,0,256,459], [1,0,81,145]] OK? Oct 26 at 3:39
• Let me think if you would ever have to express d in terms of c which in turn is expressed in terms of b.
– user7467
Oct 26 at 3:44
• Such situation can always be simplified to my form using substitution followed by expansion. Oct 26 at 3:47
• Yes. That’s where my concern about coefficient size comes in I believe.
– user7467
Oct 26 at 3:49
• Why are you concerning about the coefficient size in the first place? Isn't it plain code golf and we're allowed to output any solution that solves the problem I assume? Oct 26 at 3:52
• Maybe I shouldn’t worry about it. You can solve the problem so that you get ugly answers with huge coefficients (which is what sympy does). I thought it would be good to avoid that.
– user7467
Oct 26 at 4:11
• Thanks for your understanding. But still you didn't answer my original question about the output format. Oct 26 at 4:15
• If you have to scale your byte count by a factor which is how much larger (in absolute value) your largest coefficient is than the examples is that then code-challenge?
– user7467
Oct 26 at 4:16
• I really like your output format. I am just trying to work if it causes problems which I want to avoid. An alternative is to have 3 coefficients for a, 4 for b, 5 for c and 6 for d. That would enable you to express each one in terms of both the free variables and the other variables.
– user7467
Oct 26 at 4:17
• No, mixing code length with some other metric doesn't work (believe me, I tried it once and failed). Just go pure code-challenge (must run in reasonable amount of time, smallest coefficient wins) or pure code-golf (no time limit, output anything valid). For the former, you also need to prepare a good amount of hidden test cases (test-battery), otherwise you can't avoid hardcoded solutions. Oct 26 at 4:23
• The point is that "fully general format" as in your examples is way too tedious to actually output in non-Mathematica languages, so I'm suggesting a structured output which tries to simplify that. And all possible outputs can be expressed in the format I'm suggesting. If you decided for code-golf, you should absolutely stop worrying about the coefficient size. Please. Oct 26 at 4:41

# Is someone eavesdropping? (WIP)

Alice and Bob, who are quantum physicists, are being watched by Eve, a quantum FBI agent. Eve has quantum tunneled underneath Bob's house and is tapping all his quantum channels. Luckily, Alice and Bob are using the BB84 protocol to exchange quantum keys to encode their quantum messages. Your job is to write a program/function to help Alice and Bob determine if Eve is evesdropping.

# Calculate Smith normal form of an integer matrix

Given an $$\m \times n\$$ matrix of integers A, there exist a $$\m \times m\$$ matrix P, an $$\m \times n\$$ matrix D, and an $$\n \times n\$$ matrix Q such that:

• P and Q are unimodular matrices (i.e. matrices which are invertible and whose inverses are also integer matrices);
• D is diagonal;
• each diagonal entry $$\d_{ii}\$$ of D is nonnegative; and
• $$\d_{11} \mid d_{22} \mid \cdots \mid d_{nn} \$$.

Furthermore, the matrix D is unique in this representation.

One common way to calculate D is via an algorithm that looks like a combination of the Euclidean algorithm for calculating gcd and Gaussian elimination -- applying elementary row and column operations until the matrix is in the desired format for D. Another way to calculate D is to use the fact that for each i, $$\d_{11} d_{22} \cdots d_{ii}\$$ is equal to the gcd of all determinants of $$\i\times i\$$ submatrices (including non-contiguous submatrices) of A.

## The challenge

You are to write a function or program that calculates the Smith normal form of an input matrix. The output may either be in the form of the full matrix D, or in the form of a list of the diagonal entries of D. In an imperative programming language, it is also acceptable to write a function that takes a matrix by reference and mutates the matrix into its Smith normal form.

## Rules

• This is code-golf: shortest code wins.
• Standard loophole prohibitions apply.
• You do not need to worry about integer overflow, if that applies in your language.

## Examples

1 2 3       1 0 0
4 5 6  ->   0 3 0
7 8 9       0 0 0

6  10       1 0
10 15  ->   0 10

6 0  0        1 0  0
0 10 0   ->   0 30 0
0 0  15       0 0  30

2 2       2 0
2 -2  ->  0 4

2 2  4 6       2 0 0 0
2 -2 0 -2  ->  0 4 0 0


Note: Mathematica already has a built-in to calculate Smith normal form. As such, you can use this to play around with test cases: Try it online!

• Three new matrices are introduced at the top of the post and it isn't immediately obvious which one is the Smith normal form. Suggest stating that it's D after the first set of bullet points. Nov 9 at 23:34
• Will input word contains duplicate characters? What is expected output for top, [to, two, too], equipment, [queue, queen, quine]?
– tsh
Oct 26 at 6:24
• Updated examples. Oct 26 at 15:01

# Fill the (possibly leaky) bowl

## Challenge:

Given an ASCII art of a (possibly leaky) bowl consisting of a distinct random non-whitespace and non-~ character, fill it completely with ~ characters. If the bowl is leaky, fill the bottom row below the bowl and a stream of water emerging from that, with the intended amount of ~ if the bowl would not have been leaky.

For example:

Regular bowl:

#      #       #~~~~~~#
#    #    →    #~~~~#
####           ####


Leaky bowl:

00     00   →   00     00
00   00         00   00
000 0         ~~000~0~~
~
~
~


If there wouldn't have been a leak, it could have contained eight ~. Instead, the bottom row including leak is now filled with five ~, and the remaining three ~ are below the leak.
(Imagine the bowl standing on a table, so the five ~ at the bottom row of the bowl are on the table, and the ~ vertically below the leak are dripping of the table.)

## Challenge rules:

• The leak is guaranteed to be a single gap
• The leak is guaranteed to be at the bottom row
• I/O is flexible. Could be a multi-line string; a list of lines; a character matrix; etc. You're allowed to pad the input with trailing spaces to make the input a rectangle.
• The character used for the bowl can be any printable ASCII character, except for the ~ (and whitespaces) of course.
• The bowl isn't necessary symmetric or a clean shape.
• If the bottom row contains more space characters than inside the leaky bowl (see the third leaky bowl test case below), we still fill the entire bottom row of the output regardless, but there won't be any additional ~ for the stream of course.
• The bowl can be in an irregular shape (see some of the test cases), but the top ridges are guarantees to be on the same line/'row'.
• For the sake of this challenge, there won't be any smaller inner bowls (if we'd imagine it as a 3D bowl). So every space in the bowl will always flow towards the leak. (See the fourth leaky bowl test case below, which doesn't have #~# # as its second line.)

## General rules:

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

## Test cases

Regular bowls:

#      #       #~~~~~~#
#    #    →    #~~~~#
####           ####

!!!        !!       !!!~~~~~~~~!!
!!      !    →      !!~~~~~~!
!!!   !             !!!~~~!
!!!!                !!!!

4   4       4~~~4
4 4 4   →   4~4~4
44444       44444


Leaky bowl:

00     00   →   00     00
00   00         00   00
000 0         ~~000~0~~
~
~
~

^^^        ^       ^^^        ^
^^      ^   →      ^^      ^
^^^   ^            ^^^   ^
^ ^        ~~~~~~~~^~^~
~
~
~
~
~
~
~

@@@ @@@   →   @@@ @@@
@ @         ~~@~@~~

#   #   →   #   #
# # #       # # #
### #       ###~#
~
~
~
~

• In all the examples and test cases the left and right edges of the bowl are the same height. Will this always be the case? Nov 9 at 23:25
• @Dingus I will clarify this, but yes, the bowls can be irregular, but the top ridges will be on the same 'row'. Nov 10 at 7:40
• I would say it could be hard to define a bow in your question. Also, in your testcases, some bows doesn't follow "decreasing, bottom, then increasing" pattern, which may have issue when they are leak. For example, will "#...#\n#.#.#\n###.#" be #...#\n#~#.#\n###~#\n...~\n...~\n...~? The left part may contain 1 cell water actually.
– tsh
Nov 11 at 9:43
• @tsh I'll add that as test case and clarify, but your test case would have its second line as #.#.# and one additional ...~ line below it. The bowl will never have any inner bowls for the sake of this challenge. (And your test case would in that case be fine if we'd imagine it as a 3D view with just a pillar in the middle it can flow around to towards the leak.) Nov 11 at 9:54
• @KevinCruijssen As these bows are allowed, what about "#..#./#.###/###.#"? Is this still a bow? Does it leak?
– tsh
Nov 11 at 9:58
• @tsh That would be non-leaky: #~~#./#~###/###.#. Although those kind of test cases does make it a bit more tricky. Both for the definition of a 'bowl', as well as for those creating answers for this the challenge. I'll have to think for a moment whether I want to allow such bowls or not. Excluding them in the rules would mean adding two rules: a guarantee stating the base / bottom row is always an uninterrupted edge; a guarantee that the top ridges are always at the very top-left and top-right, but it does impact the complexity of the challenge quite a bit. 🤔 Nov 11 at 10:25
• @KevinCruijssen Without these testcases, all testcases you listed may simply be tested by checking if letters in bottom line are continuously. Although "#...#\n###.." may also break such assumption, but it could be fixed by checking the bottom 2 rows instead.
– tsh
Nov 12 at 1:44

# Validate a Metroid password code-golfdecision-problemencodingchecksum

Released in 1986, Metroid was a popular action-adventure game for the Nintendo Entertainment System. Owing to the technical limitations of the day (and a cost-cutting decision not to include a battery in the cartridge), game progress is saved using passwords instead of save slots. The password encodes data about the game state, including things like what equipment Samus (the protagonist) has in her inventory, her location, and which bosses have been killed.

Your task in this challenge is to determine whether a given string is a valid Metroid password.1

More details are given below but in summary, a valid3 Metroid password:

• consists of 24 characters,
• contains only characters from the Metroid character set, and
• passes checksum verification.

Each character encodes 6 bits of data for a total of 144 bits/18 bytes.

Metroid recognises 65 characters: the digits 09, uppercase and lowercase letters AZ and az, question mark ?, dash -, and space  .4 Excluding the space, these characters are mapped to unique values in the range 0–63 according to their 0-indexed position in the following string:

0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz?-


Spaces are special. It's arguably easiest to treat them as if they have a value of 63, like dashes do. However, spaces and dashes are not always interchangeable, as we will see below.

## Decoding the password and calculating the checksum

1. Replace each password character with the 6 bit binary number corresponding to its value. For example, the letter S has a value of 28, which is 011100 in binary.

There is one exception to this rule. If a character is followed by a space and that space's 0-indexed position in the password is not a multiple of 4, set the two least significant bits for the character to 11. For example, an S followed by such a space becomes 011111. (This special case is why some references describe spaces as having a value of 255.)

The result is a 144 bit/18 byte binary string, $$\p\$$.

2. Rotate only the first 128 bits of $$\p\$$ to the left $$\r\$$ times, where $$\r\$$ is the 17th byte of $$\p\$$. Call the result $$\p^\prime\$$.

3. Let the checksum $$\c\$$ be the 8 least significant bits of the sum the first 17 bytes of $$\p^\prime\$$. Then the password is valid if the 18th byte of $$\p^\prime\$$ equals $$\c\$$.

#### Example

The password to validate is you HAvE BeEn termiNated.

1. Convert to binary, noting that the first and third spaces (but not the second) trigger the special case behaviour (spaces shown as underscores for clarity):

y     o     u     _     H     A     v     E     _     B     e     E     n     _     t     e     r     m     i     N     a     t     e     d
111100110010111011111111010001001010111001001110111111001011101000001110110011111111110111101000110101110000101100010111100100110111101000100111

2. The 17th byte is 01111010, so rotate the first 128 bits to the left 122 times:

010011111100110010111011111111010001001010111001001110111111001011101000001110110011111111110111101000110101110000101100010111100111101000100111

3. The sum of the first 17 bytes is $$\100100100111_2\$$ (2343) so the checksum is 00100111, which matches the 18th byte. The password is valid.

## Rules

1. Input will consist of exactly 24 valid characters, which you may take in any reasonable format (e.g. string, list of characters/codepoints). In other words, you are only required to verify the password's checksum.

2. Your code may take the full Metroid character set in order (space last) as a second input.

3. To indicate whether a password is valid or not, your program/function should output/return either

• any truthy/falsy value (swapping allowed) according to your language's convention, or
• one of two distinct, fixed values of your choice.

## Test cases

#### Valid

YOu HaVE BeeN tERmInATeD
YIPPEEKiYAY MotHERF----R
05d3jktcHrgR-B?FFR-6wPkH
05d3jktcHrgR B?FFR 6wPkH
c?w6HI-4rbP5p7AiH EsJyJQ
c?w6HI-4rbP5p7AiJ-EsJyJQ


#### Invalid

reVeaL mE YOUr tREAsurEs
?sudo mAKE mE a SaNDWiCH
c?w6HI-4rbP5p7AiH-EsJyJQ
c?w6HI 4rbP5p7AiH-EsJyJQ
c?w6HI 4rbP5p7AiH EsJyJQ


¹ This challenge was partly inspired by this question on Retrocomputing.SE.

² References: Metroid ※ Cracking VG Passwords S2e2, Metroid Password Format Guide.

³ We ignore the special debugging password, NARPASSWORD, which does not conform to the rules for state-saving passwords.

⁴ The password input screen also accepts blank 'characters' that look like spaces but are functionally equivalent to 0s. We ignore blanks here.

# Implement every dirname (1p)

Implement the dirname utility from scratch. It can be either a program or a fucntion. Assume input string satisfies these constraints:

The dirname utility, however, has two kinds of implementations. This is because some POSIX systems treat //foo/bar differently from /foo/bar. So in this challenge, you must output every possible outputs, in any order. They can be duplicated.

Here is the algorithm to implement the utility, provided string to be input:

1. If string is //, skip steps 2 to 5.
2. If string consists entirely of <slash> characters, string shall be set to a single <slash> character. In this case, skip steps 3 to 8.
3. If there are any trailing <slash> characters in string, they shall be removed.
4. If there are no <slash> characters remaining in string, string shall be set to a single <period> character. In this case, skip steps 5 to 8.
5. If there are any trailing non- <slash> characters in string, they shall be removed.
6. If the remaining string is //, it is implementation-defined whether steps 7 and 8 are skipped or processed.
7. If there are any trailing <slash> characters in string, they shall be removed.
8. If the remaining string is empty, string shall be set to a single <slash> character.

The final string is the output.

Standard I/O rules apply. Standard Loopholes apply. No builtins or libraries that does exactly same functionality. Shortest code wins.

# Examples

Some examples are taken from POSIX explaination of basename().

* means an empty string. 1st column is input and 2nd and 3rd are possible outputs.

usr               .
usr/              .
*                 .
..                .
../               .
/                 /
//                /          //
///               /
/usr/             /
//usr/            /          //
///usr/           /
/usr/lib          /usr
//usr//lib//      //usr
/home//dwc//test  /home//dwc


• ?