560
\$\begingroup\$

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

To post to the sandbox, scroll to the bottom of this page and click "Answer This Question". Click "OK" when it asks if you really want to add another answer.

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

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

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
  • Comments addressing specific points mentioned in the proposal
  • Problems that could make the challenge uninteresting or unfit for the site

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

If you think one of your posts requires more feedback, but it's been ignored, you can ask for feedback in The Nineteenth Byte. It's not only allowed, but highly recommended! Be patient and try not to nag people though, you might have to ask multiple times.

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

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

\$\endgroup\$
0

4327 Answers 4327

1
22 23
24
25 26
145
3
\$\begingroup\$

Base Neutral Numbering System

\$\endgroup\$
3
  • \$\begingroup\$ Can we output as a nested list? Like <<1> * <<1>>> = [[[1],[[1]]]] \$\endgroup\$
    – naffetS
    Nov 22, 2022 at 20:40
  • \$\begingroup\$ Also, can we omit the *? Most of the test cases omit it, only the last two use it. \$\endgroup\$
    – naffetS
    Nov 22, 2022 at 20:41
  • \$\begingroup\$ Omitting the * from the test cases was a mistake. I think [[[1],[[1]]]] already qualifies by my rules since I allow replacing <> with [] and * with , . \$\endgroup\$
    – mousetail
    Nov 22, 2022 at 21:08
3
\$\begingroup\$

Turn two dice into one die

\$\endgroup\$
4
  • \$\begingroup\$ Is it guaranteed that target is divisible by die1 * die2? Seems all your test cases assume so \$\endgroup\$
    – mousetail
    Dec 8, 2022 at 10:42
  • 1
    \$\begingroup\$ What if there are multiple possibilities? Or will the input configuration guarantee an unique solution? \$\endgroup\$
    – pajonk
    Dec 8, 2022 at 11:16
  • \$\begingroup\$ @mousetail that issue is already addressed in the assumptions: "assume N is a divisor of A*B" \$\endgroup\$
    – rtrb
    Dec 8, 2022 at 20:25
  • \$\begingroup\$ @pajonk if there are multiple solutions (such as making a one-sided), you only need to return one of them. I will clarify that in the post. I have not proven mathematically if there are unique solutions for the examples in the post, but I will postulate that they are (up to permutation) \$\endgroup\$
    – rtrb
    Dec 8, 2022 at 20:27
3
\$\begingroup\$

KotH: Build an Organism

A while back, I made a thing that simulates a world, with a bunch of organisms with randomly chosen genes:

dieplife

These would code for things like how the organism would manage resources (such as sugar, water, and starch), whether it could photosynthesize, hunt, run away from enemies, or defend itself using tough materials like wood or stone spikes.

In this challenge, you'll design an organism which can effectively survive. This could be through strategies including:

  • Being an effective hunter, chasing down and killing prey
  • Being difficult to attack, such as by having tough armor and fleeing from stronger organisms
  • Growing and dividing too quickly for it to be possible that all organisms of your species are killed at the same time

I will update this post with a spec listing all available resources, materials, genetic traits, and actions later.

\$\endgroup\$
1
  • \$\begingroup\$ this seems fun. \$\endgroup\$
    – math scat
    Dec 23, 2022 at 20:18
3
\$\begingroup\$

Change the subject

Posted here

\$\endgroup\$
4
  • \$\begingroup\$ Nice challenge! Is it guaranteed that there will be an order in which each sentence connects to the next? \$\endgroup\$
    – The Thonnu
    Jan 15 at 19:02
  • 1
    \$\begingroup\$ @TheThonnu Yes, I'll add that to the challenge rules \$\endgroup\$
    – Jacob
    Jan 15 at 19:19
  • \$\begingroup\$ How are words defined in a sentence? Space separated or any non-letter/punctuation separated? \$\endgroup\$
    – lyxal
    Jan 16 at 4:31
  • \$\begingroup\$ @lyxal, to not make things too complicated, they will just be space separated. But the first and last words of the sentence can be compared with the others as well, and the first word starts with a capital letter while the last word ends with a period. I'll clarify this in the challenge. \$\endgroup\$
    – Jacob
    Jan 16 at 13:58
3
\$\begingroup\$

Simplify a Cycle

