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

4670 Answers 4670

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

Shortest distinguishable slice (posted)

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

How super is this prime?

Posted here

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

The Jaccard Index

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

Calculate Bloons RBE Equivalent

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

International Resource Trading KOTH

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

Goal of the game

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

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

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

The game loop

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

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

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

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

There are 3 rounds of trading for every production phase.

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

Example bot

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

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

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

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

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

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

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

Extra Rules

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

Add two real numbers ... probably

\$\endgroup\$
1
  • \$\begingroup\$ @AnttiP The number of inputs which require reading an infinite number of bits like this has measure zero. The solution here is to simply loop forever in the tough cases. \$\endgroup\$
    – Wheat Wizard Mod
    Feb 9, 2023 at 12:42
3
\$\begingroup\$

Complex remainder

Complex remainder can be defined in a similar way to real remainder as \$ y - x \lfloor \frac y x \rfloor \$. However this depends on a suitable complex floor function. There are a number of ways of defining a complex floor function (for at least one of which there has been a previous challenge), but for this challenge I will relax the requirements to the following:

  • Every complex number has exactly one floor which is a Gaussian integer.
  • \$ \lfloor z \rfloor = \lfloor \Re ( z ) \rfloor \$ if \$ \Im (z) = 0 \$.
  • \$ \lfloor z + n \rfloor = \lfloor z \rfloor + n \$ where \$ n \$ is a Gaussian integer.

Note that this implies that \$ \lfloor n \rfloor = n \$ for every Gaussian integer \$ n \$.

Please write a program or function that will perform complex remainder using a compatible definition.

Even if your language supports complex numbers you can choose to input them as separate real and imaginary parts. You can also choose to support only Gaussian integers as inputs and outputs.

If your language has suitable builtins for remainder or floor then you can earn extra brownie points by providing an additional solution that doesn't use them.

This is , so the shortest program that breaks no standard loopholes wins!

\$\endgroup\$
8
  • 1
    \$\begingroup\$ Maybe some test cases? \$\endgroup\$
    – Adám
    May 8, 2023 at 13:27
  • \$\begingroup\$ How about negative numbers? There are, rather famously, multiple ways to give a sign to a remainder involving negative numbers. \$\endgroup\$
    – Adám
    May 8, 2023 at 13:28
  • \$\begingroup\$ @Adám I didn't want to provide test cases as they would assume a certain complex floor function. Also, the use of floor makes the result consistent for negative numbers (i.e. it's like Pascal's mod rather than rem). \$\endgroup\$
    – Neil
    May 8, 2023 at 14:06
  • \$\begingroup\$ How do we demonstrate correctness of a submission? \$\endgroup\$
    – Adám
    May 9, 2023 at 6:36
  • \$\begingroup\$ @Adám Probably showing that (y-y%x)/x is a Gaussian integer and (y+x)%x and (y+ix)%x both equal y%x for multple random test cases would be enough. \$\endgroup\$
    – Neil
    May 9, 2023 at 7:44
  • 1
    \$\begingroup\$ You should probably explicitly say a Gaussian integer is a complex number whose real and imaginary parts are integers to avoid an inevitable comment about it. Similarly, adding your response to Adám's question will probably save you some time. \$\endgroup\$ May 9, 2023 at 21:34
  • \$\begingroup\$ Will there ever be some different floor functions \$f_1\$ and \$f_2\$ both satisfy the requirement but have at least one \$x\in\mathbb{C}\$ that \$f_1(x)\ne f_2(x)\$? What if we change the second requirement into simply \$\lfloor 0\rfloor = 0\$? \$\endgroup\$
    – tsh
    May 11, 2023 at 5:49
  • \$\begingroup\$ @tsh Yes it's quite easy to have different satisfactory floor functions. I do want real modulus to continue to work as expected though. \$\endgroup\$
    – Neil
    May 11, 2023 at 7:00
3
\$\begingroup\$

Given an integer, output an if its English name begins with a vowel (namely it is positive, and its first digit is 8 or it has the form 11 followed by a multiple of 3 digits), and otherwise output a. This is code-golf, so the shortest code in bytes wins.

Test cases

