568
\$\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

4556 Answers 4556

1
24 25
26
27 28
152
3
\$\begingroup\$

Find the centroid of a spherical polygon on Earth

Given a list of N (latitude, longitude) coordinates in decimal degrees, coord={{lat1,lon1},{lat2, lon2}, ...,{latN,lonN}}, we consider the spherical polygon enclosed by the geodesics connecting successive pairs of coordinates (including the geodesic between the last and first pair of coordinates). We will follow the convention that the enclosed polygon is always to the left as we traverse each geodesic, i.e., the coordinates are given counter-clockwise around the boundary.

Your task is to find the coordinates of the centroid (center of mass) of the spherical polygon (technically, the projection of the centroid onto the surface of the Earth).

For example, the coordinates {{0,0}, {60,0}, {0, -90}} define a spherical triangle with a centroid at {24.5839, -37.5891}:

Simple Example

Specifications and Assumptions

  • Assume a perfectly spherical earth with a radius of 1.
  • At least 3 coordinates will be specified; there could be arbitrarily many. All the coordinates will be distinct and properly define a spherical polygon in counter-clockwise ordering (no crossing geodesics, no zero-area polygons, no lunes, etc.).
  • To avoid edge cases and indeterminate inverse trig evaluations, all given coordinates will be confined to a single hemisphere. Furthermore, you do not need to handle inputs that would result in a centroid at the North or South Pole nor a longitude of +180=-180 degrees. (These would be valid inputs though!).
  • The input format is flexible: list of lists, array, .csv file, etc. The output coordinates of the centroid should be given to at least 3 decimal places in the decimal degree format, but may otherwise be returned as you see fit.

One possible approach

One possible approach is a neat application of Stokes' Theorem, partially illustrated in this stack overflow answer, and is outlined as follows:

  1. Duplicate and append the first pair of coordinates: {{lat1,lon1},{lat2, lon2}, ...,{latN,lonN}, {lat1,lon1}}
  2. Convert these lat/long coordinates to unit vectors in Cartesian (rectangular) coordinates, \$\vec{v_i}\$, \$i=1,...,N+1\$. NB. Latitude is measured in degrees away from equator (\$xy\$-plane) as opposed to the common mathematical convention of measuring spherical coordinates from \$z\$-axis.
  3. Compute the sum \$\vec{c} = \sum_{i=1}^N \frac{1}{2}\cdot \frac{ \vec{v_i} \times \vec{v_{i+1}}}{\Vert \vec{v_i} \times \vec{v_{i+1}} \Vert} \mathrm{ang}(\vec{v_i}, \vec{v_{i+1}})\$ to find the 3D Cartesian coordinates of appropriate moment, where \$\times\$ is the cross-product and \$\mathrm{ang}(\vec{a}, \vec{b})\$ is the angle between vectors \$\vec{a}\$ and \$\vec{b}\$. (Note that \$\mathrm{ang}\$ can return either radians xor degrees, so long as it does so consistently. The choice of degrees vs radians effectively corresponds to a rescaling of the sphere, which is cancelled out in the following normalization step.)
  4. Normalize \$\vec{c}\$ to project the centroid to the surface of the sphere, \$\vec{c}/\Vert \vec{c} \Vert \$.
  5. Convert these Cartesian coordinates to lat/long using inverse trig functions.

Be careful to mind radians vs degrees and inverse trig function ranges within your chosen language. Also, some parts of this given algorithm may or may not be superfluous...

More Test Cases

{{0, 170}, {-90, 0}, {0, -160}} has a centroid of {-32.7795, -175.0000}

{{26.158, -80.326}, {35.803, -78.722}, {36.103, -115.178}, {32.791, -96.81}} has a centroid of {33.9037, -90.7267}

{{52.37, 4.89}, {41.89, 12.5}, {37.98, 23.73}, {46.06, 14.51}, {52.52, 13.38}, {52.26, 21.02}, {60.17, 24.94}} has a centroid of {50.0215, 14.5968}

Rules

E: Sandbox Questions

Any comments on difficulty/question scope? I think the connection with lat/long coordinates on earth is a nice motivation, but about half of my program to generate test cases is purely coordinate conversions. For reference, my very un-golfed program (complete with camelCase function names) is ~500 bytes.

There are certainly ways to make the task simpler or more complex:

  • The easiest version (I think) would be to forget about the earth and lat/long entirely and have a purely geometric question. Inputs and outputs as unit Cartesian vectors.
  • A harder version would not use a spherical earth approximation, but rather require an ellipsoidal earth or even a proper geodetic datum. However, I think this becomes very difficult very quickly--even finding a geodesic on a geoid is hard, let alone the given algorithm requiring proper (numerically approximated) line integrals rather than a sum. Simultaneously, the task would likely become trivial with commercial GIS software. Using a more accurate earth model does significantly impact the centroid coordinates, changing it by up to several degrees for the given test cases.
\$\endgroup\$
3
\$\begingroup\$

Logarithmic incrementation

\$\endgroup\$
7
  • 1
    \$\begingroup\$ Is there precedent in using $x\ast$ for the length of a list? I've always encountered $#x$. \$\endgroup\$
    – RubenVerg
    May 26 at 13:27
  • \$\begingroup\$ @RubenVerg just thought I’d use that notation. I don’t think it matters. \$\endgroup\$ May 26 at 13:28
  • \$\begingroup\$ You're also missing an indication for empty lists: either say that they never occur or specify what the value should be \$\endgroup\$
    – RubenVerg
    May 26 at 13:38
  • \$\begingroup\$ @RubenVerg fixed \$\endgroup\$ May 26 at 14:28
  • 2
    \$\begingroup\$ actually, f([n, n, n, ..., n]) = n + 1 for any list length, which is even more interesting (and trivially provable) \$\endgroup\$
    – RubenVerg
    May 26 at 17:01
  • \$\begingroup\$ Can we get some test cases please? \$\endgroup\$
    – The Thonnu
    May 28 at 13:46
  • 1
    \$\begingroup\$ @TheThonnu test cases have been made. \$\endgroup\$ May 28 at 15:38
3
\$\begingroup\$

Vanilla Natural Logarithm Challenge

There is a challenge for multiplying two numbers so I guess this counts too

Given as input a positive real number n compute its natural logarithm.

Your answer should be within \$10^{-6}\$ for \$1 \leq n \leq 10\$ and within \$10^{-3}\$ for \$0.1 \leq n \leq 100\$. You don't need to handle numbers outside this range.

See this thread on mathematics.se for various approaches to this problem. Just for inspiration, feel free to use a method not on that page.

Using builtins for logarithms is discouraged but not forbidden. Consider marking your language as "community wiki" if you just use a builtin.

Test Cases

x ln(x)
0.1 -2.3025850929940455
0.25 -1.3862943611198906
0.5 -0.6931471805599453
0.75 -0.2876820724517809
0.9 -0.10536051565782628
1.0 0.0
1.3 0.26236426446749106
2 0.6931471805599453
2.718281828459045 1.0
3.141592653589793 1.1447298858494002
4 1.3862943611198906
5 1.6094379124341003
7 1.9459101490553132
10 2.302585092994046
53 3.970291913552122
54.59815003314423 4.0
99 4.59511985013459

IO

Standard IO rules apply. Importantly, you may take input as a fraction if you prefer. You may also output as a fraction, which does not need to be fully reduced.