\$\endgroup\$
13
  • 2
    \$\begingroup\$ A worked out example would be great. I don't get why aren't all vertices from the input in the output. \$\endgroup\$
    – pajonk
    Aug 19, 2022 at 8:16
  • \$\begingroup\$ Is this really "given a path that may include cycles, remove the cycles"? \$\endgroup\$ Aug 19, 2022 at 8:42
  • 1
    \$\begingroup\$ @UnrelatedString no, it's "given a cycle between two vertices, return the shortest cycle" \$\endgroup\$
    – lyxal
    Aug 19, 2022 at 8:43
  • 3
    \$\begingroup\$ The last test case seems to contradict that, since the shortest cycle between 1 and 7 seems like it should just be [1,2,7]. I guess what I'm getting at is there needs to be a clearer spec and/or worked through example :P \$\endgroup\$ Aug 19, 2022 at 8:47
  • \$\begingroup\$ So is this a 1-D graph or what? Are you only giving us the X coordinates or what? Or am I just not understanding a thing? If we have the coordinates (both X and Y) is this basically removing adjacent coordinates that are colinear? \$\endgroup\$
    – naffetS
    Aug 19, 2022 at 15:50
  • \$\begingroup\$ @Steffan these numbers arent coordinates; they're just the labels on the nodes of the graph. the input is a path that exists on the graph, meaning you can get from each node in the list to the next node in the list by following a single edge \$\endgroup\$ Aug 22, 2022 at 2:35
  • \$\begingroup\$ Maybe an example program will help. \$\endgroup\$ Aug 26, 2022 at 14:29
  • \$\begingroup\$ Questions for @lyxal . \$\endgroup\$ Aug 26, 2022 at 14:39
  • \$\begingroup\$ Suppose his answers are what I expect, this should work. \$\endgroup\$ Aug 26, 2022 at 14:40
  • \$\begingroup\$ It was at 4 char left. Sorry for another post. Why must [1,2,7,2,7,2,3,7] be [1,2,3,7] ([1,2,...,3,7]) and not [1,2,7] ([1,2,7,...])? \$\endgroup\$ Aug 26, 2022 at 14:42
  • \$\begingroup\$ The mathematical definition deems that both are correct. You might want to clarify or add that to the test case. \$\endgroup\$ Aug 26, 2022 at 14:42
  • \$\begingroup\$ E \$\endgroup\$ Aug 26, 2022 at 14:44
  • \$\begingroup\$ ...dited to match the test cases. The last post was too long. \$\endgroup\$ Aug 26, 2022 at 14:44
3
\$\begingroup\$

Change the Temperature of Swatchlings

Warning: Contains Deltarune Chapter 2 Spoilers

Summary

Your challenge today is to determine the minimum number of turns needed to change the temperatures of an arbitrary amount of Swatchlings to all be the same.

Context

In the second chapter of Deltarune, there are enemies you encounter that are called Swatchlings (suit-wearing butler-like characters that serve the main antagonist of the chapter). These enemies always appear in battle in groups with at least one outlier in terms of suit colorsource. Swatchlings are defeated by making all Swatchlings in the group have the same suit colour.

Each Swatchling's color can be changed in stages, either becoming warmer (redder) or colder (bluer). While there are only five colours in the actual game, for this challenge, there will be an infinite amount, represented by positive integers.

During each turn of a battle, there are 3 ways to change the temperature of a Swatchling: increasing/decreasing the temperature by 2 stages, increasing the temperature by 1 stage or decreasing the temperature by 1 stage. You may perform up to 3 of these actions per turn, and no action twice in a turn.

Task and Worked Example

Given a list of Swatchling temperatures, determine the minimal number of turns needed to change the temperatures of all Swatchlings to be the same. Note that

For example, given the following temperatures:

[1, 5, 5]

The optimal solution would be:

Turn 1:
Increase Swatchling #1 by 2 stages: [3, 5, 5]

Turn 2:
Increase Swatchling #1 by 2 stages: [5, 5, 5]

Meaning a minimum of 2 turns are needed to change the temperatures of all Swatchlings to be the same.

Another example is:

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

One optimal solution might be:

Turn 1:
Increase Swatchling #1 by 2 stages: [3, 5, 3, 4, 4, 2, 1]
Decrease Swatchling #4 by 1 stage: [3, 5, 3, 3, 4, 2, 1]
Increase Swatchling #6 by 1 stage: [3, 5, 3, 3, 4, 3, 1]

Turn 2:
Decrease Swatchling #2 by 2 stages: [3, 3, 3, 3, 4, 3, 1]
Decrease Swatchling #5 by 1 stage: [3, 3, 3, 3, 3, 3, 1]

Turn 3:
Increase Swatchling #7 by 2 stages: [3, 3, 3, 3, 3, 3, 3]

Meaning a minimum of 2 turns are needed to change the temperatures of all Swatchlings to be the same.

Rules

  • Input will be a list of positive integers representing the temperatures of each Swatchling. The list will contain at least one Swatchling.
  • Output will be an integer representing the minimum number of turns needed to change the temperatures of all Swatchlings to be the same.

Test Cases

[1, 5, 5] => 2
[1, 2, 5] => 1
[1, 5, 3, 4, 4, 2, 1] => 3
[1, 7] => 2
[1, 10, 3] => 4

As this is , the aim of the game is to get y'all's byte count as low as possible, just like the turn count to make all the Swatchlings the same temperature.

Sandbox Meta

  • Is the explanation clear enough?
