515
\$\begingroup\$

What is the Sandbox?

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

To post to the Sandbox, scroll to the bottom of this page and click "Answer This Question", or click on the "Add Proposal" link below. Click "OK" when it asks if you really want to add another answer. Write your challenge just as you would when actually posting it. You may also add some notes about specific things you would like to clarify before posting it. Other users will help you improve your challenge by rating and discussing it. When you think your challenge is ready for the public, go ahead and post it, and replace the post here with a link to the challenge and delete the Sandbox post.

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

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

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

Add Proposal

Search the Sandbox

Browse your pending proposals

Get the Sandbox Viewer to view the sandbox more easily

\$\endgroup\$
0

3281 Answers 3281

1
27 28
29
30 31
110
2
\$\begingroup\$

Integer partitions into fixed parts with coprime constraint, and exclusion set

Background

Let \$a\$ \$\in \mathbb{N}\$, \$b\$ \$\in \mathbb{N}\$, \$c\$ \$\in \mathbb{N}\$ and \$S\$ be some subset of \$\{i:1\leq i\leq a\}\$.

Consider \$X(a ,b, c, S)\$: The number of integer partitions of \$a\$ into \$b\$ many parts, where each of the parts are co-prime to \$c\$ and no part is contained within \$S\$.

Formally, for \$b=2\$

$$X(a ,2, c, S) = |\{(x, y): x + y = a,\ gcd(c, x) = gcd(c, y) = 1, x \notin S, y \notin S,\ x \leq\ y\}|$$

Challenge

Codegolf, standard rules apply. Write code to calculate the function \$X(a ,b, c, S)\$ above.

Inputs:

  • \$a\$, an integer. Your function does not need to be correct for \$a \le 2\$.

  • \$b\$, an integer. Your function does not need to be correct for \$b \le 1\$.

  • \$c\$, an integer.

  • \$S\$, can be any set of integers between \$1\$ and \$a\$ (inclusive). The elements of \$S\$ are unique.

Test-cases

Below test cases are written in the following format: \$a, b, c, S =\$ Answer

3, 2, 2, {} = 0
4, 2, 2, {} = 1
4, 2, 3, {2} = 0
7, 3, 5, {} = 3
7, 3, 2, {5} = 1
11, 3, 1, {} = 10
11, 3, 2, {} = 4
11, 3, 3, {5, 7} = 1

BONUS

Brownie points for anyone who can do either of the following:

  1. Disprove the following recursive relationship.
  2. Extend the following recursive relationship (for higher values of \$b\$), and/or write code utilising it.

Recursive formula for \$b = 3\$ (Might be incorrect):

$$X(a ,3, c, S) = \sum_{i=1}^{i=\lfloor\frac{a}{2}\rfloor} {X(a - i, 2, c, T_i)} $$

With

$$T_0 = S$$

and,

$$T_i = T_{i-1}\cup\{i - 1, a + 1 - i\},\ for\ i \geq 1$$

Questions for sandbox

Is this challenge good to go?

\$\endgroup\$
7
  • \$\begingroup\$ you can add tags here via [tag:<tagname>]. \$\endgroup\$ – Razetime Feb 27 at 8:37
  • \$\begingroup\$ @Razetime , sorry total noob here. In the comment section? or do I edit the post and add the [tag:<tagname>] at the end? \$\endgroup\$ – DanielOnMSE Feb 27 at 9:30
  • 1
    \$\begingroup\$ in the post. Add it near the title, like in the other posts. \$\endgroup\$ – Razetime Feb 27 at 9:55
  • \$\begingroup\$ About test cases. It looks like that this challenge doesn't have too many test cases, don't need a lot. \$\endgroup\$ – user202729 Feb 27 at 12:15
  • \$\begingroup\$ I think the info about integer types makes the question harder to read (they all have default rules), so I removed it. \$\endgroup\$ – user202729 Feb 27 at 12:15
  • \$\begingroup\$ The tag doesn't matter too much, as long as there's a code golf tag. // Usually people don't like time limits, but if you insist there's either "solutions must have time complexity that does not exceed (something)" or "you must be able to run the program to completion with the following test cases" or "the program must finish on my machine in X seconds" (requires you running the programs) [please review other sandbox posts] \$\endgroup\$ – user202729 Feb 27 at 12:17
  • \$\begingroup\$ @user202729 Thanks for the edits. Yes I suppose I'm not interested in any time constraints. Rather just interested to see the solutions people can come up with. Yes I will need to make some test cases, will add them when I get a chance. \$\endgroup\$ – DanielOnMSE Feb 27 at 13:01
2
\$\begingroup\$

Posted

\$\endgroup\$
7
  • \$\begingroup\$ The analogy isn't exact, but consider the name "Literate JS" \$\endgroup\$ – Unrelated String Feb 23 at 13:29
  • \$\begingroup\$ Test cases (N denotes literal new line): //aN//b, /*/, /*a*//*b*/ (<- should a space be inserted between the tokens in this test case? [please review other sandbox posts] \$\endgroup\$ – user202729 Feb 24 at 4:13
  • \$\begingroup\$ suggested test case "abc //" def // ghi to show whether an answer should implement a full JS tokenizer (in actual JS, only ` ghi` is commented, while it makes more sense to only require the answerers to return " def // ghi) \$\endgroup\$ – Wezl Feb 24 at 17:51
  • \$\begingroup\$ @Wezl good point, I never thought of that! I agree that a full JS tokenizer would be too complex, so I'm going with your sensible version. \$\endgroup\$ – A username Feb 25 at 3:36
  • \$\begingroup\$ @user202729 In the first case, a newline would be inserted between the two. In the second case, the output would just be ab. Thanks for clarifying, and I'll look at some other sandbox posts later. \$\endgroup\$ – A username Feb 25 at 3:39
  • \$\begingroup\$ Then why is the third test case have a space added between the first two comments? \$\endgroup\$ – user202729 Feb 25 at 7:21
  • \$\begingroup\$ Sorry, typo. Thanks for pointing that out! \$\endgroup\$ – A username Feb 25 at 8:31