\$\endgroup\$
8
  • 1
    \$\begingroup\$ "Using builtins" — surely one must use some buildins‽ \$\endgroup\$
    – Adám
    May 30 at 12:29
  • \$\begingroup\$ @Adám Not really… there are methods for doing this. \$\endgroup\$ May 30 at 12:30
  • 1
    \$\begingroup\$ @Hippopotomonstrosesquipedalian I can't imagine solving this without any builtins. \$\endgroup\$
    – Adám
    May 30 at 12:31
  • \$\begingroup\$ @Adám just needs a for loop and the 4 basic arithmetic operations \$\endgroup\$ May 30 at 12:44
  • 1
    \$\begingroup\$ According to Adam those are technically builtins, I've clarified though so there is no need to further pollute the comments \$\endgroup\$
    – mousetail
    May 30 at 12:45
  • \$\begingroup\$ Is there any reason for the increased accuracy requirement between 1 and 10? \$\endgroup\$ May 30 at 19:41
  • \$\begingroup\$ @Hippopotomonstrosesquipedalian most approximations are more accurate around that range \$\endgroup\$
    – mousetail
    May 30 at 19:41
  • \$\begingroup\$ You deserve an upvote. Anyways, I have a programme in mind that just requires me to increase a k value if it isn't precise enough. \$\endgroup\$ May 30 at 19:47
3
\$\begingroup\$

Lowest digit addition generator

A digit addition generator of an integer n is any integer x that satisfy the equation x + s(x) = n, with s(x) being the sum of the digits of x. (We will work under base 10 for convenience.)

For example, a digit addition generator for 29 would be 19, because 19 + (1 + 9) = 29. Some numbers have more than one generator. An example might be 216, which has generators of 198 and 207.

Your objective is to generate the lowest digit addition generator of every non-negative integer n, and output anything other than a non-negative integer if there is none for n. The non-negative terms in your result should match the sequence A096234. You may find this paper related to the challenge.

Fewest bytes win; standard rules apply.

\$\endgroup\$
11
  • \$\begingroup\$ Do sequence rules apply? (Since you haven't put any tags) \$\endgroup\$
    – mousetail
    Jun 13 at 14:17
  • \$\begingroup\$ This doesn't output any sequence, to my knowledge... the program should accept an integer and output another. Maybe I should get that edited in. \$\endgroup\$ Jun 13 at 14:20
  • \$\begingroup\$ It might be shorter to just output the LDA for every number in sequence infinitely \$\endgroup\$
    – mousetail
    Jun 13 at 14:25
  • \$\begingroup\$ After 2 minutes of introspect, I realized that the OEIS didn't exist for nothing... Time to add a new tag and also a rewrite. \$\endgroup\$ Jun 13 at 14:28
  • \$\begingroup\$ I'd also suggest allowing any non-positive value, not just -1 on errors. Something like None or "" could be shorter depending on the language. \$\endgroup\$
    – mousetail
    Jun 13 at 14:30
  • \$\begingroup\$ @mousetail Edited. Do you have any more suggestions? \$\endgroup\$ Jun 13 at 14:33
  • \$\begingroup\$ By the way, welcome to Code Golf, and thanks for using the Sandbox! \$\endgroup\$
    – The Thonnu
    Jun 14 at 20:01
  • \$\begingroup\$ @TomEpsilon I feel like still @mousetails' suggestion isn't fully implemented - None doesn't fit the "any negative number" definition for when there is no generator. \$\endgroup\$
    – pajonk
    Jun 15 at 4:33
  • \$\begingroup\$ I agree, and plan to implement the wording of "anything other than a non-negative integer". \$\endgroup\$ Jun 15 at 6:40
  • \$\begingroup\$ Edit successful. Do you have any more suggestions? \$\endgroup\$ Jun 15 at 6:42
  • \$\begingroup\$ Alright. If there is none, I shall post it on the site. \$\endgroup\$ Jun 15 at 8:08
3
\$\begingroup\$

Compute the maximal Ducci period

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

Diagonalize a vector

\$\endgroup\$
3
  • \$\begingroup\$ +1 because this is an opportunity for less usable languages to do well or at least be able to compete. Could you add two or three test cases? \$\endgroup\$
    – noodle man
    Jul 13 at 18:02
  • \$\begingroup\$ if $n = 0$, must the result be a 0x0 matrix (if such a concept exists in the language), or is a 0-element vector acceptable? \$\endgroup\$
    – RubenVerg
    Jul 13 at 18:18
  • \$\begingroup\$ @RubenVerg yes, that's fine \$\endgroup\$
    – bigyihsuan
    Jul 13 at 18:34
3
\$\begingroup\$

Fast and Golfiest Challenges

I am planning on creating a series of cops-and-robbers style challenges. My inspiration is the coexistance of code efficiency problems and code golfing problems on this site - and the problem that code efficiency challenges seem to be often overlooked, even though most of competitive programming is centered upon efficiency. So I plan to combine the two in order to let golfers on the site try considering code efficiency as well, and as an opportunity for competitive programming experts to show off their cool knowledge of segment trees and the Bellman-Ford ;-) (alright, maybe not such hard stuff since I still want the challenge to be accessible to most people, especially golfers).

So here comes my idea. Each challenge in the series will be based on one theme (for instance, one theme I have in mind is "The Lords of the Strings", aimed at string operations).

The cops will choose a problem (the difficulty must not be "easy") on the competitive coding platform LeetCode and independently (there's no way to do anti-cheat for this, though, so we'll leave it up to the integrity of the participants themselves) write a both efficient and golfed answer for it. The problem should not be too easy. However, for the cops efficiency is emphasized over golfiness.

The robbers need to improve on the cops' code by golfing up the code (in the same language as the cop's), but here comes the thing: the golfed up version must not be algorithmically slower than the cop version. The robber has to prove this by theoretically proving that the time complexity of their code is lower or equal to the cop code. If it is lower, the robber gets 2.718 times their normal score (will still be rounded to the nearest integer).

Both cops and robbers must report the UTC time of their answer post. The cop's score is the number of hours (rounded to the nearest whole) that pass before the first valid robber answer is posted. The robber's score is the percentage reduction of code bytes compared to the cop code, again rounded to the nearest whole number.

What do you think, community? Any suggestions are very welcome! Thanks in advance :-D

TL;DR: An unusual cops and robbers game. Cops choose a competitive programming problem under a certain theme and write code to solve it. Robbers golf up the cop's code but must not sacrifice efficiency in the process. Cops mainly aim for code efficiency, while robbers mainly aim for code golfing.

Example

Cop

Input n, output 2*n (in the actual challenge please go get a real problem on LeetCode and paste the link).

Code: ,[>+>+<<-]>>[<+>-]<. (Brainfuck, 20 bytes)

2 hours and 40 minutes later...

Robber

Code: ,[>+>+<<-]>[>+<-]>. (19 bytes)

Both have complexity O(n).

Results: Cop gets 3 points (3 hours before first solve) and robber gets 5 points (5% reduction in code length).

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

[Dual scoring criterion challenge concept]