\$\endgroup\$
5
  • \$\begingroup\$ For your first case, can't you decrease #3 by 2, decrease it by 1 again, and increase #1 by 1? \$\endgroup\$
    – emanresu A
    Jul 2, 2022 at 0:09
  • \$\begingroup\$ @emanresuA huh, so you can. Just tested it in deltarune lol \$\endgroup\$
    – lyxal
    Jul 12, 2022 at 13:43
  • \$\begingroup\$ I'm assuming the line after the solution for [1, 5, 3, 4, 4, 2, 1] should say "Meaning a minimum of 3 turns are needed..." \$\endgroup\$ Jul 15, 2022 at 19:01
  • \$\begingroup\$ Is [2,5,5] 1 or 2, or say is multiple operating on one item allowed in one turn? \$\endgroup\$
    – l4m2
    Jan 22 at 7:44
  • \$\begingroup\$ [1, 10, 3] should be 3 if I understand it correctly. [1, 10, 3] => [3, 8, 4] => [5, 6, 4] => [5, 5, 5] \$\endgroup\$
    – AndrovT
    Jan 22 at 16:46
3
\$\begingroup\$

Definitions

A \$ \xi \$-word is defined as a string of letters such that every letter in the string appears an even number of times. For example, aeaeccaa is a \$ \xi \$-word.