10: a
0: a
8234987: an
110: a
11: an
11234: an
-8: a
-11: a
8: an

Note for the sandbox viewers: in the related question English An or A? the input is an arbitrary word as a string, and in the related question An A , or An An? the article a/an must be placed inside a sentence, properly capitalized. The present question has a more minimalistic input and output.

\$\endgroup\$
3
  • \$\begingroup\$ I feel like this is just arbitrarily adding a change to this challenge, as the answers would be pretty much the same except with the added conversion from integer to cardinal \$\endgroup\$
    – emirps
    May 11, 2023 at 13:10
  • 3
    \$\begingroup\$ @emirps A solution to this could easily shortcut that using the pattern noted in the question body. Although a language with appropriate builtins might find the most direct approach shortest, I'd almost hesitate to call the challenges related at all. In any case, I'd recommend relaxing the output to make this a decision-problem, and possibly also excluding negative numbers from the input. Also, perhaps make it explicit that we don't have to handle octillions :P \$\endgroup\$ May 11, 2023 at 13:47
  • \$\begingroup\$ Good point about the word octillion, although that cannot come up as the first word in the number's name, right? \$\endgroup\$ May 11, 2023 at 23:03
3
\$\begingroup\$

Turn strings into hexagonal spirals!

\$\endgroup\$
3
  • 1
    \$\begingroup\$ Should it be hexagon or hexagonal spirals? Confused as an ESL, both sound correct to me. Perhaps they are? \$\endgroup\$
    – pan
    May 11, 2023 at 21:37
  • 1
    \$\begingroup\$ Since you mentioned "You may start the spiral at any of the 6 points you like.", does this mean this would be a valid output for the first example as well? All your test cases and examples start at the top-left corner. As for the question in your comment, I'm not a native English speaker, but I'm pretty sure both hexagon spirals and hexagonal spirals are correct, as well as spirals of hexagons. I see all three used when I randomly google around. \$\endgroup\$ May 15, 2023 at 10:03
  • \$\begingroup\$ @KevinCruijssen Yeah, it would be valid output. I will include it as an example, thanks! I think I will change the title to hexagonal spirals since that's how I'd have said it in my native language, thank you for clarifying. \$\endgroup\$
    – pan
    May 15, 2023 at 10:30
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, 2023 at 13:27
  • \$\begingroup\$ @RubenVerg just thought I’d use that notation. I don’t think it matters. \$\endgroup\$ May 26, 2023 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, 2023 at 13:38
  • \$\begingroup\$ @RubenVerg fixed \$\endgroup\$ May 26, 2023 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, 2023 at 17:01
  • \$\begingroup\$ Can we get some test cases please? \$\endgroup\$
    – The Thonnu
    May 28, 2023 at 13:46
  • 1
    \$\begingroup\$ @TheThonnu test cases have been made. \$\endgroup\$ May 28, 2023 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, 2023 at 12:29
  • \$\begingroup\$ @Adám Not really… there are methods for doing this. \$\endgroup\$ May 30, 2023 at 12:30
  • 1
    \$\begingroup\$ @Hippopotomonstrosesquipedalian I can't imagine solving this without any builtins. \$\endgroup\$
    – Adám
    May 30, 2023 at 12:31
  • \$\begingroup\$ @Adám just needs a for loop and the 4 basic arithmetic operations \$\endgroup\$ May 30, 2023 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, 2023 at 12:45
  • \$\begingroup\$ Is there any reason for the increased accuracy requirement between 1 and 10? \$\endgroup\$ May 30, 2023 at 19:41
  • \$\begingroup\$ @Hippopotomonstrosesquipedalian most approximations are more accurate around that range \$\endgroup\$
    – mousetail
    May 30, 2023 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, 2023 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, 2023 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, 2023 at 14:20
  • \$\begingroup\$ It might be shorter to just output the LDA for every number in sequence infinitely \$\endgroup\$
    – mousetail
    Jun 13, 2023 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, 2023 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, 2023 at 14:30
  • \$\begingroup\$ @mousetail Edited. Do you have any more suggestions? \$\endgroup\$ Jun 13, 2023 at 14:33
  • \$\begingroup\$ By the way, welcome to Code Golf, and thanks for using the Sandbox! \$\endgroup\$
    – The Thonnu
    Jun 14, 2023 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, 2023 at 4:33
  • \$\begingroup\$ I agree, and plan to implement the wording of "anything other than a non-negative integer". \$\endgroup\$ Jun 15, 2023 at 6:40
  • \$\begingroup\$ Edit successful. Do you have any more suggestions? \$\endgroup\$ Jun 15, 2023 at 6:42
  • \$\begingroup\$ Alright. If there is none, I shall post it on the site. \$\endgroup\$ Jun 15, 2023 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, 2023 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, 2023 at 18:18
  • \$\begingroup\$ @RubenVerg yes, that's fine \$\endgroup\$
    – bigyihsuan
    Jul 13, 2023 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, 2023 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, 2023 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, 2023 at 16:34
  • \$\begingroup\$ @RydwolfPrograms Well, good luck establishing the protocol ;-) \$\endgroup\$ Jul 24, 2023 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, 2023 at 2:48
  • \$\begingroup\$ @RydwolfPrograms Well what if someone submits code in esoteric languages that have no "canon" interpreter, like Brainfuck? \$\endgroup\$ Jul 25, 2023 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, 2023 at 14:14
  • \$\begingroup\$ @RydwolfPrograms Nice idea! I think it's pretty good to go ;-) \$\endgroup\$ Jul 26, 2023 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, 2023 at 3:07
  • \$\begingroup\$ @SuperStormer Noted, title changed. Also, sure - within reason. Adding that now. \$\endgroup\$ Jul 23, 2023 at 9:39
  • \$\begingroup\$ Am I allowed to take a list of characters with special characters as a singleton list? \$\endgroup\$ Jul 30, 2023 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, 2023 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, 2023 at 13:49
  • \$\begingroup\$ It won’t handle unescaped backslashes or newlines in the input. \$\endgroup\$
    – Bbrk24
    Jul 1, 2023 at 13:50
  • \$\begingroup\$ @Bbrk24 fixed now \$\endgroup\$
    – Dadsdy
    Jul 1, 2023 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, 2023 at 14:22
  • \$\begingroup\$ @Bbrk24 should be fixed now \$\endgroup\$
    – Dadsdy
    Jul 1, 2023 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, 2023 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, 2023 at 12:32
  • \$\begingroup\$ @Adám No, I could use help how to specify that clearly though \$\endgroup\$
    – mousetail
    Jul 18, 2023 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, 2023 at 1:13
  • \$\begingroup\$ @Bbrk24 I guess they meant ps \$\endgroup\$
    – c--
    Jul 26, 2023 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, 2023 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, 2023 at 12:09
  • \$\begingroup\$ @noodleman There are many possible solutions though \$\endgroup\$
    – mousetail
    Jul 30, 2023 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, 2023 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, 2023 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, 2023 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, 2023 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, 2023 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, 2023 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, 2023 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, 2023 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, 2023 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, 2023 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, 2023 at 13:24
  • \$\begingroup\$ What can I do with the money? \$\endgroup\$ Jul 21, 2023 at 13:12
  • \$\begingroup\$ @Iamkindofalanguagedev points is what defines the leadership, who is winning xD \$\endgroup\$ Jul 21, 2023 at 14:22
  • \$\begingroup\$ @LuisfelipeDejesusMunoz So if I get lots of money, it’s ok to die soon? \$\endgroup\$ Jul 21, 2023 at 14:42
  • \$\begingroup\$ @Iamkindofalanguagedev That could be a strategy, I just dont know how good it would be \$\endgroup\$ Jul 21, 2023 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, 2023 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, 2023 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, 2023 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, 2023 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, 2023 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, 2023 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, 2023 at 17:54
  • \$\begingroup\$ This isn't a new challenge type at all, it 100% fits within king-of-the-hill \$\endgroup\$ Aug 3, 2023 at 23:16
  • \$\begingroup\$ @RydwolfPrograms Fair enough. I have updated the question regarding that. \$\endgroup\$
    – NeRoboto
    Aug 4, 2023 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, 2023 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\$
1
24 25
26
27 28
156

You must log in to answer this question.

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