(that's right...three OWC tags on one post :p)


Inspired by The Fast and the Golfiest, I've come up with what might be a novel way to do a combined code golf/fastest code challenge. I haven't decided what the actual task would be, but here's how it would work:

Your score is the number of answers you outgolf, plus the number of answers you outperform.

This means the highest possible score is \$2(n-1)\$, where \$n\$ is the number of answers. The idea is that an answer could focus purely on golfing or on speed, and get a score close to \$n-1\$, but achieving a balance of the two is the only way to do better than that.

Since this scoring method depends on having many answers to compare against, I'm thinking it would work differently from our site's normal rules, and all languages would compete against one another (this is more commonly treated as true in ). In order to keep the side of things fair, any language (including a specific flag combination) used must have at least 10 2 answers, which must meet any of the following requirements:

  • Posted by a user other than OP
  • Posted before the challenge
  • Posted at least two months ago

This limits flag abuse and other tricks to a more acceptable degree. Common flags in flag-abuse-oriented languages like Japt or Vyxal might still be usable, but most languages which have these sorts of flags are enormously uncompetitive in performance.

That's another reason I want to make all languages compete; it makes choosing the language you use an opportunity to strategize. A faster language like C might beat more answers in speed, while losing badly on golfiness, while the reverse may be true for Jelly or Vyxal.

\$\endgroup\$
8
  • \$\begingroup\$ Myxal ought to do well. \$\endgroup\$ Jul 21 at 11:48
  • \$\begingroup\$ Wow, cool thing my challenge inspired others :-) I think it's a cool idea but it's hard to measure performance. We need to find an extremely stable interpreter/compiler for every single language if we wanna do that, and it's just difficult overall. Still, the idea itself is very cool. \$\endgroup\$ Jul 24 at 15:45
  • \$\begingroup\$ @ShiranYuan Testing a few dozen times on the same hardware with countermeasures taken to minimize random noise should make the scoring much more consistent, I think. And any time the distribution of times from two submissions overlaps enough that it's hard to say with certainty which is faster, could always just run a dozen more tests. It's imperfect, but should work fine \$\endgroup\$ Jul 24 at 16:34
  • \$\begingroup\$ @RydwolfPrograms Well, good luck establishing the protocol ;-) \$\endgroup\$ Jul 24 at 21:07
  • \$\begingroup\$ @ShiranYuan I mean, we do already have quite a few fastest-code questions. I'd probably just add in some statistics to make it more rigorous, and set up my test machine in such a way that consistent performance is more likely (I've got a server which I'm going to be using for hosting an online interpreter with code timing functionality, so this will sort of be like an opportunity to get that sort of isolation set up) \$\endgroup\$ Jul 25 at 2:48
  • \$\begingroup\$ @RydwolfPrograms Well what if someone submits code in esoteric languages that have no "canon" interpreter, like Brainfuck? \$\endgroup\$ Jul 25 at 2:57
  • \$\begingroup\$ @ShiranYuan A specific implementation would be required to be specified (and it would anyway, given that, e.g., BF has a wide range of unspecified behaviors that different interpreters vary on) \$\endgroup\$ Jul 25 at 14:14
  • \$\begingroup\$ @RydwolfPrograms Nice idea! I think it's pretty good to go ;-) \$\endgroup\$ Jul 26 at 1:46
3
\$\begingroup\$

Print this pulsar (or "Print this diamond" gone beautifully wrong)

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

Simulate Keyboard Inputs

Background

You know how in text editors and just text fields in general, there's always that blinking bar where you type? Yeah, simulate typing there.

You'll be given 3 inputs: The current text field, the position of the cursor, and the input sequence.

Here's an example:

Hello, World!
5
[U];[U];[B];[B];[B];[B];[B];[U];i;[R];[R];[R];[R];[R];[R];[R];[R];[R];[B];.
=> Hi, World.

Firstly, the number 5 tells us that the cursor is here, represented by the asterisk: Hello*, World!. If you take the string as zero-indexed, and choose the left side, you will find the cursor's starting point.

Next, we have 2 [U]s. [U] is a special input, representing undo. However, there is nothing to undo, so nothing happens.

Then, we have 5 [B]s. [B] is another special input, representing backspace. This tells us to erase 5 characters to the left of the cursor, one at a time. This gives *, World!.