The function \$ T \$, which operates on \$ \xi \$-words, is defined as follows:

  1. Replace the odd-positioned (first, third, etc.) occurrences of each letter with (. For the example above, this produces ((ae(c(a
  2. Replace all the remaining letters (i.e., those that were the even occurrences) with ). For our example, this produces (())()()

This will always produce a string with balanced brackets.

Task

Take, as input, a string \$ i \$, where every letter appears exactly twice (e.g. xffcxc). Note that this is a stricter condition than merely being a \$ \xi \$-word.

Return the lexicographically earliest \$ \xi \$-word, such that the input and output give the same value when \$ T \$ is applied to them.

Hint: a linear-time algorithm is possible.

Rules

  • You do not need to handle an empty input
  • Letters are ASCII lowercase (a to z)
  • You may choose to operate on integers instead of strings of letters. You can use any set of integers, as long as there are at least 26 of them.
  • You may use any standard I/O method
  • Standard loopholes are forbidden
  • This is , so the shortest code in bytes wins

Test cases

todo


Sandbox notes

At the moment, this challenge is very abstract, which I think means it will look seem quite boring (until you start to actually solve it, which I think is fun, although fairly simple). (What kind of a title is Lexicographically earliest \$ T \$-invariant \$ \xi \$-word?)

If you can think of a good domain to make it concrete, I think it would be much better. (Unfortunately I can't reveal the original context in which I encountered it). At the least I will probably replace the symbolic names with cute names before posting.

\$\endgroup\$
2
  • \$\begingroup\$ How do you pronounce that? \$\endgroup\$
    – Jacob
    Jan 23 at 16:19
  • 1
    \$\begingroup\$ @Jacob According to Google Translate, it's pronounced "she". \$\endgroup\$
    – Peter
    Feb 9 at 18:15
3
\$\begingroup\$

Yakko's New World Order

\$\endgroup\$
5
  • 2
    \$\begingroup\$ I don't think allowing outputting the indices into the list should be allowed \$\endgroup\$ Jan 24 at 21:11
  • \$\begingroup\$ @RydwolfPrograms Why not? \$\endgroup\$ Jan 24 at 21:17
  • \$\begingroup\$ Everybody's just going to do that, and that rules out some interesting approaches involving the text itself (such as using some sort of custom digest as a sorting key). \$\endgroup\$ Jan 24 at 21:18
  • \$\begingroup\$ Given a list of countries in alphabetical order -> are we always given the full list, or could it be a subset of this list? \$\endgroup\$
    – Arnauld
    Jan 29 at 20:23
  • \$\begingroup\$ @Arnauld You are always given the full list. (If you want, you can ignore the input completely.) \$\endgroup\$ Jan 29 at 21:12
3
\$\begingroup\$

Sum of Consecutive Squares

\$\endgroup\$
3
\$\begingroup\$

Infinite Apple Dilemma

Posted here

\$\endgroup\$
5
  • \$\begingroup\$ +1 just cause Dennis \$\endgroup\$ Feb 1 at 4:54
  • 1
    \$\begingroup\$ Are the third and fourth test-cases correct? - I get different results. Maybe the 20 and 30 are swapped? \$\endgroup\$
    – pajonk
    Feb 9 at 14:40
  • \$\begingroup\$ @pajonk right lol \$\endgroup\$
    – math scat
    Feb 9 at 14:52
  • \$\begingroup\$ Will all the steps result in integer apple numbers (step-by-step)? Currently it's not true for test cases 5 and 6. \$\endgroup\$
    – pajonk
    Feb 9 at 16:58
  • \$\begingroup\$ @pajonk nope, ty \$\endgroup\$
    – math scat
    Feb 9 at 19:21
3
\$\begingroup\$

Base64 fixed point

It can be proven that there's exactly one string of infinite length that remain same after base64 encoding Vm0wd2QyUXlVWGxWV0d4V1YwZ...

Given \$n\$, output one of

  • the \$n\$-th character
  • the first \$n\$ characters
  • The whole string

\$\endgroup\$
8
  • \$\begingroup\$ I don't understand this at all \$\endgroup\$
    – mousetail
    Jan 21 at 16:23
  • \$\begingroup\$ A strings that starts with the outputted string? Doesn't every string begin with itself? \$\endgroup\$
    – mousetail
    Jan 21 at 16:33
  • \$\begingroup\$ @mousetail base64(x) starts with x \$\endgroup\$
    – l4m2
    Jan 22 at 6:36
  • 1
    \$\begingroup\$ It is confusing that your link starts with V and the test cases start with m. Also, fastest-code requires specifying how exactly each submission will be scored codegolf.stackexchange.com/tags/fastest-code/info. \$\endgroup\$
    – pajonk
    Jan 24 at 13:47
  • \$\begingroup\$ @pajonk The one starting with m is str.slice(\$3^0\$) \$\endgroup\$
    – l4m2
    Jan 24 at 16:34
  • \$\begingroup\$ @pajonk Scoring thing isn't decided \$\endgroup\$
    – l4m2
    Jan 24 at 16:35
  • \$\begingroup\$ I'm not sure this is exactly fastest code - "most computation in fixed time" rather than "fixed computation in least time". It should maybe be code-challenge restricted-time? \$\endgroup\$
    – pxeger
    Jan 31 at 16:43
  • \$\begingroup\$ @pxeger Largest input successfully processed within a fixed time limit. \$\endgroup\$
    – l4m2
    Jan 31 at 17:16
3
\$\begingroup\$

Rotate an Image

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Might want to clarify if exif-orientations are allowed \$\endgroup\$
    – AnttiP
    Feb 16 at 10:07
3
\$\begingroup\$

Reverse the polyglot, change the language.

\$\endgroup\$
3
\$\begingroup\$

Approximate a root of an odd degree polynomial

\$\endgroup\$
2
  • \$\begingroup\$ I've got a couple of answers so vote for to move to main page :p \$\endgroup\$
    – lesobrod
    Feb 18 at 19:32
  • \$\begingroup\$ The only note: usually \$a_i\$ means coefficient of polinomial \$\endgroup\$
    – lesobrod
    Feb 18 at 19:45
3
\$\begingroup\$

Whole Number Groups

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Where does 1/7 come from in the second example? \$\endgroup\$
    – chunes
    Feb 17 at 10:21
3
\$\begingroup\$

Fibonacci Binary Squares

\$\endgroup\$
4
  • \$\begingroup\$ since this is a sequence, can we just use the default sequence rules? \$\endgroup\$
    – naffetS
    Feb 21 at 1:01
  • \$\begingroup\$ I'd be willing to allow the Fibonacci sequence used to generate the answer to be 0 or 1 indexed, but I don't see the logic in allowing the main "sequence" to be 0 indexed. The rest of the rules I think would be fine. \$\endgroup\$ Feb 21 at 11:55
  • \$\begingroup\$ Well, some languages use zero-indexing for arrays, and some use one-indexing, so it can help. \$\endgroup\$
    – naffetS
    Feb 21 at 17:20
  • \$\begingroup\$ Fair. Changed it to allow for 0- or 1- indexing. \$\endgroup\$ Feb 22 at 1:35
3
\$\begingroup\$

"Candy Crush" a string

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Suggested test case: 1322232223222311 -> (1332223222311 -> 1333222311 -> 1222311 ->) 1311. Since you mention you reiterate after every replacement from left to right again (well done for making that bold). :) If one would filter out all blocks of 3+ at once, it would incorrect result in -> 1333311 -> 111 -> "". Good challenge overall, so +1 from me. And welcome to CGCC. \$\endgroup\$ Feb 21 at 12:19
  • \$\begingroup\$ @KevinCruijssen Thank you for your feedback! I added your test case to the list :) \$\endgroup\$
    – Fhuvi
    Feb 21 at 12:43
3
\$\begingroup\$

Help Me Type on My New Keyboard

\$\endgroup\$
12
  • \$\begingroup\$ In the 5th test case first letter of output must be r not p \$\endgroup\$
    – EzioMercer
    Feb 20 at 20:36
  • \$\begingroup\$ It is very hard to read q as я... can we remove this rule? :) I'm not expert but I have never seen that Russians use q as я \$\endgroup\$
    – EzioMercer
    Feb 20 at 20:41
  • \$\begingroup\$ JFYI they widely use 4 as ч, so if you want you also can add this rule \$\endgroup\$
    – EzioMercer
    Feb 20 at 20:44
  • \$\begingroup\$ @EzioMercer 1. Thanks. My english kicked in. for 2. and 3. this is the specific keyboard layout im using. most mnemonic layouts ive used use q as я \$\endgroup\$
    – Seggan
    Feb 20 at 20:48
  • \$\begingroup\$ Your task your rules :) Also please remove additional space after second word in 5th test case \$\endgroup\$
    – EzioMercer
    Feb 20 at 20:51
  • \$\begingroup\$ @EzioMercer read the comments after the test case: note the double space after "chtec". its required because c is a combining letter \$\endgroup\$
    – Seggan
    Feb 20 at 20:54
  • \$\begingroup\$ And the last question :) Are you sure about these rules: "e" -> "е", "je" -> "э" and "ye" -> "э"? The letter j uses for я,ё,ю because in their pronunciation we have й at the start. я - йа, ё - йо, ю - йу and the same thing for letter е - йэ, so it is logical to have the these rules: "je" -> "е", "ye" -> "e" and "e" -> "э" \$\endgroup\$
    – EzioMercer
    Feb 20 at 21:02
  • \$\begingroup\$ About c you already have the rule "c" -> "ц" you don't need any additional space after it \$\endgroup\$
    – EzioMercer
    Feb 20 at 21:03
  • \$\begingroup\$ @EzioMercer yes im sure. i know it seems weird. for the second comment, note To type the single letters mapped to them, either press that key and then press space \$\endgroup\$
    – Seggan
    Feb 20 at 21:05
  • \$\begingroup\$ You have weird keyboard :) \$\endgroup\$
    – EzioMercer
    Feb 20 at 21:06
  • \$\begingroup\$ In 5th test case xepdyami -> xerdyami - change the p to r \$\endgroup\$
    – EzioMercer
    Feb 20 at 21:08
  • 1
    \$\begingroup\$ @EzioMercer aargh the challenges of being bilingual :P \$\endgroup\$
    – Seggan
    Feb 20 at 21:10