2
\$\begingroup\$

Decompress an integer, Jelly style

\$\endgroup\$
1
  • 3
    \$\begingroup\$ Algorithm description looks good. Requiring to handle inputs up to \$2^{64}-1\$ sounds unfair to the languages that do not support that large integers though. I'd prefer something in the line of the 5th bullet under the Rules on this challenge. \$\endgroup\$ – Bubbler Mar 25 at 0:09
2
\$\begingroup\$

Rotate brackets until they're balanced

\$\endgroup\$
1
  • \$\begingroup\$ I've edited this down to a stub now that it's been posted \$\endgroup\$ – caird coinheringaahing Mar 28 at 14:03
2
\$\begingroup\$

(Σ*)² ⟲ Σ* (aka Round-Trip a String Pair)

\$\endgroup\$
2
\$\begingroup\$

Unique languages

As we found out before, each of the 680 languages on Try it online! has a "TIO uniqueness", defined as the length of the shortest substring that appeared in the language's name and no others'.

This time, we're going to make it more general. Given a list of strings S and a target T, output the length of the shortest substring of T that is not in any other element of S. You may choose whether T is part of S or not. The elements of S will always be unique. All elements of S, and T, will only contain lowercase letters (abcdefghijklmnopqrstuvwxyz). You may also take input as uppercase if you wish.

Your score will be calculated as code length × TIO uniqueness, where code length is measured in bytes and TIO uniqueness is the TIO uniqueness as specified here. If a language has an undefined TIO uniqueness, it cannot compete in this challenge.

The answer with the lowest score wins.

Meta

\$\endgroup\$
1
2
\$\begingroup\$

Check B-powersmoothness - posted

\$\endgroup\$
2
  • \$\begingroup\$ Can you link to the wiki article please. \$\endgroup\$ – Alex bries Mar 29 at 8:57
  • 1
    \$\begingroup\$ @Alexbries I added a link \$\endgroup\$ – Command Master Mar 29 at 9:06
2
\$\begingroup\$

To raise \$ e \$ to the power of a matrix

Inspired by this 3Blue1Brown video

Given a square matrix \$ M \$, compute \$ \exp(M) \$, which is defined as

$$ \exp(M) = \sum_{r=0}^\infty \frac {M^r} {r!} = M^0 + M^1 + \frac 1 2 M^2 + \frac 1 6 M^3 + \cdots + \frac 1 {n!} M^n + \cdots $$

where \$ n! \$ represents the factorial of \$ n \$, and \$ M^0 \$ is the identity matrix for the dimensions of \$ M \$.

You must compute this infinite sum until its value converges to the extent that it no longer changes within your language's available precision (typically a float or double). If your language provides only infinite-precision numeric types, it is ineligible for this challenge.

There are other ways to compute this, which you may use, as long as the result is precise????

Test cases

Coming soon - I wanted to post this early so I don't get sniped by any other 3b1b viewers!

Rules

  • \$ M \$ will be square and have dimensions between 2x2 and 8x8
  • The elements of \$ M \$ will all be integers \$ -20 \le x \le 20 \$
  • You may take \$ M \$ as a nested array, a flat array with separate
  • Standard loopholes are forbidden
  • Standard I/O rules apply
  • This is , so the shortest code in bytes wins

Meta

  • Is this clear enough?
  • Is this a duplicate?
  • Is the rule about convergence actually a terrible idea?
  • Any other feedback?