Next, we have [U]. This tells us to cancel out the previous input (if there's anything to cancel out). If you have two [U]s, then you cancel out the last two instructions before the [U]s. Logic extends to all number of [U]s. Cancelling out the previous input, we have H*, World!.

Next, we have i. If there are no square brackets around the character, just add it to the text as a string, to the left of the cursor: Hi*, World!.

Now, we have 9 [R]s. [R] represents Move Cursor Right, so we move the cursor right 9 times: Hi, World!*. Note how it only actually takes 8 [R]s to get to the end, so the final [R] doesn't do anything.

Now, a [B]. This gives us Hi, World*.

Finally, .. This gives us Hi, World..

//

The list of special inputs is shown here:

[B] = Backspace
[U] = Undo
[R] = Move Cursor Right
[L] = Move Cursor Left

Of course, within reason, you can change these special inputs (as long as it won't conflict with any non-special inputs.

//

With regards to other rules:

  • Left or Backspace when the cursor is furthest left does nothing.
  • Right when the cursor is furthest right also does nothing.
  • Undo when there's nothing to undo also does nothing.

Your Task

  • Sample Input:
  1. The current text field
  2. The position of the text cursor (<= length of current text field)
  3. The input sequence

Wrt the input sequence, in my examples I have used a string where each instruction is separated by semicolons. You can take the input sequence in any reasonable format - but note that the no input can contain this character. You can expect the non-special inputs and the text field to contain no \ns or \ts. They will also not contain any [B]s, [, or whatever you're using for making the special input unique.

  • Output: Return the final text field, after the sequence has been executed.

Test Cases

Input => Output

Hello, World!
5
[U];[U];[B];[B];[B];[B];[B];[U];i;[R];[R];[R];[R];[R];[R];[R];[R];[R];[B];.
=> Hi, World.

3987^12 + 4365^12 = 4472^12
27
[L];[B];[L];[L];[B];[B];[B];[B];[B];[U];[U];[L];[U];[R];[B];5;[L];[L];[L];[L];[B];[L];[B];[B];[B];[L];[L];[R];[R];[L];[L];[L];[L];[L];[B];[L];[B];[B];[B];[B];[B];[B];[B];[B];4;[B];3"
=> 3^2 + 4^2 = 5^2

I kinda don't like pepperoni on pizza, yknow?
0
[B];[B];[B];[L];[L];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[U];[B];[B];[B];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R]; ;[R];[R];[R];[R];[R];[B];[R];[R]; and garlic too actuallyk;[B];[U];[U]
=> I kinda do like pepper onion pizza, yknow?

This is [tag:code-golf], so shortest answer wins.
13
[R];[R];[R];[R];[R];[R];[B];c;h;s;[U];a;[R];[R];[B];[B];[R];L;[U];[L];llenge;[R];r;[L];[B];[R];[B];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[B];[B];[B];[B];[B];b;[R];[R];[L];[U];[R];[R];response or ;[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[R];[B];[B];[B];[B];ill accepted as answer.;[U];ill be accepted as answer!
=> This is [tag:code-challenge], so best response or answer will be accepted as answer!

This is , so shortest answer wins.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ IMO, a title that's something like "Simulate keyboard inputs" would be better, as the challenge doesn't really have much to do with the blinking cursor. Also, can we choose what value represents each special input (within reason, of course)? \$\endgroup\$ Jul 23 at 3:07
  • \$\begingroup\$ @SuperStormer Noted, title changed. Also, sure - within reason. Adding that now. \$\endgroup\$ Jul 23 at 9:39
  • \$\begingroup\$ Am I allowed to take a list of characters with special characters as a singleton list? \$\endgroup\$ Jul 30 at 8:36
3
\$\begingroup\$

Meta-cat program

\$\endgroup\$
7
  • \$\begingroup\$ Just replacing " with \" isn't sufficient, is it? I'd probably use JSON.stringify or another function with more edge-case handling. \$\endgroup\$
    – Bbrk24
    Jul 1 at 12:50
  • \$\begingroup\$ @Bbrk24 you can put anything except unescaped double quotes inside a double quote string. Same with single quotes. The only issue is if you use backticks (because you have to escape the ${} stuff) \$\endgroup\$
    – Dadsdy
    Jul 1 at 13:49
  • \$\begingroup\$ It won’t handle unescaped backslashes or newlines in the input. \$\endgroup\$
    – Bbrk24
    Jul 1 at 13:50
  • \$\begingroup\$ @Bbrk24 fixed now \$\endgroup\$
    – Dadsdy
    Jul 1 at 13:52
  • \$\begingroup\$ Still doesn’t handle unescaped line breaks (you can only have those in template strings, not double-quoted strings) \$\endgroup\$
    – Bbrk24
    Jul 1 at 14:22
  • \$\begingroup\$ @Bbrk24 should be fixed now \$\endgroup\$
    – Dadsdy
    Jul 1 at 15:52
  • \$\begingroup\$ JSON.stringify should works for any Unicode strings since ES2019 or any ASCII strings since maybe ES5. \$\endgroup\$
    – tsh
    Jul 12 at 3:02
3
\$\begingroup\$

Sleep Forever

Write a program that never exits completely, but also after startup consumes exactly 0.0 CPU time.

This means you must sleep in a way that the operation system never wakes up the process. ps aux | grep [your program] should show %CPU 0.0 at any time after startup.

Note a long sleep in a loop is not enough, since then the OS will need to wake up your program to start the next iteration. You must absolutely never be woken up.

Waking up on signals for the purpose of exiting is OK if your language does that by default. However, no normal input over pipes should not wake your program up.

You can use CPU for any finite amount of time during startup.

This is , shortest code wins.

Meta:

I need some help with the signals exception. I don't want submissions to need to spend a large amount of code to disable all signal handlers present by default, but also I don't want programs that just "wait for a keypress" for example which isn't really reasonable.

I also want to avoid giving significant advantages to languages just because of what signal handlers they do/do not have by default.

I also want to avoid using too much OS specific terminology.

Suggestions appreciated.

\$\endgroup\$
4
  • \$\begingroup\$ Is waiting for input or confirmation OK? E.g. JS alert() \$\endgroup\$
    – Adám
    Jul 18 at 12:32
  • \$\begingroup\$ @Adám No, I could use help how to specify that clearly though \$\endgroup\$
    – mousetail
    Jul 18 at 12:32
  • \$\begingroup\$ What is px? I don't seem to have it, though Ubuntu says I can get it with apt. \$\endgroup\$
    – Bbrk24
    Jul 25 at 1:13
  • \$\begingroup\$ @Bbrk24 I guess they meant ps \$\endgroup\$
    – c--
    Jul 26 at 18:15
3
\$\begingroup\$

Efficient Ouroboros Quine

An ouroborus quine is a program that (taking no input) outputs the source code of a different program, which in turn outputs the source code of a different program, and so on, until after some number of iterations, the result is the source code of the original program. In some cases (often called quine relays) each program is in a different language, but here all the programs forming an ouroboros should be in the same language. Let the period of an ouroboros quine, \$T\$, be the number of distinct programs involved in the loop.

The challenge is to find the most efficient ouroboros quine, achieving the maximum period using the minimum program size. Let the size, \$N\$, be the number of bits (not bytes) in the source code of largest program in the ouroboros. Your score is \$\frac{\log_2 T}{N}\$.

This formula is scaled such that the theoretical maximum score is arbitrarily close to 2, for arbitrarily large \$N\$. A score of 1 is achieved if every possible string of length \$N\$ is a valid program which forms a part of an ouroboros quine. The maximum theoretical score also requires that every possible string of length less than \$N\$ is a program forming part of the ouroboros.

As achieving an arbitrarily high score may require an arbitrarily large program, it is permitted to describe the program (and prove/demonstrate its correctness), rather than providing an arbitrarily large amount of raw code.

Sandbox Questions

  • Is this an interesting (and novel) question?
  • Do I need to specify the output format more precisely, or do standard guidelines on output format suffice?
  • Is allowing a program description, rather than raw code, a disastrous idea? Or, conversely, is it even necessary to state that this is permitted?
\$\endgroup\$
1
  • \$\begingroup\$ Welcome to Code Golf, and very nice first challenge idea! I don't think you need to explicitly state that a description and proof for large programs is allowed (that's usually the default here). See some Unary answers which do exactly that. \$\endgroup\$
    – The Thonnu
    Jul 29 at 13:41
3
\$\begingroup\$

Cut a Pizza into infinite number of slices using the minimum number of cuts

It is well known that with n straight cuts it is possible to cut a circle into \$\frac{n^2 + n + 2}{2}\$ pieces. This is known as the Lazy Caterer's Sequence.

https://en.wikipedia.org/wiki/Lazy_caterer%27s_sequence#/media/File:Central_polygonal_numbers.svg

However, finding the right angles to cut the circle is less easy. The areas after each cut become very small.

Your task is to find these angles. Output a infinite sequence of pairs of angles such that if you connect each pair by a line, you'd cut the circle into \$\frac{n^2 + n + 2}{2}\$ pieces. Angles may be either in degrees, radians, or any other reasonable way to measure angles, can be either floating points, fractions, or any other reasonable way to represent numbers.

As with standard sequence rules, you may:

  1. Print the pairs infinitely
  2. Take an input N then output the Nth chord
  3. Take an input N then output the first N chords.

This is , shortest answer wins.

\$\endgroup\$
5
  • \$\begingroup\$ Nice challenge, a couple of test cases would definitely help when you get the chance. \$\endgroup\$
    – noodle man
    Jul 30 at 12:09
  • \$\begingroup\$ @noodleman There are many possible solutions though \$\endgroup\$
    – mousetail
    Jul 30 at 12:58
  • \$\begingroup\$ Hmm, maybe I don't understand this quite right. Is this not a regular sequence? Is it an open-ended-function or something? I guess I need some kind of example to understand this. \$\endgroup\$
    – noodle man
    Jul 30 at 13:10
  • 1
    \$\begingroup\$ As long as your chords divide the circle into the required number of segments your solution is valid \$\endgroup\$
    – mousetail
    Jul 30 at 13:15
  • \$\begingroup\$ Even with there being many possible solutions I think a clear example of some valid IO is worthwhile. Even just labelling the existing diagram with its angles would make things a lot easier to understand in my opinion \$\endgroup\$ Jul 31 at 19:39
3
\$\begingroup\$

Calculating Transitive Closure

\$\endgroup\$
6
  • \$\begingroup\$ Wouldn't the output for the empty relation be 0? It satisfies the condition for being transitive. \$\endgroup\$
    – bsoelch
    Jul 27 at 8:10
  • \$\begingroup\$ I think the task might be easier to understand, if you add a purely graph theoretic explanation. If I understood it correctly a graph is transitively closed iff any two vertices that are connected by a directed path (or cycle) are also connected by an edge. \$\endgroup\$
    – bsoelch
    Jul 27 at 8:25
  • \$\begingroup\$ @bsoelch Yeah, actually, it should be 0. I'll update that. And yes, I thought I could do a better job explaining, but I would prefer to keep the visuals, I think it makes the question seem more inviting. I can definitely change the visuals though, for an easier-to-understand task. \$\endgroup\$
    – SanguineL
    Jul 27 at 12:12
  • \$\begingroup\$ The visuals also work for the graph theoretic explanation. But only talking about general relations may be a bit to abstract (especially the Wikipedia citations) makes the task sound more complicated than it actually is. \$\endgroup\$
    – bsoelch
    Jul 27 at 12:19
  • \$\begingroup\$ Hmm. I thought talking about general relations would be the easiest way to go about explaining the concept. Introducing cycles and more complicated topics seemed unnecessary. How would you recommend I go about simplifying my question? \$\endgroup\$
    – SanguineL
    Jul 27 at 13:09
  • \$\begingroup\$ I think I'm going to leave the technical definitions in, but also provide a link to a website that explains transitive closure in simple terms. It's not very complicated at all. \$\endgroup\$
    – SanguineL
    Jul 27 at 13:16
3
\$\begingroup\$

Battle Chess Royale (Any better name?)


Imagine a large chess board where different players can choose and place a chess piece. Pieces are Knights, Bishops, Rooks, Kings or Queens. Each piece has an unique movement ability and a point per turn value. The board, after an specific amount of rounds will shrink (as a battle royale field do) disqualifying any player that left its piece outside.

The goal of the game is to get as many points as you can. This can be achieved by simply staying within the safe zone of the board and killing other players to take their points.

Each piece has an specific amount of passive points per turn based on how freely it can move. Below is the table used. Feel free to give any suggestion on point distribution.

enter image description here

Note: Pawns are not added to the game since their movement is similar to a king

For the game, you will select which piece type you wanna play with. The function for your bot will take as a parameter a board (n x n matrix), an array with the available moves your piece can perform, a list with the next players, and finally an object with info about the game (next shrinking round, leaderboard, etc...). Your return value should be your desired move (must be from your available move array).


Bots Examples

new Bishop(function(board, availableMoves, players, gameInfo){
    return availableMoves[0];
}, "Drunky Step");

new Rook(
    (board, availableMoves, players, gameInfo) => 
          availableMoves[Math.floor(Math.random() * availableMoves.length)], 
    "Le Rook"
)

new Queen(function(board, availableMoves, players, gameInfo){
    let targets = availableMoves.filter(move => {
        return board[move[0]][move[1]] != null;
    });
    if(targets.length > 0)
        return targets[0];
    else
        return availableMoves[Math.floor(Math.random() * availableMoves.length)];
}, "Killer")

Here is an example of a 5x5 board with 2 bishops in it

enter image description here


Notes

  • The game will be turn based.
  • Players are randomly shuffled before the beginning of the game
  • There is an specific amount of rounds where you cant capture anyone
  • Board always shrinks towards the center
  • If you die or get captured, you score remains
  • It is possible to die because of board shrink, and still win the game
  • There is no suicide unless you wait for board shrink

Questions:

  • Has this been made?
  • Config options as # of rounds, board size, how many rounds every shrink, etc... can be set up before the game. What values should I use?
  • Any considerations I should take?

PD: I have most of the controller done, I'll be uploading it soon. I'm still working on some basic graphic interface.

\$\endgroup\$
6
  • \$\begingroup\$ Why would anyone select bishop, rook or king if the queen can do more? \$\endgroup\$ Jul 18 at 7:49
  • \$\begingroup\$ @SuperStormer You would earn less points per turn using a queen instead of some other piece. The queen has a better attacking capabilities but her pasive income is low compared to other pieces \$\endgroup\$ Jul 18 at 13:24
  • \$\begingroup\$ What can I do with the money? \$\endgroup\$ Jul 21 at 13:12
  • \$\begingroup\$ @Iamkindofalanguagedev points is what defines the leadership, who is winning xD \$\endgroup\$ Jul 21 at 14:22
  • \$\begingroup\$ @LuisfelipeDejesusMunoz So if I get lots of money, it’s ok to die soon? \$\endgroup\$ Jul 21 at 14:42
  • \$\begingroup\$ @Iamkindofalanguagedev That could be a strategy, I just dont know how good it would be \$\endgroup\$ Jul 21 at 14:49
3
\$\begingroup\$

Is this set laminar?

\$\endgroup\$
1
  • \$\begingroup\$ Maybe add plain English explanations alongside the mathy-notation? \$\endgroup\$
    – noodle man
    Jul 30 at 12:12
3
\$\begingroup\$

Calculate the aspect ratio of the Nepal flag

This is the nepal flag.

Apove is the picture of the flag of the country Nepal. Pretty cool.

What's cooler, is the aspect ratio, which is defined under the constitution as:

Aspect ratio.

This is A230582.

Your task is to output at least the first 113 digits of the decimal expansion, in any format of your choosing.

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

Pennies to Dollars

Over on Puzzling, Hermant Agarwal proposes the following question:

In a certain country the following coins are in circulation: 1 cent, 2 cents, 5 cents, 10 cents, 20 cents, 50 cents, and 1 dollar. It is known that you can pay A cents with B coins. Prove that you can pay B dollars with A coins.

Let's help answer this! Spoilers for the answer to the puzzle below


The answer relies on the fact that you can replace 1 coin worth \$X\$ cents with \$X\$ coins worth 1 dollar. For example, in the puzzle posed in the question, we replace a 20¢ coin with 20 5¢ coins.

Given a list of cent coin values \$L\$, and a positive integer \$B\$, output a positive integer \$A\$ such that

  • There is a sublist of \$L\$ containing \$B\$ (not necessarily distinct) values that sum to \$A\$, and
  • there is a sublist of \$L\$ containing \$A\$ (not necessarily distinct) values that sum to \$100B\$

For example, take \$L = \{2, 5, 10\}\$ and \$B = 3\$. We can see that the sublist \$\{10, 10, 10\}\$ sums to \$A = 30\$, and the sublist consisting of \$30\$ \$10\$s sums to \$300 = 100B\$. However, while there exists a sublist that sums to \$A = 6\$ with \$B = 3\$ elements, there is no sublist with \$6\$ elements that sums to \$300\$ - the maximum being \$60\$.

Another example, take \$L = \{1, 2, 5, 10, 20, 50, 100\}\$ (i.e. the example in the question) and \$B = 2\$. We can make \$A = 25\$ cents with 2 coins (\$\{20, 5\}\$) and \$$2\$ with \$25\$ coins (15 \$10¢\$ and 10 \$5¢\$ coins). In this case, however, any value we choose for \$A\$ has a solution, so any positive integer is a valid output

Finally, take \$L = \{2, 5, 7\}\$ and \$B = 2\$. The possible values for \$A\$ (i.e. totals you can make with 2 coins) are \$4, 7, 9, 10, 12, 14\$. However, for each of these \$A\$ values, we can see that there are no sublists of \$L\$ with \$A\$ values that sum to 200: in fact, the largest sum we can get is \$98\$. You aren't expected to handle these inputs


The list \$L\$ will always be non-empty, and contain positive integers between \$1\$ and \$100\$ inclusive. You may assume that, for the provided \$L\$ and \$B\$, there exists at least one \$A\$ that satisfies the conditions, and you may output any such \$A\$.

You may input and output in any convenient manner. This is , so the shortest code in bytes for each language wins.


Test cases

Coming soon

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

Write a Tank AI

Preamble

This preamble will be removed in the real post.

I have created a platform to automatically run multi-language KotH. In this example, the framework will simulate an abstract battle of tanks on a grid. Each user's answer will control their tank.

The idea is that the competition will be open for a month -- after which the competition will be run offline and then the results will be appended to the Code Golf question.

I have written the proof-of-concept simulator in a way that makes it easy for people to add new competitions. It should be good enough for this first competition and then made more robust afterwards.

The title for the software is Harmagedon (which means Mount Magiddoh) because:

  1. it conveys the idea of Armageddon i.e. there is a high stakes battle.
  2. the mountain part gives a nod to classic King of the Hill type games.

I am interested in feedback on how the post can be worded more clearly and what information needs to be added.

Tank Battle

Write an AI to control a tank on a grid. Each player's tank is placed in a randomly, unique row and column. The number of the grid's rows and columns are each equal to the number of players.

The grid is a torus. In other words, things exiting the grid from the right-most column will appear on the left-most column (in the same row), things exiting from the upper-most row will appear on the bottom most row (in the same column), and visa-versa.

Tanks receive instructions based on the output of their code. Output is in the form of two letters and a new line.

All tanks act simultaneously in a round of decision-making called a tick.

Running code

Every tick, when the simulator needs a tank to make a decision, it runs the tank's code (passing the game state into the standard input). It then captures the standard output and performs that action (as long as it matches a valid instruction for moving or shooting).

There is a 3 second timeout for running code. Any code that takes longer to run will result in that tank not performing any action that tick.

Note: During a tick, all of the move actions will first resolve and then all of the shooting actions.

Format of Standard Input

The format of the game state will be as follows:

Game_State ::= YourUserID ';' GridWidth (';' Position)+

Position ::= TankUserID ',' XCoord ',' YCoord

As an example, if you are user 9999 on Code Golf Stack Exchange, and the following is the starting grid:

    Y
    ^
    |
    +--------+--------+--------+
    |        |        |        |
 2  |  [0]   |        |        |
    |        |        |        |
    +--------+--------+--------+
    |        |        |        |
 1  |        |        | [9999] |
    |        |        |        |
    +--------+--------+--------+
    |        |        |        |
 0  |        |[50000] |        |
    |        |        |        |
    +--------+--------+--------+-> X
        0        1        2

Then the input to your code will look like this for the 1st tick:

9999;3;0,0,2;9999,2,1;50000,1,0

Breaking it up one chunk at a time:

  • 9999: You are tank 9999.
  • 3: The grid is 3 squares wide and 3 squares tall.
  • 0,0,2: The tank controlled by user 0 is at co-ordinate (0, 2)
  • 9999,2,1: The tank controlled by user 9999 is at co-ordinate (2, 1)
  • 50000,1,0: The tank controlled by user 50000 is at co-ordinate (1, 0)

Format of code output

Your output can be either a moving or shooting instruction.

Moving Instruction

  • mu: Move one tile up
  • md: Move one tile down
  • ml: Move one tile left
  • mr: Move one tile right

If more than one tank attempts to move to the same square in a tick, only one will move there and the others will remain where they were. No grantees are made about which ones stay behind (i.e. in theory non-deterministic but potentially deterministic in implementation).

Shooting Instruction

  • su: Shoot upward
  • sd: Shoot downward
  • sl: Shoot left
  • sr: Shoot right

When a tank shoots in a direction, the projectile will instantly traverse from the tank in that direction until it reaches another tank or back to its starting position. If it reaches another tank (other than the one who fired it), it will destroy that tank and remove it from the grid. If no other tanks are encountered along its path, nothing happens.

Winning

Players are ordered by the amount of time that they last on the grid. The winner is the player who doesn't die, the second placed players are those whose tanks were destroyed last, the third place are those whose tanks were destroyed second-last and so on.

Ties for places happen when more than one tank is destroyed in a tick.

Submitting

Code should be submitted as an answer on Code Golf.

The answer needs to have a very specific format so that the simulator can parse it.

The format can be described as follows.

The answer must contain at least two code blocks. The first code block should be the name of the language being used and the second should be the code being submitted.

The language can be any listed in this JSON object. Use one of the object keys to refer to which language you will use.

Note: There is a hard 1024 character limit for submissions.

Example

# This is an example submission

All of this text before the next code block will be ignored:

```
python3
```

The above code block will be parsed to find out which language to run the code in (because it's the first code block); this text, however, will be ignored because it is not a code block.

The next code block will be parsed to get the code that will control this answer's tank. Normally one could add extra information here to elaborate on the solution.

```
import random  
stdin = input()  # Get the world state
                               
# Parse the world state
my_id, width, *tanks = stdin.split(';') 
tanks = [t.split(',') for t in tanks]          
                                               
# Get my position
my_x, my_y = next(t for t in tanks if t[0] == my_id)[1:]  
        
# Get a list of other tanks that are in-line with me
inline = [t for t in tanks if t[0] != my_id and (t[1] == my_x or t[2] == my_y)]  

if inline:      
    # If one exists,
    other_tank = inline[0]
    # then shoot on that axis.
    if other_tank[1] == my_x:
        print('sl')
    else:       
        print('su')
else:           
    # otherwise, move in a random direction
    print(random.choice(['mu', 'md', 'ml', 'mr']))
```

Everything after this previous code block will be ignored (including other `code blocks`).


\$\endgroup\$
9
  • 1
    \$\begingroup\$ Everything else aside for now: Do you need a separate code block to specify the language? You can indicate the language on the same line as the opening backticks. \$\endgroup\$
    – Bbrk24
    Aug 3 at 17:08
  • 2
    \$\begingroup\$ Looks interesting, although I don't understand yet how it differs from king-of-the-hill challenges, going to have to read it a few more times. I see you're allowing any language on TIO. Does that mean they'll all be run by making requests to TIO? Or are you planning to install languages onto your computer as necessary? \$\endgroup\$
    – user
    Aug 3 at 17:08
  • \$\begingroup\$ My bad, I see now you're making requests to TIO. Any idea if you'd get rate-limited or something? \$\endgroup\$
    – user
    Aug 3 at 17:11
  • 1
    \$\begingroup\$ @user Perhaps its not too different to KotH. It it could be a new way to do it. Since you can run more languages than the average KotH challenge and there is less manual work. I don't particularly mind if a new challenge type is created or not. As for the TIO question. I asked the maintainer in 2021 if it's fine (back when I first had the idea) and they said that they didn't currently have plans to rate limit. Either way, when the competition is actually run, it can be done in stages if needed. \$\endgroup\$
    – NeRoboto
    Aug 3 at 17:15
  • \$\begingroup\$ @Bbrk24 Not really. It seemed easier to explain the code blocks like this conceptually. It can always change. \$\endgroup\$
    – NeRoboto
    Aug 3 at 17:18
  • 1
    \$\begingroup\$ Can submissions store state between ticks? When I first read this I thought the programs would be run once with stdin being blocked between ticks, but now that I know it's being run on TIO, I'm not sure that's possible. \$\endgroup\$
    – Bbrk24
    Aug 3 at 17:54
  • \$\begingroup\$ This isn't a new challenge type at all, it 100% fits within king-of-the-hill \$\endgroup\$ Aug 3 at 23:16
  • \$\begingroup\$ @RydwolfPrograms Fair enough. I have updated the question regarding that. \$\endgroup\$
    – NeRoboto
    Aug 4 at 18:13
  • \$\begingroup\$ @Bbrk24 Code is run statelessly. Every time someone's code is run, the world state is passed in as input. Can you suggest a way to make it clearer? \$\endgroup\$
    – NeRoboto
    Aug 4 at 18:18
3
\$\begingroup\$

Braille Base64

Make a one-to-one map from the base64 character table(0-9a-zA-Z+/) to Braille(U+2800-U+283F).

These characters are fixed map for compatibility. For other characters you can choose any map as long as there's no collision.

⠁ a     ⠃ b     ⠉ c     ⠙ d     ⠑ e     ⠋ f 
⠛ g     ⠓ h     ⠊ i     ⠚ j     ⠅ k     ⠇ l
⠍ m     ⠝ n     ⠕ o     ⠏ p     ⠟ q     ⠗ r
⠎ s     ⠞ t     ⠥ u     ⠧ v     ⠺ w     ⠭ x
⠽ y     ⠵ z     ⠴ 0     ⠂ 1     ⠆ 2     ⠒ 3
⠲ 4     ⠢ 5     ⠖ 6     ⠶ 7     ⠦ 8     ⠔ 9

Shortest code wins.


  • Braille ASCII defines uppercase letters while Computer Braille Code defines lowercase ones. Should I allow only one or both?
  • Should I also fix / == as the several standards all claim so?
\$\endgroup\$
3
\$\begingroup\$

Hashers and Crashers

\$\endgroup\$
14
  • \$\begingroup\$ You might want to add an example cop and crack. \$\endgroup\$
    – noodle man
    Jul 20 at 17:42
  • \$\begingroup\$ Related \$\endgroup\$
    – Bbrk24
    Jul 20 at 17:44
  • \$\begingroup\$ @noodleman added \$\endgroup\$ Jul 20 at 17:59
  • \$\begingroup\$ @Bbrk24 it seems exactly the same except of the scoring system, is that enough to make it not a duplicate? Edit: I just realized the other challenge hashes numbers instead of strings. \$\endgroup\$ Jul 20 at 17:59
  • \$\begingroup\$ How does this work when there is more than one collision? For (a poor) example, if my hash last_char(input) and no one cracks it I might say that the collision was "longstringyousee" and "bigscore" giving me a score of 24, but clearly "a" and "ba" are also a collision. One could imagine more complex (that actually have a chance at not being cracked) hashes that allow arbitrarily sized collisions. \$\endgroup\$ Jul 21 at 16:02
  • \$\begingroup\$ @CursorCoercer for cops the shorter collision is better. \$\endgroup\$ Jul 21 at 16:06
  • \$\begingroup\$ Ah right, I got mixed up in my train of thought, I was concerned about the robber scoring. It probably won't be much of a problem anyways, but just something to keep in mind \$\endgroup\$ Jul 21 at 16:32
  • \$\begingroup\$ What if a cop just copy-pastes a SHA256 implementation? lol \$\endgroup\$ Jul 24 at 15:47
  • 1
    \$\begingroup\$ @ShiranYuan They would have to know a collision in the SHA256 hash system for the answer to be valid, so the US government would be very interested. \$\endgroup\$ Jul 24 at 15:52
  • \$\begingroup\$ @Iamkindofalanguagedev Ok so maybe sending the challenge out would help CGCC get government attention and thus more publicity :P \$\endgroup\$ Jul 24 at 16:04
  • \$\begingroup\$ @ShiranYuan huh? \$\endgroup\$ Jul 24 at 16:05
  • \$\begingroup\$ @Iamkindofalanguagedev just joking lol \$\endgroup\$ Jul 24 at 16:06
  • \$\begingroup\$ @CursorCoercer Standard CnR rules are that unintended cracks are still valid, so if I find a shorter crack than the cop intended, scoring works the same as if that was the intended solution. \$\endgroup\$ Jul 25 at 2:54
  • \$\begingroup\$ @RydwolfPrograms yes, that’s true. \$\endgroup\$ Jul 25 at 6:47
3
\$\begingroup\$

Count N-Rich Permutations of an Integer Sequence

Given a sequence of integers with length \$L\$ and an integer \$1 \le N \le L\$, an "\$N\$-rich" permutation is one whose the longest strictly increasing subsequence has length exactly \$N\$.

For example, let our sequence be [0, 1, 2, 3]. There is exactly one \$1\$-rich permutation, given by [3, 2, 1, 0]. By contrast, there are sixteen \$2\$-rich permutations:

[0, 2, 1, 3] [0, 3, 1, 2] [0, 3, 2, 1]
[1, 0, 3, 2] [1, 2, 0, 3] [1, 3, 0, 2] [1, 3, 2, 0]
[2, 0, 3, 1] [2, 1, 0, 3] [2, 1, 3, 0] [2, 3, 0, 1] [2, 3, 1, 0]
[3, 0, 2, 1] [3, 1, 0, 2] [3, 1, 2, 0] [3, 2, 0, 1]

Note that [0, 1, 3, 2] is \$3\$-rich and NOT \$2\$-rich, because even though it contains a strictly increasing subsequence of length 2, it also contains a longer strictly increasing subsequence.

The Challenge

Your challenge is to write a function which takes in an integer sequence S with some length \$L\$, and an integer \$1 \le N \le L\$, and returns the number of N-rich permutations of S.

This is code golf, so the shortest valid answer wins.

Test cases

Each row is a sequence along with the expected output for all possible values of L. For example, the first row says that if your function is called f, then f([1, 2, 3, 4, 5], 3) = 41

[1, 2, 3, 4, 5] => 1, 69, 41, 8, 1
[1, 2, 2, 3, 3, 4, 5] => 4, 2612, 2064, 336, 24, 0, 0
[1, 1, 1, 1, 1, 1, 1] => 5040, 0, 0, 0, 0, 0, 0
[1, 2, 3, 1, 2, 3, 4] => 8, 2976, 1864, 192, 0, 0, 0
\$\endgroup\$
3
\$\begingroup\$

Could it be a possible chess move?

Backstory

Professor Chesster has a library of chess puzzles with solutions, but a meteor has struck (not real, I promise) and now their hard drive may be corrupted! Luckily, Professor Chesster's puzzle FENs are stored securely, but the solutions to those puzzles have all been jumbled up and could be as ridiculous as gxm9=L or even axc3! Professer Chesster needs a quick and simple scan to check if the solutions to their puzzles are valid.

Luckily, most of the meteor is not radioactive (no ) but because Professor Chesster's hard drive is now a literal potato, they need the code to be as short as possible () or it might overheat!

Stop waffling pls and show me the challenge!!!

OK, fine. Here:

Check if a move inputted with algebraic notation could be valid. Return a truthy value if it is, and a falsy value otherwise.

List of all moves that are valid

Na1, Na2, ..., Nh8
Ka1, ...
... [all other pieces]
Nxa1, Nxa2, ... [captures]
Nba1, ... [specify row]
N2a1, ... [specify col]
Nb3a1, ... [row & col]
Nbxa1, N2xa1, Nb3xa1, ...
(NOT Kab3 as there's only one king)
O-O (or 0-0??? META - WHAT DO I DO)
O-O-O (or 0-0-0??? META - THIS TOO)
axb2 to axb7
bxc2 to bxc7
...
gxh2 to gxh7
then bxa1 to bxa7 ... hxg7
Then promotions (a1=Q, a1=R, a1=B, a1=N)
b1=QRBN, c1=QRBN, ..., h1=QRBN
a8=QRBN, ...
axb1=QRBN,bxc1=QRBN, .......
[other moves I may have missed]

Scoring

Again, Professor Chesster's hard drive is such a potato that they require it to be golfed as much as possible. (this is )

META: Mandatory duplicate check

Not a duplicate of Is it a valid chess move? as that asks about a specific position.

Not a duplicate of Is it a plausible chess move? as that doesn't include piece information and a few other things that will be mentioned below

Sandbox/Meta stuff

  • Specifications
    • Do I include...
      • Check (move+)?
      • Double check (move++)?
      • Checkmate (move#)?
    • Did I miss any other chess moves?
  • Funny enough backstory?
\$\endgroup\$
9
  • \$\begingroup\$ Are we allowed to move our king into check? \$\endgroup\$ Aug 20 at 9:19
  • \$\begingroup\$ related challenges: next move in restricted set of moves, verify next move \$\endgroup\$
    – bsoelch
    Aug 20 at 13:08
  • \$\begingroup\$ @bsoelch If I'm reading it correctly it's about outputting all possible moves from any position. So something like axc6 would not be included in the output because no matter what the position is, a pawn can't take a piece two files away from it. I could be misinterpreting the question though, it certainly isn't too clear what is meant by "all valid chess moves." \$\endgroup\$
    – Aiden Chow
    Aug 20 at 18:50
  • \$\begingroup\$ It's all moves that could ever be valid in any position. Editing that in now \$\endgroup\$
    – W D
    Aug 21 at 9:21
  • \$\begingroup\$ Considering that the order of possible moves is not fixed I would not mark it as sequence \$\endgroup\$
    – bsoelch
    Aug 21 at 9:28
  • \$\begingroup\$ You should probably explain/link to the chess notation you are using \$\endgroup\$
    – bsoelch
    Aug 21 at 9:30
  • \$\begingroup\$ @TheEmptyStringPhotographer doesn't matter as it's over all possible boards || @bsoelch thanks for related challenges; not marked sequence anymore; linked to algebraic notation || @AidenChow yes - see the updated question \$\endgroup\$
    – W D
    Aug 21 at 9:35
  • \$\begingroup\$ IMO you would need to specify how to differentiate a a good move from a brilliant move from a normal move (Sotckfish uses an AI and an specific scoring system to determine the quality of a move) \$\endgroup\$ Aug 21 at 14:29
  • \$\begingroup\$ You don't need to differentiate them; this program has no input. It generates ALL possible moves from ALL possible boards \$\endgroup\$
    – W D
    Aug 22 at 8:02
3
\$\begingroup\$

Decode Chess Move

\$\endgroup\$
2
  • \$\begingroup\$ Apart from exluding moves like Nae5 (which I assume you did intentionally - "Knight (b) to a3" or "Knight(b) to a3" seem like good options if you were to include it) this looks good. May want to specify how to handle O-O-O (using the letter o and not the number 0) \$\endgroup\$
    – W D
    Aug 23 at 9:43
  • 1
    \$\begingroup\$ @WD for ambiguous moves (such as Nae5 even tho that is not a valid move) input will specify the starting square and the target square. For example, imagine there is a knight on d3 and another one on f3, input will specify the movement of the d3 knight as Nd3e5 \$\endgroup\$ Aug 23 at 13:32
3
\$\begingroup\$

Erasure Poetry

Given two strings of digits \$A\$ and \$B\$, count the minimum number of digits that need to be removed from \$A\$ to make it a substring of \$B\$. (META: i am still brainstorming what this actual challenge part should be, though i think this challenge might be good).

However, you will not be "writing" programs/functions to solve this challenge, so much as you will be finding them in the previous answer.

Challenge specification

(spec in progress)

Take two strings of digits \$A\$ and \$B\$. You can assume these strings will both be nonzero in length and contain any amount of the following characters in any order: 0123456789. Return the number of digits needed to be removed from \$A\$ in order to make it be a substring of \$B\$.

Worked out examples:

A: "3"
B: "123"
Output: 0
Explanation: "3" is already a substring of "123", so 0 characters need to be removed from it

A: "1322"
B: "12345"
Output: 2
Explanation: "12" is the biggest potential substring of B that could be made from A, and it requires removing the 3 and one of the 2s

A: "12345"
B: "123"
Output: 2
Explanation: "123" is the biggest potential substring of B that could be made from A, and it requires removing the 4 and 5

A: "12345"
B: "67890"
Output: 5
Explanation: None of A exists in B, so "" (the empty string) is the biggest potential substring of B that could be made from A, and it requires removing all 5 of the digits

Scoring specification

Contrary to what I said in the intro, you will technically be writing a program or function to solve this challenge. However, you will not be scored directly on your code length.

Included with your answer will be a list of characters you will remove from the previous answer's code such that it becomes your answer's code. If this is not possible with removals alone, you may also add characters to the previous answer, but this will come with a score penalty.

In particular: Your score is the number of characters you need to add to some substring of the previous answer's code in order to make it your answer's code. Lowest score wins.

The first answer to base your score off of will be provided at the bottom of this post.

Answer chaining rules

Importantly, you may not answer the challenge in a language that has already been used unless your answer has a lower score. Flags and version numbers do not differentiate languages in this challenge.

(more clarifications and guidelines)

Answer chaining example

6. MyOwnLanguage, +3 characters

previous answer with removed characters replaced with *:

do ****thing *o**

with my added characters becomes:

do thing now!

Try It Online

7. HQ9+2, +0 characters

previous answer with removed characters replaced with *:

do*thing****!

with my (0) added characters becomes:

dothing!

Try It Online

Starting answer

0. JavaScript (V8), +361 characters

f = (a, b) => {
  const isSubstring = (c, d) => {
    if(!c){
      return true
    }else{
      return RegExp(`${c}`).test(d)
    }
  }
  if(isSubstring(a, b)){
    return 0
  }else{
    a = [...Array(a.length).keys()]
        .map(w => a.slice(0, w)
                + a.slice(w + 1)
            )
    a = a.map(w => f(w,b))
    return 1 + Math.min(...a)
  }
}

Try it online!

meta

work in progresss, but feel free to suggest anything you think i might be missing, even if it seems obvious. Still working out the formatting for everything to look nice :-)

\$\endgroup\$
3
  • 2
    \$\begingroup\$ How does this work with SBCS? \$\endgroup\$ Sep 5, 2022 at 17:37
  • \$\begingroup\$ @CommandMaster not sure yet, im thinking about just making it based on the byte value itself. seems fair since most languages use just printable ascii, and from what ive seen, most SCBSes have their printable ascii on the same bytes as regular printable ascii. I might require / ask that languages with alternate encodings provide a hex dump. Does that sound reasonable? \$\endgroup\$ Sep 5, 2022 at 18:09
  • \$\begingroup\$ @CommandMaster actually I changed my mind, im making it char based so its just gonna be easier to work with in general :P I can't imagine there will be much cheesing in the way of "my language has one million different encodings for these commands so i can do every solution in 0", plus you can only use the language again if you can actually lower its score :P this should be ok :-) \$\endgroup\$ Oct 17, 2022 at 13:45
3
\$\begingroup\$

A robber flipped some bits. This is what happened to the cop's code.

Objective

Cops shall pose a code that outputs a truthy or falsy value deterministically, depending on the input. The output must be truthy on some inputs and falsy on some other inputs.

Flipping some bits in the code shall result in negating the output for every input. Robbers shall find such bits.

Winning criterion

For cops, the submission whose the cardinality of all valid inputs is the biggest shall win. The shortness of the code is a tiebreaker. In other words, this is primarily and secondarily . (Note that there may be infinitely many valid inputs, and its cardinality cannot exceed aleph-naught.)

For robbers, the submission whose percentage of the flipped bits is the closest to 50% shall win. The number of the flipped bits is a tiebreaker. So this is primarily and secondarily .

Rule

Cops must specify what the valid inputs are.

\$\endgroup\$
6
  • \$\begingroup\$ I think you should elaborate the 'cardinality of valid inputs' scoring criterion better. In Husk, a cop answer could be = increment. All integers are valid inputs (so they are infinite), and only -1 results in falsy output (zero). I don't think there's a single-byte Husk command that would make -1 truthy and everything else falsy, so it seems uncrackable. \$\endgroup\$ Sep 1 at 12:25
  • 1
    \$\begingroup\$ @DominicvanEssen they way I understood the second sentence of the objective, there has to be a way to crack the program for the submission to be valid \$\endgroup\$
    – bsoelch
    Sep 3 at 8:31
  • 1
    \$\begingroup\$ @bsoelch - ah, that makes sense… \$\endgroup\$ Sep 3 at 9:30
  • \$\begingroup\$ Why is higher cardinality better? I would think it would be the opposite. \$\endgroup\$
    – Wheat Wizard Mod
    Sep 3 at 18:56
  • \$\begingroup\$ @WheatWizard If smaller cardinality were better, cop submissions might take no input, which gives cardinality 1. That's too trivial. \$\endgroup\$ Sep 4 at 1:17
  • \$\begingroup\$ Isn't trivial better? It makes it harder to disguise things. But if trivial is bad what's to prevent someone from "taking" the input and ignoring it. That makes no real difference to the cop but makes their score in that infinity. \$\endgroup\$
    – Wheat Wizard Mod
    Sep 4 at 2:10
3
\$\begingroup\$

What's my score?

The question score on Stack Exchange is the total number of upvotes minus the total number of downvotes a question receives. However, the reputation gained/lost for every upvote/downvote is different (10/-2 on Code Golf).

Given the total reputation and the reputation gained/lost on votes, list out all possible scores the question could have.

Rules

  • The total reputation, the reputation gained by an upvote and reputation lost by a downvote must be integers
  • The upvote-reputation will be positive and the downvote-reputation will be negative
  • You can output the possible question scores as a (possibly infinite) list or print each one individually.
  • This is , so the shortest answer wins

Examples

[total reputation, upvote-reputation, downvote-reputation] -> [question scores]

[28, 10, -2]  -> [2, -2, -6, -10, ...]
[34, 10, -2]  -> [1, -3, -7, -11, ...]
[17, 10, -2]  -> []
[11, 7, -5]   -> [1, -1, -3, -5, ...]
[82, 31, -11] -> [2, -18, -38, -58, ...]
[15, 5, -10]  -> [3, 4, 5, 6, ...]
\$\endgroup\$
3
\$\begingroup\$

Sum of consecutive nth powers

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

How many ways to cut a number into an equation?

\$\endgroup\$
1
24 25
26
27 28
152

You must log in to answer this question.

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