3
\$\begingroup\$

Largest Binary Area

\$\endgroup\$
1
  • 2
    \$\begingroup\$ You may want to clarify that each column in ASCII art is a binary number. I had to read it a couple times before that was clear to me. Writing it out might probably be even clearer (e.g. "Take the sequence of all natural numbers in binary: [1,10,11,100,101,110,111,1000,1001,1010,1011,1100,1101,1110,1111,10000,10001,...]. Displaying each of these binary numbers as reversed columns gives: <insert current ascii-art here>") Apart from that the challenge is clear; nice challenge btw! I'm curious what kind of algorithms can be found instead of actually calculating the areas. \$\endgroup\$ Feb 28 at 12:51
3
\$\begingroup\$

Calculate the p-adic square root of -1

Given a prime number \$p\$, a \$p\$-adic number is a number whose representation in base \$p\$ may have infinitely digits to the left of the radix point, but only finitely many digits to the right of it. A \$p\$-adic integer has no digits after the radix point.

\$p\$-adic numbers have some interesting properties. It can be proven that for any prime number \$p\$, there exists a \$p\$-adic integer \$x\$ such that \$x^2 = -1\$ if and only if the congruence \$x_0^2 \equiv -1 \pmod{p}\$ has a solution. (That is, there is some integer \$x_0\$ such that \$x_0^2 + 1\$ is divisible by \$p\$.)

Your task is to determine whether this is the case and calculate the digits of the number \$x\$. Note that there will always be two solutions which are additive inverses of each other; you only need to calculate one.

Input

A prime number \$p \ne 2\$. (You don't need to verify that it's prime.)

Output

Find the digits of the \$p\$-adic square root of \$-1\$, as described above. Following the standard sequence rules, do one of the following:

  • Given an index \$i\$, output the \$i\$-th digit from the end. Since base representations are naturally 0-indexed, you may not use 1-indexing.
  • Given a positive integer \$n\$, output the last \$n\$ digits. You can choose between little-endian and big-endian.
  • Output all digits in the form of a non-halting program, a generator, an infitite lazy list, etc.

If the \$p\$-adic square root of \$-1\$ does not exist, do anything that can be clearly distinguished from a valid output, such as raising an exception or returning an empty list.

Algorithm

Here I describe one possible way to solve this challenge.

  • Find a number \$x_0\$ between \$0\$ and \$p-1\$ such that \$x_0^2 \equiv -1 \pmod{p}\$. If not found, report failure.
  • Find a number \$y\$ between \$0\$ and \$p-1\$ such that \$2x_0y \equiv 1 \pmod{p}\$. (This is always possible.)
  • Let \$c_0 = \left\lfloor\frac{x_0}{p}\right\rfloor\$.
  • For each positive integer \$i\$:
    • Let \$h_i = c_{i-1} + \sum_{j=1}^{i-1} x_j x_{i-j}\$.
    • Let \$x_i = (p-1-h_i)\cdot y \bmod p\$.
    • Let \$c_i = \left\lfloor\frac{h_i + 2 x_0 x_i}{p}\right\rfloor\$.
  • The sequence \$\left(x_i\right)\$ is the output.

Ungolfed Python implementation:

def sqrt_minus_one(p, n):
    for x in range(p):
        if (x * x + 1) % p == 0:
            last_digit = x
            break
    else:
        return None # no solution
    for x in range(p):
        if (x * 2 * last_digit) % p == 1:
            inv = x
    digits = [last_digit]
    carry = (last_digit * last_digit) // p
    for i in range(1, n):
        h = sum(digits[j] * digits[i - j] for j in range(1, i)) + carry
        digits.append((p - 1 - h) * inv % p)
        carry = (h + 2 * last_digit * digits[i]) // p
    return digits