\$\endgroup\$
8
  • \$\begingroup\$ why not require exact calculation, it makes for a harder challenge but a more interesting one \$\endgroup\$ – rak1507 Apr 1 at 19:54
  • \$\begingroup\$ @rak1507 it's irrational so an exact value can't be calculated \$\endgroup\$ – pxeger Apr 1 at 19:55
  • \$\begingroup\$ looked like there were methods on wikipedia but I could be wrong \$\endgroup\$ – rak1507 Apr 1 at 21:45
  • \$\begingroup\$ Note that the exponential of a 9x9 matrix of 100's exceeds what floats can represent. You might want to lower the 100 bound or make allowances for that. \$\endgroup\$ – xnor Apr 2 at 6:30
  • \$\begingroup\$ I think the precision convergence rule is too restrictive and too tied to that specific power series method, and some loose accuracy bound would allow more varied methods. For instance, one can approximate \$e^M \approx (I+M/n)^n\$ for large \$n\$. \$\endgroup\$ – xnor Apr 2 at 6:38
  • \$\begingroup\$ @xnor I didn't read much into the matrix exponential (because I couldn't find the article on Wikipedia and was too busy watching the rest of the 3b1b video :P), so I hadn't not really realised there were other ways to compute it. What would you recommend? I still like the idea of requiring it to be observed to converge within floating point limits, because it adds an extra layer of challenge rather than just "repeat this step 100 times", but maybe that just isn't practical \$\endgroup\$ – pxeger Apr 2 at 6:50
  • 2
    \$\begingroup\$ I think convergence within floating point limits would unfortunately be hard and finicky here because of the nature of exponentials. The same way that \$e^{100}\$ and \$e^{100.001}\$ differ a lot, small errors in the computation can accumulate into huge ones. Also, the values in the output might be extremely small and become represented as zero. I'd have to think more about bounds, but maybe something like every entry within either 1% or 1e-4 of the true one should work. \$\endgroup\$ – xnor Apr 2 at 7:03
  • 1
    \$\begingroup\$ My solution to floating-point errors is "the result should be within [insert error bound here] relative error for the given test cases". (The bolded part is VERY important. FP computation methods often have errors dependent on the magnitude of the input, so it is very hard to judge if an implementation is valid, even if the possible input range is specified. Explicitly giving the test cases makes it much easier to test submissions. Also, you need to craft the test cases carefully so that you don't accidentally ban a valid method or allow invalid methods.) \$\endgroup\$ – Bubbler Apr 4 at 23:28
2
\$\begingroup\$

Quoted rational numbers

\$\endgroup\$
2
\$\begingroup\$

Battery charging tracker

If there are any better titles please post them in the comments


If any more tags might be appropriate, please post them in the comments


The task here is to create a program which can output a battery's percentage at all times. It will be given input in the form of an array of "indications". These dictate when to plug and unplug the charger.

If this sounds confusing, let us take this sample input:

[[12, 23, 34], [15, 28, 67]]

Note: you can take input in the form of a list of strings or a single string if you would like.

The first array indicates the number of seconds to wait before unplugging the charger, and the second one indicates the number of seconds to wait before plugging in the charger. There will never be two coinciding values in one of the arrays or between the arrays. So [[11, 22, 33], [15, 22, 34]] is not valid input and neither is [[1, 2, 3, 3, 6], [15]]. Both arrays are guaranteed to have at least one value in them. Also, all values are positive non-zero integers.

The "battery" we are trying to simulate starts with 0%. When your program runs, the charger is automatically "plugged in", and each second the charge should tick up by 1% if the charger is plugged in, and decrease by 1% if it is not.

Each second, the program should output the amount of charge the battery has. It should not charge beyond 100% and should not go down below 0%; if the battery hits 100% then it will stay there until the charger is unplugged and if it hits 0% it will stay there until the charger is plugged in.

In addition, your program should store a "second counter" containing information on how long the program has been running for. When this counter hits any of the integers in either of the input arrays, the charger will be either unplugged or plugged in depending on which array it was in. It is guaranteed that between two "unplug" events there will be at least one "plug" event and vice versa, and it is also guaranteed that the first event is "unplug".

Whenever the charger is unplugged or plugged, a "U" or "P" should be shown, respectively.

In the case of our sample input, the charger is "unplugged" when the counter reaches twelve, 23 or 34 seconds and is "plugged" when the counter reaches fifteen, 28 or 67 seconds.

What, then, is the output of our example?

1
2
3
4
5
6
7
8
9
10
11
12
U
11
10
9
P
10
11
12
13
14
15
16
17
U
16
15
14
13
12
P
13
14
15
16
17
18
U
17
16
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0
0

To be clear, the first zero should not be outputted, the charger is acted on after the corresponding second, meaning that we wait 12 seconds before unplugging the charger; the 12th second does not happen after the charger is unplugged. The program runs for the highest value in the input array, in this case 67.

The question is so the shortest answer in bytes wins. Standard loopholes are not allowed here.

\$\endgroup\$
2
  • \$\begingroup\$ You should clarify that the program does not need to wait 1 second between each output (assuming that is the case). Also, title suggestion: Battery charging tracker or something along those lines? \$\endgroup\$ – pxeger Apr 5 at 17:17
  • \$\begingroup\$ @pxeger thanks for the suggestion, the program should wait 1s between each output except for the U or P indicators \$\endgroup\$ – ophact Apr 5 at 17:33
2
\$\begingroup\$

Overwrite a string on a tape

\$\endgroup\$
2
  • \$\begingroup\$ Related \$\endgroup\$ – Razetime Apr 6 at 5:06
  • \$\begingroup\$ I've edited this down to a stub now that it's been posted to save space \$\endgroup\$ – caird coinheringaahing Apr 11 at 14:34
2
\$\begingroup\$

Draw the flag of Bangladesh

,

The flag of Bangladesh is very simple. It looks like below:

enter image description here

The flag will be in bottle green (#006a4e) and rectangular in size in the proportion of length to width of 10:6, with a red circle in near middle. The red circle will have a radius of one-fifth of the length of the flag. This image will help you to understand the proportions properly:

enter image description here

In this Graphical output challenge, you need to draw the flag of Bangladesh like first image. Standard loopholes apply, Shortest code wins.

Resolution cannot be 0px, or echo style answers not supported.

Minimum resolution is 286*176

\$\endgroup\$
8
  • 1
    \$\begingroup\$ I think you need to state a minimum resolution. \$\endgroup\$ – Adám Apr 12 at 8:28
  • \$\begingroup\$ @Adám what do you mean by minimum resolution? \$\endgroup\$ – Wasif Apr 12 at 8:29
  • 1
    \$\begingroup\$ If my output is 0px tall, then the width has to be 10×0px÷6=0px wide, and the red circle's diameter has to be 4×0px÷6=0px. Easy; here you go: \$\endgroup\$ – Adám Apr 12 at 8:31
  • \$\begingroup\$ You should also specify what the colours are and/or if an exact colour match is acceptable. \$\endgroup\$ – Adám Apr 12 at 8:32
  • \$\begingroup\$ Is ASCII art acceptable? \$\endgroup\$ – Adám Apr 12 at 8:33
  • \$\begingroup\$ @Adám ascii art is not acceptable, also in place of bottle green (#006a4e) dark green is acceptable, if you have more flaws come to chat \$\endgroup\$ – Wasif Apr 12 at 8:35
  • \$\begingroup\$ You had specified the color of green background. So what is the color for the circle? \$\endgroup\$ – tsh Apr 13 at 3:52
  • \$\begingroup\$ @tsh I suppose it is #f42a41 \$\endgroup\$ – Adám Apr 13 at 7:46
2
\$\begingroup\$

Saboteurs in our Halls

This is a challenge, where one member on each team attempts to sabotage their team in secret.

Similar to Red vs. Blue - Pixel Team Battlebots, bots will be divided into teams, based on the user ID number of the user who posted them. Your user ID can be found by navigating to your profile (click your icon in the top bar) and looking at the URL:

https://codegolf.stackexchange.com/users/[user-id]/[display-name]

For example, my user ID is 66833: https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing

If your ID is an even number, then you are on the Red team.
If your ID is an odd number, then you are on the Blue team.
There is no way to change teams.

As you cannot change your user ID, and to prevent one team flooding the field with bots, each user may only submit one bot


How the KotH will work

At the start of the game, each bot will be placed in a random cell in a \$1000\times1000\$ cell grid. No bot will be placed on the same cell as another bot, or within 5 cells of another bot. Additionally, \$999\$ random cells will be filled with 1 food. These cells may be any cell on the board that doesn't contain a bot.

The aim of the game is to collect food. Each bot will navigate their way around the grid, attempting to gather food. The team with the most food at the end of the game wins.

However, one bot will actually be a saboteur. This bot will appear to be a member of one team, but will instead act in a manner that helps the other team. When writing your bot, you should consider the existing bots on the opposing team and try to write in a sabotage tactic that will help them without being overly obvious.

Let's say that for this specific match, the saboteur is Blue. Their actions should aim to help the Red team win, while not giving themselves away to the Blue team. If either team suspects that bot to be the saboteur, they can then act in a preventative manner towards that bot. If Blue wins, the saboteur has failed, and so will get no points when the rest of Blue does. If Red wins, then the saboteur has succeeded, and thus gets 2 points. No matter which team the saboteur is on, each member of the winning team always gets 1 point.

Which bot is the saboteur is randomly chosen at the start of the game and remains constant until the game ends. There is only ever one saboteur per game.


The game is broken up into turns. Each team acts on alternating turns, so Red moves, then Blue, then Red etc. or the other way around. Each turn, each bot will be passed a list of game data, detailed below, and will return an integer between \$1\$ and \$9\$ inclusive, indicating which direction it would like to move in:

enter image description here

The bot is at \$5\$ before moving.

The bots for each team are called in a random order each turn, but none of them move until they all have returned values.

After all bots in a team have returned their movement choice, all moves happen at the same time. If two bots on the same team attempt to move into the same cell, neither bot moves. If a bot tries to move out of bounds, nothing happens. If a bot moves into a cell with food, it adds that piece of food to the amount it has already gathered. Initially, all bots have gathered \$0\$ food.

If a bot moves into a cell containing an enemy bot, the two bots fight. The winner is determined by which bot has gathered the most food. The winner then "steals" the losers food, adding it to their total gathered food. The loser is then removed from the board and re-placed at a random location not within 5 cells of another bot, and with an initial \$0\$ food again. If both bots have the same amount of food, then both bots are removed and re-placed, and any food they had is randomly placed in empty cells around the board.

After \$10000\$ turns, the game ends. Each team has their total gathered food counted, and the team with the most food wins. The actual competition will have \$100\$ games played. If a team wins a game, each team member receives 1 point. However, if the saboteur's team (the one it's on, not the team it's helping) wins, the saboteur does not get this point. If the saboteur's team loses, the saboteur gains 2 points.

The team with the most total points of all its bots at the end of \$100\$ games wins.

How to answer

You should include in your answer 2 functions: move and sabotage. move is the function that will be called each turn when you aren't the saboteur and sabotage will be called each turn that you are the saboteur.

Both functions will receive the same arguments:

  • x and y. The x and y coordinates of your bot, each an integer between \$0\$ (top-left corner) and \$999\$ (bottom-right corner).
  • food. The current amount of food you are carrying. Initially 0, and changed by the controller for you when necessary.
  • t_near. A list of bots on your team within a square, side length 33 cells, centered on you. Each bot is represented by a list containing their x and y coordinates, the amount of food they're currently carrying, and the CGCC ID of their poster.
  • e_near. A list of bots n the opposing team within a square, side length 33 cells, centered on you. Each bot is represented by a list containing their x and y coordinates, the amount of food they're currently carrying, and the CGCC ID of their poster.
  • f_near. A list of coordinates of all food within a square, side length 33 cells, centered on you. Each food is represented by a pair [x, y] representing it's coordinates
  • team_chat. A list of all chat messages sent between your team.

Messages

In order to allow inter-game cooperation, each team will have a "chat" ability. Each bot will be passed team_chat, an array containing the chat history of that team - i.e. a series of strings saying more-or-less whatever you want. The most recent message will be at the end of the array. Each bot may, on each turn, append up to 3 messages to the chat. Each message must be no longer than 100 characters, and will be prefixed with the ID of the bot who sent it (with a space after the ID).

For example, if a bot with a user ID of 1234 sent Hello, World! to the chat, the message would be 1234 Hello, World!.

Example Submission

This is Joey. Joey isn't too smart, and hasn't got the hang of proper sabotage. If not the saboteur, Joey just hunkers down and waits for the game to end. Otherwise, he moves around the board aimlessly in random directions:

import random

def move(x, y, food, t_near, e_near, f_near, team_chat):
	return 5

def sabotage(x, y, food, t_near, e_near, f_near, team_chat):
	return random.randint(1, 9)

Rules

Any attempted gaming of the rules will lead to a disqualification of your bot. If you break any rules, your bot will be disqualified until it is fixed (if possible).

  • You may only edit your answer within 12 hours of posting to prevent answers that continually optimise against new bots. You may not delete and repost your answer in order to try to circumvent this restriction
  • Your code must not take longer than half a second (give or take a few milliseconds) to return its move
  • You may not attempt to modify the controller or other bots' code; attempt to communicate outside of using the team chats; make web queries; or do anything malicious.

I'll keep an eye out for other unsportsmanlike behaviour, such as stealing code verbatim from other answers or using sock puppets to mess with the other team.

You are welcome to collaborate and scheme with your team, but keep the contest friendly and ethical. We don't need or want this to devolve into anarchy.

You will have 2 weeks from the posting of the challenge to submit bots. After which time, I'll run 100 games with 10000 turns each and determine the winner


Meta

  • Is this clear enough?
  • Is this a duplicate?
  • I'm not sure whether to write this in Python or Javascript. On the one hand, I'm better at Python, but Javascript is more popular/used. Thoughts?
  • Tags are , , . Suggestions?
  • Any further feedback?
\$\endgroup\$
4
  • 1
    \$\begingroup\$ Very nice challenge :) Just one thing: have you considered letting bots know about the food quantity of nearby bots (in t_near and e_near)? I think it could give the saboteur a little more room to do his job (like kamikaze against enemies if they have more food than he does). Otherwise, it seems to me that there aren't many ways for the saboteur to help the enemy team, but maybe I just haven't given it enough thought. \$\endgroup\$ – Delfad0r Apr 11 at 16:14
  • \$\begingroup\$ Also, do you plan to do anything to prevent unbalanced teams (i.e. teams of different sizes)? It seems to me that having one less teammate is almost as bad as having a saboteur in your team, although this is probably because (as I said above) I still haven't found many effective strategies for the saboteur. \$\endgroup\$ – Delfad0r Apr 11 at 16:18
  • \$\begingroup\$ @Delfad0r Yeah, that sounds like a good idea, editing in the food suggestion for t_near and e_near. I'm not sure about dealing with unbalanced teams (it seems as though it wasn't a problem with Red vs Blue, which gives some kinda hope) \$\endgroup\$ – caird coinheringaahing Apr 11 at 16:25
  • \$\begingroup\$ @Delfad0r Nope, that's a mistake - fixed \$\endgroup\$ – caird coinheringaahing Apr 12 at 13:32
2
\$\begingroup\$

The Meeker numbers sequence

\$\endgroup\$
1
  • 1
    \$\begingroup\$ I've edited the draft a bit, mainly "The Challenge" section to be more in line with the standard [sequence] rules (which is what I think you were going for). I've also cleared up some of the wording. Feel free to revert/rollback if you dislike my changes \$\endgroup\$ – caird coinheringaahing Apr 11 at 13:57
2
\$\begingroup\$

R.E.P.A.I.R. T.H.E. K.E.Y.B.O.A.R.D.

\$\endgroup\$
7
  • \$\begingroup\$ This is a very good challenge, apart from one thing - help mode is FAR too overpowered. I could take +, * and h (in Python), and write the password as chr(1+1+1.....) +chr(1+1+1.....) and write all of the characters that way, using multiplication to ease the process. Though, without it, I think this becomes a very interesting challenge, especially for languages like Befunge-98/<><, which would be unable to do as such. An idea would be to ban +/*, or add a penalty for using it, though I'm just throwing ideas around at this point, so take my upvote. \$\endgroup\$ – StackMeter Apr 11 at 9:37
  • \$\begingroup\$ @StackMeter i reduced help mode to take one key only \$\endgroup\$ – Wasif Apr 11 at 9:59
  • \$\begingroup\$ Thanks - that should cover any loopholes. \$\endgroup\$ – StackMeter Apr 11 at 10:27
  • \$\begingroup\$ Are functions/programs allowed to share auxiliary definitions? For instance, if two of my programs need a function for (say) computing the factorial, do I count the bytes of this function once or twice? \$\endgroup\$ – Delfad0r Apr 11 at 10:52
  • \$\begingroup\$ @Delfad0r you have to write seperate programs for different keys, and so unlike your example you have two use the function twice instead of once, and it will doubled in the byte count. But don't worry its not code golf! \$\endgroup\$ – Wasif Apr 11 at 11:15
  • \$\begingroup\$ DISALLOW WHITESPACE!!!!!!!!! I cannot stress this enough. \$\endgroup\$ – A username Apr 12 at 9:34
  • \$\begingroup\$ @Ausername then I'd disallow deadfish~ too \$\endgroup\$ – Wasif Apr 12 at 9:42
2
\$\begingroup\$

Make it prime with the smallest suffix


Posted

\$\endgroup\$
3
  • \$\begingroup\$ "Your solution must work for the largest integer your language supports" If my language support integers in 0~n. Is this means my program should support all inputs in range 0~n? Or is this means my program should support all inputs when connect it with its output, the result of connection still in 0~n? \$\endgroup\$ – tsh Apr 14 at 3:07
  • \$\begingroup\$ Java has support to signed 64 bit integers as long type. But Java also have java.math.BigInteger support. By saying "largest integer your language supports", does it means I must working on BigInteger instead of long or int types? \$\endgroup\$ – tsh Apr 14 at 3:11
  • \$\begingroup\$ @tsh my intent here was that Java users would have to do that, yes. Considering that java isn't that popular of a golfing language to begin with, I'm not really concerned about the insane verbosity that brings. I am, however, considering bringing the cap to \$2^{53}-1\$ since that's the largest odd integer that can be represented with double-precision floats. \$\endgroup\$ – Beefster Apr 14 at 16:05
2
\$\begingroup\$

Posted

\$\endgroup\$
4
  • 1
    \$\begingroup\$ There's many challenges which have this as a subproblem, but no exact dupe I could find. \$\endgroup\$ – Razetime Apr 12 at 5:34
  • 2
    \$\begingroup\$ Presumably, code-golf? And add decision-problem array-manipulation \$\endgroup\$ – pxeger Apr 12 at 6:45
  • 1
    \$\begingroup\$ Heh, lots of solutions to this exact problem were presented at the recent APL conference. \$\endgroup\$ – Adám Apr 12 at 8:29
  • 3
    \$\begingroup\$ Given how trivial this is, I'd suggest just limiting it to digits 1 to 9, as the overall approach isn't going to change much in list-based languages, but it'll allow string based languages (e.g. Retina) to compete better/easier. Also, as far as I can tell, this is, somehow, not a dupe \$\endgroup\$ – caird coinheringaahing Apr 12 at 13:09
2
\$\begingroup\$

Worst time complexity for an irreducible program

Time complexity, typically represented in Big O notation, represents how long a program will typically take to run given some input(s), ignoring constants.

Your task is to do one of the following things, with the worst time complexity possible:

  • Sort an array of integers
  • Find duplicates in an array

Tasks:

All of the tasks involve taking one input, an array of items, in any reasonable format, and returning an array. If your language supports mutable array data types, this is an allowed output format. Assume all items in the arrays will be (not necessarily positive) integers.

If you choose sorting: You may choose to sort the array by minimum or maximum.

If you choose listing duplicates: You may include a duplicate item any number of times in the output; [1, 2, 2, 3, 4] could result in [2, 4], [2, 2, 4], or even [2, 4, 4, 4].

Rules:

Your program must be irreducible. This means removing any slice of the program, other than the whole thing (or nothing), will cause it to no longer perform the required task. Your program should terminate in a finite amount of time. You can assume your program will never run out of memory, and it does not have to terminate before the heat death of the universe.

This is a . The winner will be based on the average time complexity, with slower being better, followed by the minimum and then maximum for ties.

\$\endgroup\$
2
  • \$\begingroup\$ Unfortunately, this answer broke all "irreducible" challenges. You can execute (almost) arbitrary code unrelated to the task without breaking the "irreducible" requirement. \$\endgroup\$ – Bubbler Apr 22 at 0:16
  • \$\begingroup\$ @Bubbler Hmm, and I don't think irreducible is a sensible requirement for this either. It definitely makes more sense with bytes than time, along with pristine. I'll have to think about some creative limitations. Maybe unique bytes only? \$\endgroup\$ – Redwolf Programs Apr 22 at 0:22
2
\$\begingroup\$

Sr. 4Der says make this shape! (Episode 1)

\$\endgroup\$
3
  • 2
    \$\begingroup\$ I feel like it might be better if the answerers just chose the character they wanted to use, and then this would be a kolmogorov-complexity challenge. \$\endgroup\$ – user Mar 25 at 13:18
  • 3
    \$\begingroup\$ "Adjust the size if needed" isn't a very precise requirement. What's the smallest valid solution? What are the necessary and sufficient requirements for a solution to be valid? \$\endgroup\$ – 79037662 Mar 25 at 14:26
  • \$\begingroup\$ I've edited this down to a stub now that it's been posted to save space \$\endgroup\$ – caird coinheringaahing Apr 22 at 0:25
2
\$\begingroup\$

Leave a wake of dead cells behind you

\$\endgroup\$
2
  • 1
    \$\begingroup\$ What if this is impossible? \$\endgroup\$ – Beefster Mar 24 at 15:44
  • 1
    \$\begingroup\$ @Beefster Then I'll happily accept a proof of impossibility \$\endgroup\$ – caird coinheringaahing Mar 24 at 16:24
2
\$\begingroup\$

Quote a rational number

\$\endgroup\$
2
\$\begingroup\$

Sum over an Interval

\$\endgroup\$
2
  • 2
    \$\begingroup\$ I'd suggest just describing the input format ("begins with either ( or [, then 2 integers separated by a comma, ends with either ) or ]") as it's clearer. Related, but not a duplicate. Additionally, will the input always be positive (or non-negative) integers, and will the range ever be empty? \$\endgroup\$ – caird coinheringaahing Apr 20 at 18:58
  • \$\begingroup\$ @cairdcoinheringaahing fixed \$\endgroup\$ – Underslash Apr 20 at 21:02
2
\$\begingroup\$

Best Rolling Ao5

\$\endgroup\$
2
  • \$\begingroup\$ I'd suggest removing [rubiks-cube] and replace it with [array-manipulation and [floating-point]. I'd also recommend not requiring a trailing 0 if the output is only 1 decimal place (e.g. 28.3 for the last example) and mentioning that the sets are overlapping ("computing the ao5 for each overlapping set of consecutive five times") \$\endgroup\$ – caird coinheringaahing Apr 19 at 22:26
  • \$\begingroup\$ @cairdcoinheringaahing I want to keep the trailing zeros because that's how all times are displayed in official results. Does that make sense \$\endgroup\$ – qwr Apr 21 at 3:24
2
\$\begingroup\$

Is this number part of a Collatz prime sequence?

A fast step of the Collatz sequence is defined as

$$s_\mathrm{Collatz}:\mathbb{N}_\mathrm{odd}\to\mathbb{N},\quad n \mapsto \frac{3\cdot n+1}{2}.$$

Given an odd positive integer \$n\in\mathbb{N}_\mathrm{odd}\$, your task is to decide whether or not both \$n\$ and \$s_\mathrm{Collatz}(n)\$ are prime numbers.

Your program should output two distinct and unique values to represent truthiness and falseness, whereby falseness may also be represented by signalling an error.

Since \$n+\frac12(n+1)=n+\lceil\frac n2\rceil\$ for odd \$n\$, the sorted sequence of all numbers which result in truthiness in the above sense is equal to the tail of A158709.

Test cases

-8 -> -        ; undefined behavior
1  -> false    ; (3*1 +1)/2 = 4 is not prime
3  -> true     ; (3*3 +1)/2 = 5 is prime
5  -> false    ; (3*5 +1)/2 = 8 is not prime
7  -> true     ; (3*7 +1)/2 = 11 is prime
11 -> true     ; (3*11+1)/2 = 17 is prime
15 -> false    ; 15 is not prime
91 -> false    ; (3*91+1)/2 = 137 is prime, yet 91 is not
97 -> false    ; (3*97+1)/2 = 146 is not prime
\$\endgroup\$
18
  • \$\begingroup\$ What is the definition defining? Is \$p\$ a Collatz prime iff it's a prime and \$\frac{3p+1}2\$ is a prime? If \$p\$ a Collatz prime iff it's a prime and \$\frac{2p-1}3\$ is a prime? Or is a prime Collatz if either of those conditions hold? \$\endgroup\$ – Peter Taylor Sep 13 '19 at 10:56
  • \$\begingroup\$ @PeterTaylor are they not the same thing? \$\endgroup\$ – Pureferret Sep 13 '19 at 11:09
  • \$\begingroup\$ Alternative phrasing: which of \$p_1\$ and \$p_2\$ are you calling a Collatz prime? \$\endgroup\$ – Peter Taylor Sep 13 '19 at 11:11
  • \$\begingroup\$ @PeterTaylor I mean \$p_1\$ \$\endgroup\$ – Pureferret Sep 13 '19 at 11:22
  • \$\begingroup\$ So neither the input prime nor the Collatz prime need to be prime? \$\endgroup\$ – Jonathan Frech Sep 17 '19 at 7:56
  • \$\begingroup\$ "Input MAY be non-prime, in which case the output is always false (see 15)" -- did you specifically define this behavior or why is the above the case? \$\endgroup\$ – Jonathan Frech Sep 17 '19 at 8:00
  • \$\begingroup\$ @JonathanFrech I'm (personally) only interested in going from prime to prime, but I wanted to define the haviour for non-prime input. When I say 'may be non-prime' I mean, it should be able to handle it, it's an allowed/expected input but not one that gives a True output. \$\endgroup\$ – Pureferret Sep 17 '19 at 10:55
  • \$\begingroup\$ To me it feels like an unnatural extra constraint. \$\endgroup\$ – Jonathan Frech Sep 17 '19 at 12:54
  • \$\begingroup\$ @JonathanFrech it's just defining how to behave with certain inputs. \$\endgroup\$ – Pureferret Sep 18 '19 at 9:12
  • \$\begingroup\$ Citing Exceptional edge cases; such out-of-place definitions are generally frowned upon. \$\endgroup\$ – Jonathan Frech Sep 18 '19 at 9:56
  • \$\begingroup\$ @JonathanFrech I've changed the initial ask, and now it shouldn't be an exception \$\endgroup\$ – Pureferret Sep 18 '19 at 10:23
  • 1
    \$\begingroup\$ Cf. A158709. \$\endgroup\$ – Jonathan Frech Sep 18 '19 at 10:53
  • \$\begingroup\$ @JonathanFrech Do you think this is postable? \$\endgroup\$ – Pureferret Apr 27 at 1:17
  • 1
    \$\begingroup\$ cf. Things to avoid when writing challenges: Prime numbers. Unless there's a mathematical way to avoid any of the existing golfed primality test methods, a task involving primality test is not very interesting. \$\endgroup\$ – Bubbler Apr 28 at 6:09
  • 1
    \$\begingroup\$ @Pureferret I would not post it -- unless you can think of an interesting golf opportunity. You could, however, improve the problem at hand: there are many questions one can ask about Collatz trajectories. And if you ask for something along the lines of "decide if the given number is a multiple of the length of its Collatz trajectory", you get a less arbitrary connection of concepts whilst preserving the topic of divisibility. \$\endgroup\$ – Jonathan Frech Apr 28 at 14:28
2
\$\begingroup\$

Reject tab, return to linefeed

\$\endgroup\$
3
  • 3
    \$\begingroup\$ How exactly are "printing" and "returning" distinguished? Are submissions required to be a function that also outputs to STDOUT in addition to returning a value from the function? Also, I would strongly advise against subjective criteria like having an error message related to tabs, unless they are purely for brownie points; point bonuses, especially ones that can't be judged objectively, are discouraged. \$\endgroup\$ – hyper-neutrino Apr 17 at 17:26
  • \$\begingroup\$ Printing and returning can be considered identical to each other for the purposes of this challenge. \$\endgroup\$ – StackMeter Apr 17 at 18:58
  • \$\begingroup\$ I've edited this down to a stub now that it's been posted to save space \$\endgroup\$ – caird coinheringaahing Apr 28 at 14:15
2
\$\begingroup\$

Solve the Alien Probe puzzle

Posted.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ The description was clear to me, without watching either video. Doesn't seem like the wording needs much improvement. \$\endgroup\$ – Redwolf Programs Apr 28 at 13:54
2
\$\begingroup\$

xkcd 2385

\$\endgroup\$
1
  • \$\begingroup\$ Now that this has been posted, it should probably be edited down and deleted. \$\endgroup\$ – Redwolf Programs May 3 at 1:38
2
\$\begingroup\$

How many Faro Shuffles for a cycle?

\$\endgroup\$
1
  • \$\begingroup\$ @Pureferret it has been! \$\endgroup\$ – pxeger May 3 at 13:27
2
\$\begingroup\$

Sum on a Fenwick Tree!

Background Information: What is a Fenwick Tree?

A Fenwick tree is a way of representing the prefix sums of an array of numbers (basically, it makes it easy to get the sum of a contiguous run of numbers). A normal array has \$O(1)\$ access time, \$O(1)\$ modification time, and \$O(n)\$ summation time, and a prefix sum array has \$O(1)\$ access time, \$O(n)\$ modification time, and \$O(1)\$ summation time. This means that neither is fast enough if you are doing a lot of modifications and summations. Therefore, a data structure known as the Fenwick Tree or the Binary Indexed Tree serves as a comprimise, with \$O(\log n)\$ access, modification, and summation time.

The best way to understand a Fenwick Tree is 1-indexed. They are usually represented as arrays, but I will present them as trees for this example.

Let's say we have an array [1, 5, 3, 7, 6, 2, 8, 5, 3]. A Fenwick Tree for 9 elements would look like this:

enter image description here

If we look at the labels in binary, B is a child of A if all digits to the left of and including A's least significant bit are the same in B. For example, 7 is 111, so it is in the subtree of 110, because 110's LSB is the second digit, and all digits up to the second digit are the same in 110 and 111. 111 is also in the subtree of 100, and 110 is in the subtree of 100. However, 111 is not in the subtree of 010 or 1000. Finally, elements with only one 1-bit are in the subtree of 0, which is a dummy value pretty much.

The value in each node is the sum of all elements between its index in the base array and the index in its parent (exclusive). For example, node 6 will contain the sum of elements 5 and 6. Node 4 will contain the sum of elements 1, 2, 3, and 4. Therefore, the Fenwick Tree for the above array would look like this:

enter image description here

To find the sum of a block of elements from N to M, you can take the sum of the first M and subtract the sum of the first N-1. To modify an element by adding X to it, we need to add X to it and all nodes that contain it within its range. For example, to update element 5, we need to update 5, 6, and 8. In general, if a node is updated, the smallest node not in its subtree needs to be updated. For example, to update 1, we update 1, which requires updating 2. 3 is in the subtree of 2, so we update 4. 5, 6, and 7 are in its subtree so we update 8.

Recall that something is in its subtree if it shares the same digits starting at and to the left of its LSB. Thus, the smallest number we can add to change that is the LSB itself - for example, to get the next value of 6 to be updated, since its LSB is 2, adding any value less than 2 will not change the digits to the left of an including 2, but adding 2 will set the place value of the LSB to a 0 instead of a 1, thus making it a value not in the subtree. So to update 5, we add the LSB, 1, and update 6. We add the LSB and update 8. If we had more values, we'd then update 16, then 32, etc. If we had 13 for example (1101), we'd add 1 and update 1110 = 14, then add 2 and update 10000 = 16.

For this challenge, you will not need to implement this.

In order to add the first N elements, we follow a reversed procedure. Recall that the value in each node is the sum of all elements between it and its parent (exclusive on the latter end). Thus, to add the first N elements, we take the value in N, which gives us the sum of the elements from N to M+1 (where M is its parent's index), then repeat this process to sum the first M elements. Then, the sum from 1 to M plus the sum from M+1 to N gives us the sum up to N.

Recall that a node B is in the subtree of A if it all digits up to A's LSB are the same. Thus, the minimum value we can subtract is B's LSB. This is because if we subtract a value less than the LSB, one of the trailing 0s in B will become a 1, and thus the new value will have a lower LSB than B and not share the appropriate digits. For example, subtracting 1 from 110 (6), the 0 becomes a 1 (101), and thus does not share the same first three digits. We can subtract 2, which removes the 1, and returns a value with a higher LSB, which means it matches the first 2 digits in this case.

In general, to sum the first N elements, if N is 0, we return 0; otherwise, we take the value in the Nth node, and then add the sum of the first N - LSB(N) elements.

The following pseudocode shows implementations of the modify and sum operations on a FT, both iteratively rather than recursively like I described.

func modify(index, change) # index points to the value in the represented array that you are modifying (1-indexed); change is the amount by which you are increasing that value
    while index <= len(fenwick_tree)
        fenwick_tree[index] += change
        index += least_significant_bit(index)

func sum(count) # sum(n) sums the first n elements of the represented array
    total = 0
    while index > 0
        total += fenwick_tree[index]
        index -= least_significant_bit(index)

least_significant_bit(x) := x & -x

Challenge

Given the Fenwick tree for an array a and an integer n, return the sum of the first n values of a; that is, implement the sum function given as an example.

Reference Implementation

A reference implementation in Python for both the make_tree and sum functions is provided here.

Test Cases

These test cases are given 1-indexed, but you can accept a leading 0 to 0-index it if you would like.

[6, 6, 3, 20, 8, 12, 9, 24, 8, 12], 6 -> 32
[6, 4, 3, 36, 1, 8, 3, 16, 5, 4], 3 -> 7
[2, 10, 1, 4, 4, 2, 0, 32, 1, 14], 4 -> 4
[7, 8, 4, 36, 9, 0, 0, 8, 1, 4], 5 -> 45
[3, 0, 7, 12, 4, 18, 6, 64, 6, 14], 6 -> 30
[3, 4, 3, 28, 5, 6, 8, 40, 1, 8], 9 -> 41
[4, 8, 8, 4, 0, 18, 7, 64, 0, 12], 7 -> 29
[9, 0, 6, 16, 8, 14, 5, 64, 3, 18], 0 -> 0
[3, 14, 7, 12, 2, 6, 5, 0, 7, 18], 2 -> 14

Rules

  • Standard Loopholes Apply
  • This is , so the shortest answer in bytes in each language will be considered the winner of its language. No answer will be marked as accepted.
  • You may take the two inputs in any order and the list in any reasonable format.
  • You may assume that the integers in the tree are all non-negative.
  • No input validation - the index will be non-negative and at most the length of the Fenwick tree
  • You may assume that all values (in the list, as the index, and the output) will be at most 232-1

Happy Golfing!


Sandbox

  • Is my explanation of a Fenwick tree sufficient enough that most people can understand it?
  • Are my test cases sufficient?
  • Any more tag suggestions?
\$\endgroup\$
2
  • \$\begingroup\$ I think you should clarify what a Fenwick tree is within the post itself, in addition to the code. \$\endgroup\$ – Redwolf Programs May 3 at 18:26
  • \$\begingroup\$ The explanation on Fenwick trees is decent, but the amount of text is slightly discouraging; I would try to reduce it a fair bit. Personally I think having a visual like this would be more helpful as it gives an intuitive understanding of the tree structure, in relation to the array. \$\endgroup\$ – dingledooper May 4 at 5:03
2
\$\begingroup\$

Solve the halting problem for \c^/[^/\\]*/[^/\\]*/[^/\\]*$c

///, a.k.a. Slashes is an esoteric programming language with simple two operations. One is to output its source to remove from it. The other is to substitute itself.

For simplicity I am assuming the case when the program matches \c^/[^/\\]*/[^/\\]*/[^/\\]*$c, which is /pattern/replacement/rest but no more special characters than two slashes.

Given pattern, replacement, and rest of the program, determine whether the program halt or not.

Assume that pattern and replacement are already escaped. Also your program/function/snippet must distinguish two or more characters.

Examples

pattern,replacment,rest: Does it halt?
"","","": No
"foo","foobar","foo": No
"1","0*","110010": Yes

Rules

Meta

  • Were similar things ever done before?
\$\endgroup\$
2
  • 1
    \$\begingroup\$ /// is turing-complete, so this is not possible \$\endgroup\$ – pxeger Apr 25 at 12:33
  • \$\begingroup\$ Should we simplify it more? \$\endgroup\$ – tail spark rabbit ear Apr 25 at 20:23
1
27 28
29
30 31
110

You must log in to answer this question.

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