It's also possible to use a brute-force approach where you find an \$n\$-digit number \$x\$ such that \$x^2 + 1\$ ends with \$n\$ zeroes in base \$p\$. I suppose this could lead to much golfier solutions, so maybe I should make the challenge restricted-complexity to forbid this?

Test cases

  p | first 20 digits (two possible outputs)
  3 | ---
  5 | 2,1,2,1,3,4,2,3,0,3,2,2,0,4,1,3,2,4,0,4
    | 3,3,2,3,1,0,2,1,4,1,2,2,4,0,3,1,2,0,4,0
  7 | ---
 11 | ---
 13 | 5,5,1,0,5,5,1,0,1,8,8,6,12,6,3,0,4,7,4,5
    | 8,7,11,12,7,7,11,12,11,4,4,6,0,6,9,12,8,5,8,7
 17 | 4,2,10,5,12,16,12,8,13,3,14,0,6,1,0,15,1,8,14,5
    | 13,14,6,11,4,0,4,8,3,13,2,16,10,15,16,1,15,8,2,11
 47 | ---
101 | 10,5,29,66,10,30,44,29,72,25,34,82,83,5,52,17,67,94,65,52
    | 91,95,71,34,90,70,56,71,28,75,66,18,17,95,48,83,33,6,35,48
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Perhaps allow assuming a square root of -1 exists? Testing for the existence of it isn't too related to finding it \$\endgroup\$ Mar 17 at 12:21
3
\$\begingroup\$

Is it traversable?

\$\endgroup\$
3
\$\begingroup\$

Qat Equation Solver

\$\endgroup\$
2
  • \$\begingroup\$ I think you should include both . and brackets, since they both add more power without being cumbersome. For example, I can't see how to express A=(.);B=aAt;C=aAe without using both of these. \$\endgroup\$ Mar 23 at 8:31
  • \$\begingroup\$ @CommandMaster In that specific case, it could be expressed as B=a.t;B=aAt;C=aAe, but that makes me realize I should specify you can have more than one equation referencing the same variable I suppose \$\endgroup\$ Mar 23 at 14:10
3
\$\begingroup\$

Record Least Uncommon Multiple Counts

\$\endgroup\$
2
  • 2
    \$\begingroup\$ You probably meant \$\frac{\text{lcm}}{\text{gcd}}\$, the other way around is less than 1 \$\endgroup\$ Mar 23 at 15:49
  • 1
    \$\begingroup\$ Good catch. I did \$\endgroup\$ Mar 23 at 16:10
3
\$\begingroup\$

Rendevous!

Your bots went to the mall together, but they got lost! Worse, they didn't agree on any strategy to find one another again.

Here's what they do know:

  • There are \$n\$ stores, and bots can only meet each other in the stores.

  • Each time step, each bot must choose one store to be in.

  • Two bots go to the mall simultaneously. Their score for the outing is the number of time steps it took for them to find one another.

  • The mall closes after \$n^2\$ time steps. If some bots are still at the mall, they will receive a score of \$n^2+1\$.

Bots must be written in Javascript. Your bot must be a generator function, receiving a single input \$n\$ (the number of stores) and output at least \$n^2\$ integers in the range \$[0..n-1]\$. Your bot's score will be the average of its scores when played with all of the other bots.

The stores will be scrambled - what is room 1 for one bot may be room 5 for another. There will be many rounds of the game (1000 right now, but if there are lots of entries and it takes longer than an hour, I may lower that number), and each round will be a round-robin with a set number of stores. \$n\$ will be in the range \$[4..25]\$.

There are better and worse strategies, but optimal strategies (when symmetric) are only known for \$n=2\$ and \$n=3\$. An example bot (which will be playing):

function* randomSearchBot(n){
  while (true){
    yield Math.floor(Math.random() * n);
  }
}

Here is the controller:

function shuffle(array) {
    for (let i = array.length - 1; i > 0; i--) {
        let j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
}
function runRound(bot1, bot2, n){
    let b1 = bot1(n), b2 = bot2(n);
    let stores = Array(n).fill(0).map((_, i) => i);
    shuffle(stores);
    let turn = 0;
    while (turn++ < n ** 2){
        if (b1.next().value == stores[b2.next().value]) break;
    }
    return turn;
}
function runAllRounds(...bots){
    const nameLength = Math.max(bots.map(b => b.name));
    bots = bots.map(b => {
        return {
            bot: b,
            totalScore: 0
        };
    });
    const rounds = 1000;
    let round = rounds;
    const pairs = bots.map((b, i) => bots.slice(i + 1).map(w => [b, w])).flat();
    while (round--){
        const n = Math.floor(Math.random() * 22) + 4; // [4..25]
        for (let [a, b] of pairs) {
            const score = runRound(a.bot, b.bot, n);
            a.totalScore += score;
            b.totalScore += score;
        }
    }
    bots.forEach(b => {
        b.totalScore /= rounds * (bots.length - 1);
        console.log(b.bot.name.padEnd(nameLength) + ": " + b.totalScore.toFixed(5));
    });
}

The main feedback I'm looking for here is whether people think there's a big enough strategy space for it to be worth playing.

\$\endgroup\$
4
  • \$\begingroup\$ Ideally submissions would include the title and tags \$\endgroup\$
    – mousetail
    Mar 30 at 10:56
  • \$\begingroup\$ When the bots are different I'm almost 100% one outputting a fixed output and the other outputting a permutation is optimal. \$\endgroup\$ Mar 30 at 18:56
  • \$\begingroup\$ If both bots output random permutations I believe the expected score is around \$ \frac e{e-1}n \$. \$\endgroup\$ Mar 30 at 19:08
  • 1
    \$\begingroup\$ I believe it is exactly \$ n+1 - \frac{ !(n+1) - n\cdot !n}{n!-!n} \$, or approximately \$ n + \frac{e-2}{e-1}\$, so it's ever so slightly worse than random search bot. \$\endgroup\$ Mar 30 at 19:44
3
\$\begingroup\$

Shortest distinguishable slice (posted)

\$\endgroup\$
6
  • \$\begingroup\$ ime, it's more common to express ranges as [start, end + 1) rather than [start, end] -- that's what most C++ STL functions do, for example. Would that be accepted here? \$\endgroup\$
    – Bbrk24
    Apr 2 at 3:18
  • 1
    \$\begingroup\$ @Jacob what I think Bbrk24 meant was that in a lot of languages, "abcdef"[1:4] would be bcd not bcde (Try it online!). Obviously it's your challenge, your rules, but IMO it might be worth allowing this format of slices as the output instead. \$\endgroup\$
    – The Thonnu
    Apr 2 at 8:16
  • \$\begingroup\$ I'm pretty sure it's [start, end) not [start, end + 1) since the latter is the same as [start, end]. \$\endgroup\$
    – The Thonnu
    Apr 2 at 13:25
  • 1
    \$\begingroup\$ @TheThonnu Yeah you are right, fixing now \$\endgroup\$
    – Jacob
    Apr 2 at 13:28
  • \$\begingroup\$ Now this part requires fixing (or removing): A slice can also be 1 character long if the two indices are equal. \$\endgroup\$
    – pajonk
    Apr 3 at 6:01
  • 1
    \$\begingroup\$ @pajonk Oh, duh. This is why the sandbox is so useful lol \$\endgroup\$
    – Jacob
    Apr 3 at 11:13
3
\$\begingroup\$

How super is this prime?

Posted here

\$\endgroup\$
2
  • \$\begingroup\$ To me, this sounds like functions are disallowed - is that intentional? \$\endgroup\$ Apr 6 at 19:45
  • \$\begingroup\$ @CreativeName No; I'll edit it \$\endgroup\$
    – Lecdi
    Apr 6 at 21:44
3
\$\begingroup\$

The Jaccard Index

\$\endgroup\$
2
  • \$\begingroup\$ Could you add a bit more explanation for those of us who haven’t studied set theory? \$\endgroup\$
    – Jacob
    Apr 6 at 11:18
  • 1
    \$\begingroup\$ @Jacob I added some historical background, a revised explanation and a few links for the set theory operations. Let me know if I missed something. Thanks. \$\endgroup\$
    – solid.py
    Apr 6 at 13:00
3
\$\begingroup\$

Zählen

Posted here

\$\endgroup\$
4
  • 2
    \$\begingroup\$ Nice challenge, the explanation might be a bit better if you listed the numbers up to 23 or so, and then listed just the multiples of ten. This way it could be easier to extrapolate the pattern, especially if there is another pattern that is useful for golfing. \$\endgroup\$
    – Jacob
    Apr 6 at 16:17
  • 2
    \$\begingroup\$ @Jacob Something like this? \$\endgroup\$ Apr 6 at 16:30
  • 2
    \$\begingroup\$ You are using zwölf in the test cases and zwoelf in the description. I guess you should either fix this inconsistency or allow both fuenf/zwoelf/dreissig and fünf/zwölf/dreißig. \$\endgroup\$
    – Arnauld
    Apr 7 at 12:04
  • 1
    \$\begingroup\$ @Arnauld Thank you, that was a mistake, it should be zwoelf. \$\endgroup\$ Apr 7 at 14:44
3
\$\begingroup\$

Calculate Bloons RBE Equivalent

\$\endgroup\$
3
\$\begingroup\$

International Resource Trading KOTH

Your country wants to reach Mars, and do it as cheaply as possible. While you can produce all required resources domestically, other countries can produce them cheaper and trading can drastically reduce both your costs.

Goal of the game

There are 10 resources, numbered 1-10. You need 1,000 of each resource to build a rocket and colonize Mars.

The cost of each rocket is different for each player though. One will cost €10, one €20, €30, ... and the last costs €100 per unit. This number is different for every bot, for example resource 1 could cost €20 for one but but €90 for a different bot.

Without trading, the rocket would cost €550,000. But if you import resources that are expensive for you to produce, and sell resources that are cheap for you to produce. If you do it right, you can make the process massively cheaper or even potentially make a profit and still launch your rocket.

The game loop

The game consists of 7 rounds. Each round has 2 phases.

The first phase is the production phase. Each bot can choose to produce some number of resources locally. The total limit for how much you can produce is 10 the first round, 20, 40, 80 ... 1280 in the last round. Bots can choose to divide their production among every resource. For example, you can buy 6 of resource A and 4 of resource B in the first round. Money will be subtracted from your score proportional to the value the resource has for you.

The second phase is the trading phase. In turns, every bot has the option offer a trade. Then other bots can choose to accept the offer or to create a counteroffer. Then the bot may choose to accept any of the counteroffers or reject all of them.

Trades can either be money for resources or resources for money. You can't trade resources for resources directly.

There are 3 rounds of trading for every production phase.

If the game ends before you collect enough to launch your rocket, the rest of the resources will be produced domestically and cost you the domestic production price.

Example bot

class PriceBelowHalf:
    """
    Will only buy resources if the price is less than half the local production price
    Will only sell resources if the price is more than double the local production price
    """

    def __init__(self, bot_ids: list[int], resource_prices: dict[int, int], rng):
        # Randomness only allowed via the provided RNG.
        self.bot_ids = bot_ids
        self.resource_prices = resource_prices

    def production_phase(self, max_production: int, resources: dict[int, int]):
        # produce the maximum amount of the cheapest resource
        return {min(self.resource_prices, key=lambda i:resource_prices[i]): max_production}
    
    def trade(self, resources: dict[int, int]):
        # Offer to buy the resource we have the least of for half it's price
        resource = min(resources, key=lambda i:resources[i])

        # 2 item tuples are treated as resources, single integers are treated as money
        # First element is what you get, second is what you want to give
        return [(resource, 10),
                self.resource_prices[resource]*5]

    def trade_offer_accepted(self, resources: dict[int, int], counteroffers: list):
        for counteroffer in counteroffers:
            # Accept the first counteroffer that is a good deal
            if isinstance(counteroffer[0], tuple) and \
               counteroffer[0][1] * 2 > self.resource_prices[counteroffer[0][0]] * counteroffer[1]:
                return counteroffer

    def trade_offer_received(self, trade_offer: list, resources:dict[int, int]):
        # If you return a offer in the same format it would be treated as a counteroffer
        # Counteroffer must be for the same resource but you may change both the amount of money and the amount of the resource
        # If you want to unconditionally accept simply `return trade_offer`
        # If you return None you will reject the offer
        # third element of the trade offer is the bot that offered it

        # they want to give a resource for money
        if isinstance(trade_offer[0], tuple):
            # Must be greater than 2:1 ratio to our own price
            return [[counteroffer[0][0], counteroffer[0][1]],
                    # Pay half price or the other bot offered, whatever is cheaper
                    min(
                        self.resource_prices[counteroffer[0][0]] * counteroffer[0][1]] // 2,
                        trade_offer[1]
                    )
            ]
        else:
            # They want to give money for our resources, so we need to check if we have enough
            if resources[trade_offer[1][0]]>=trade_offer[1][1]:
                return [
                    max(
                        trade_offer[0],
                        self.resource_prices[trade_offer[1][0]] * trade_offer[1][1]
                    ),
                    trade_offer[1]
                ]
 

Extra Rules

  • No IO
  • No RNG except via the provided seeded PRNG
  • No exploiting the controller
  • No targeting a specific bot or specifically helping one specific bot. Hurting or helping a range of strategies is perfectly fine.
\$\endgroup\$
8
  • 1
    \$\begingroup\$ Suggestion: Use the ¤ generic currency symbol \$\endgroup\$
    – Ginger
    Apr 17 at 11:53
  • \$\begingroup\$ @Ginger I'd rather not \$\endgroup\$
    – mousetail
    Apr 17 at 11:54
  • \$\begingroup\$ Instead, use $, as it’s ASCII \$\endgroup\$
    – Seggan
    Apr 21 at 19:34
  • \$\begingroup\$ It really isn't a issue for the bots, all math is plain integers. So whether the currency is ASCII doesn't matter at all. I prefer to use € since I'm from europe, but you are free to imagine the currency as pounds or yen or whatever. It really doesn't matter for the challenge. If there are any genuine concerns about the challenge instead of bikeshedding about the currency symbol used I'd love to hear it. \$\endgroup\$
    – mousetail
    Apr 21 at 21:34
  • \$\begingroup\$ If multiple bots accept an offer, who gets it? Do all bots see all offers, even ones that have already been accepted? \$\endgroup\$ Apr 24 at 4:33
  • \$\begingroup\$ Do bots get any info about other bots' production prices? \$\endgroup\$ Apr 24 at 4:33
  • \$\begingroup\$ @Spitemaster Every bot can choose which counteroffer to accept, and they do not get info on others production prices \$\endgroup\$
    – mousetail
    Apr 24 at 5:15
  • \$\begingroup\$ @Spitemaster I'm not sure yet if all bots will see all offers. I like the idea of being able to limit a trade offer to a certain subset of bot as a way to hide information but I'm afraid it would make the game too complex \$\endgroup\$
    – mousetail
    Apr 24 at 5:16
1
22 23
24
25 26
145

You must log in to answer this question.

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