577
\$\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\$
2
  • \$\begingroup\$ What if I posted on the sandbox a long time ago and get no response? \$\endgroup\$
    – None1
    Commented May 15 at 14:05
  • \$\begingroup\$ @None1 If you don't get feedback for a while you can ask in the nineteenth byte \$\endgroup\$ Commented May 29 at 13:27

4831 Answers 4831

1
17 18
19
20 21
162
3
\$\begingroup\$

Number rewinder

Inspired by this SO question and little bit expanded.

Your task is to rotate left a given integer by one digit in a given base and return integer (move the MSD to the LSD position).

Input: Two integers Number > Base > 1
Output: Result

Test cases:

Number Base  Result  String representations
61453   10    14536  61453 -> 14536
61453   16      223  F00D -> DF (00DF)
61453    8   229481  170015 -> 700151
60429   16    49374  EC0D -> C0DE
62977   16    24607  F601 -> 601F

This is Code-golf, standard loopholes are forbidden and shortest answer wins.

\$\endgroup\$
5
  • 3
    \$\begingroup\$ I don't think your restriction about strings is going to work out well, there's not really a way to verify strings aren't being used. In any case, string rotation isn't that much different from the arithmetic required to do this operation. Personally, I'd recommend just allowing them. Thanks for using the sandbox! \$\endgroup\$ Commented Feb 5, 2018 at 22:09
  • \$\begingroup\$ (i.e., we don't like do X without Y or unobservable behavior) \$\endgroup\$
    – user202729
    Commented Feb 6, 2018 at 5:45
  • \$\begingroup\$ @FryAmTheEggman If there isn't some ToString-like function that opperates on any base using strings may be more difficult than dealing with it numerically. \$\endgroup\$
    – Crowley
    Commented Feb 6, 2018 at 8:12
  • 3
    \$\begingroup\$ I've never heard "rewind" used with this meaning before. I would call that operation "rotation left". \$\endgroup\$ Commented Feb 6, 2018 at 11:09
  • \$\begingroup\$ @PeterTaylor Thanks for suggestion. I've updated bounds for the inputs to avoid rotating 1 digit "number" \$\endgroup\$
    – Crowley
    Commented Feb 6, 2018 at 16:04
3
\$\begingroup\$

The Programming Language Quiz, Mark II - Cops

\$\endgroup\$
8
  • \$\begingroup\$ I would say posting the challenge separately for cops and for robbers with cross-referencing links will be better, because posting robbers' answers to the cops' thread is a bit obfuscating I think, and it seems to be the general method to post a C&R. \$\endgroup\$ Commented Dec 14, 2017 at 0:56
  • 5
    \$\begingroup\$ For the languages on Try it Online!, what's to stop me from trying to run a cops submission on every language there? Doesn't that put all those languages at a disadvantage? \$\endgroup\$
    – KSmarts
    Commented Dec 14, 2017 at 18:46
  • 1
    \$\begingroup\$ Same concern as @KSmarts. With the C&R challenges where it is instead the code is hidden it's hard to crack answers because there are a large amount of possible programs they could have written (naively) but there are a relatively small number of languages so people could just try them all. I feel like there could be some added rules to get around this but I don't know what they'd be \$\endgroup\$
    – dylnan
    Commented Dec 15, 2017 at 1:17
  • \$\begingroup\$ So basically it is possible but impractical to try all of the languages on TIO. \$\endgroup\$
    – user202729
    Commented Dec 15, 2017 at 11:21
  • \$\begingroup\$ @KSmarts Good point. As DLosc pointed out, changing the time restriction to, say, 5 minutes would most likely handle it. \$\endgroup\$ Commented Dec 15, 2017 at 15:20
  • \$\begingroup\$ @DLosc 1) Unary output seems perfectly acceptable, I'll edit it in. 2) I think allowing arbitrary starting and ending delimiters is a good idea 3) non-standard flags are flags that aren't required to run the program. Although, in hindsight, a better idea would be to allow flags but the answer has to state which flags are used. 4) Thanks for pointing that out, editing now. \$\endgroup\$ Commented Dec 15, 2017 at 15:27
  • \$\begingroup\$ @DLosc Edited in \$\endgroup\$ Commented Dec 15, 2017 at 22:53
  • \$\begingroup\$ The character limit for PPCG answers has been bumped to 65,536. Also, not that printable ASCII excludes newlines. \$\endgroup\$
    – Dennis Mod
    Commented Dec 16, 2017 at 4:33
3
\$\begingroup\$

How acceptable is it to base challenges off of pre-existing challenges? I saw the challenge for Your Own Pet Ascii Snake and had a thought about making the output look more 'snakelike' by printing the characters |,\,/,(,),_ instead of always using the + character.

Here's how it would work. You would get some positive, negative, and 0 numbers as input, and based on those numbers, the snake moves one row down and that many characters in that direction. So, for a snake like the ones in the previous problem, your array would be restricted to the numbers 0, 1, and -1.

Here are the rules to draw the snake, the characters you print are dependent on the spacing of the lines before and after it.

So, say your snake is at position n (in the previous problem, n=30 to start, in this one you need to figure out a number for n that will keep your entire snake on the screen),

if the input is 0 you print n-1 spaces and a |
if the input is +1 you print n spaces and a \
if the input is +2 you print n spaces and \_, +10 would be \_________ (9 _ and a backslash)
if the input is -1 you print n-2 spaces and /
if the input is -2 you print n-3 spaces and _/, -10 would be _________/

Here's an example snake based on this array [+4, -3, +1, -4, +2, -3, +2, +5, -4, -1, -2, 0, +4, -4]

                        |
                         \___
                          __/
                          \
                       ___/
                       \_
                      __/
                      \_
                        \____
                        ____/
                       /
                     _/
                    |
                     \___
                     ___/

I could also add optional 'curvy' rules that would include the '(' and ')' characters on direction changes to produce a snake like this, based on the same array above:

                         |
                         \___
                          ___)
                         (_
                       ____)
                      (__
                      ___)
                     (__
                        \____
                        _____)
                       /
                     _/
                    (
                     \___
                     ____)

note that for the curvy snake, 0s are handled differently depending on if there is a direction change in the rows above and below them, here there is a negative, 0, positive pattern, so we use a '(', if there were no direction change we'd use a |, and in the opposite pattern, a ')'

There are spaces to the left of my example snake because I didn't want to count out how many spaces I should leave exactly, I don't know whether it should be mandatory to cut out extra whitespace to the left, or whether to let people have as much or as little whitespace as they want, provided that their snake doesn't 'go off screen'

\$\endgroup\$
2
  • \$\begingroup\$ I don't think there's a problem determining the next line randomly. For example, my program could generate the numbers for all 30 lines and then go back and format the characters appropriately. However, I'm not sure that's different enough to warrant its own challenge. Your second idea, though, regarding taking +1/-1/0 as input, that has some merit as it's pretty radically different than the existing snake challenge. \$\endgroup\$ Commented Feb 23, 2018 at 19:29
  • \$\begingroup\$ I'm far, far too tired for you to rely on my opinion alone but this looks sufficiently different enough from the 2 existing challenges to not be a dupe, once it's fleshed out a bit more. I'd suggest waiting a while before posting it, though, as people do get jaded of a barrage of similarly themed challenges. \$\endgroup\$
    – Shaggy
    Commented Feb 24, 2018 at 21:26
3
\$\begingroup\$

The TI series of calculators. I've put a lot of hours in writing TI-BASIC programs. The single most tedious part was either scrolling through the program, or switching between alpha and numeric input.

For those unfamiliar, the entire Latin alphabet is overlaid on the existing keys alphabetically, and to type any of them (For variable names or assembly programming), you had to first press the ALPHA key, then your desired letter. Alternatively, you could press 2ND, A-LOCK and type in any number of letters, before pressing ALPHA again for numeric input.

Why am I saying all this? I want to write a code golf like challenge where scoring is done with this tediousness in mind, like switching between numbers/punctuation and letters carrying an extra penalty.

My original idea is that the source code of the submission would be converted to hexadecimal, and the number of transitions between alphas and numerics would be the "score," with a lower score being better.

How can/should I better refine this scoring system, and what sort of challenge should accompany it?

The Challenge

Implement a program or function, in the language of your choice, that takes a string of characters as input and outputs that string's "tediousness score."

How tediousness is scored:

  1. The string is converted into its hexadecimal representation. This is Unicode for languages that don't specify, but for a language like, say, Jelly, the Jelly codepage is used.
    "The quick brown fox jumps, over the lazy dog's back." in Unicode == 0x54686520717569636b2062726f776e20666f78206a756d70732c206f76657220746865206c617a7920646f672773206261636b2e
  2. Each switch between numbers and letters in the hexadecimal representation is counted.
    0x54686520717569636b2062726f776e20666f78206a...
    ..0 12 34 56 78 9...
  3. This is your tediousness score. For this example, it is 25.

Standard loopholes apply.

Should I change the tediousness score? How might I implement golf? I thought about adding/multiplying the two together, but it still seemed to be in favor of just plain golfing. I wanted to make golfing languages be a bit harder for a golfing challenge, since they really pack their character sets and there would be a high "tediousness score".

Is the challenge, as written, clear enough? Should I restrict or relax the I/O requirements?

\$\endgroup\$
5
  • 5
    \$\begingroup\$ I have found that challenges with novel scoring mechanisms work nicely if the task is to implement the score calculator itself, see e.g. this challenge. \$\endgroup\$
    – Laikoni
    Commented Mar 12, 2018 at 8:24
  • 1
    \$\begingroup\$ Probably tedious×log(nbytes)? \$\endgroup\$
    – user202729
    Commented Mar 13, 2018 at 14:16
  • \$\begingroup\$ What about giving a list of integers (byte values), or restricting the input to printable ASCII? \$\endgroup\$
    – user202729
    Commented Mar 13, 2018 at 14:29
  • \$\begingroup\$ @user202729 Because I wanted entries to be scored by this method, and I didn't want to exclude esoteric golfing languages. I specifically want to include them, and make them hard to win with. \$\endgroup\$
    – Orion
    Commented Mar 14, 2018 at 6:06
  • \$\begingroup\$ What about "the input is a byte string"? That way you don't need to worry about the encoding. \$\endgroup\$
    – user202729
    Commented Mar 14, 2018 at 8:19
3
\$\begingroup\$

Signed exponentiation


Let us define signed exponentiation of a base x to a power n as this procedure:

  1. Take the absolute value of x.
  2. Raise to the power of n.
  3. Re-apply the original sign of x.

Or, for a more mathematical (albeit slightly flawed) definition:

the absolute value of x, to the power of n - 1, times x

For this challenge, we will denote the signed exponentiation of x to a as x ' a. Some notes:

  • Unlike f(x) = xa, f(x) = x ' a is defined for negative x no matter the value of a.
  • The negative portion of the graph of x ' n is the positive portion rotated halfway about the origin; hence, f(x) = x ' a is an odd function for all values of a.
  • If a is odd, x ' a = xa for all values of x.
  • x ' 1 = x, while x ' -1 = 1 / x. x ' 0 is a sign function (+1 for positive x, -1 for negative x).

Challenge

Given a base x and a power n, compute x ' n.

Rules

  • You may assume that -9 ≤ x, n ≤ +9.
  • You may assume that x ≠ 0, for the sake of avoiding 0 ' 0, 0 ' -1, etc.
  • You may assume that 1e-4 ≤ |x ' n| ≤ 1e9.
  • The output must be precise to at least 3 significant digits for the given test cases.
  • Input/output may be taken/given in any standard format.

Test cases

x, n -> output
1, 0 -> 1
3.14159, 0 -> 1
-9, 0 -> -1
7, 1 -> 7
-1.23456, 1 -> -1.23456
5, 2 -> 25
-4, 3 -> -64
0.1, 4 -> 0.0001
-9, 9 -> -387420489
1, -1 -> 1
-3, -1 -> -0.33333
5, -2 -> 0.04
2.71828, -9 -> 0.0001234
4, 0.5 -> 2
-2, 0.5 -> -1.41421
2, -0.5 -> 0.7071
3.8236, -1.6702 -> 0.10645
0.1, -9 -> 1000000000

Scoring

This is , so the shortest code in bytes in each langauge wins.


Sandbox questions

  • Could the definition be improved?
  • Too many test cases? Are there any important ones missing?
  • Any issues with the rules?
\$\endgroup\$
10
  • \$\begingroup\$ This isn't a huge deal, but I find the "your answer must be accurate to x significant figures" to be a largely unobservable property. The only ways to know that a submission meets this criterium is to check each and every possible combination, or to give an incredibly complex proof. I've always thought it was better to say floating point errors don't matter and to use loopholes otherwise. Maybe just a small thing about having to be able to represent any of the numbers from 1e-4 to 1e9? \$\endgroup\$ Commented Oct 2, 2017 at 21:23
  • \$\begingroup\$ Thanks @FryAmTheEggman; I like your suggestion, but I'm afraid if it's not objective enough it'll cause any issues. Any suggestions on how to phrase it? \$\endgroup\$ Commented Oct 3, 2017 at 21:38
  • \$\begingroup\$ Perhaps have a few special test cases where they have to match the first three sig figs, and put in a line that those can't be hard coded. Then otherwise floating point errors don't matter? I'm honestly unsure. I've been getting to the point where I want to ask on meta because it always feels like fp questions are unclear or unobservable. \$\endgroup\$ Commented Oct 4, 2017 at 16:38
  • \$\begingroup\$ @FryAmTheEggman Hopefully a little more objective now. \$\endgroup\$ Commented Feb 27, 2018 at 1:54
  • \$\begingroup\$ I think this looks much better, but there are perhaps too many "mandatory" test cases? Maybe making a split will make it easier for people to check the validity of answers. \$\endgroup\$ Commented Feb 27, 2018 at 6:04
  • \$\begingroup\$ Am I allowed to print more than 3 sigfigs? \$\endgroup\$
    – Nissa
    Commented Apr 6, 2018 at 22:02
  • \$\begingroup\$ @StephenLeppik Of course. Should be slightly clarified now \$\endgroup\$ Commented Apr 7, 2018 at 1:37
  • \$\begingroup\$ The way to prevent hardcoding is to have hidden test cases. \$\endgroup\$
    – user202729
    Commented Apr 7, 2018 at 11:15
  • \$\begingroup\$ @user202729 Not sure I understand. How could hard coding possibly be useful for this challenge? \$\endgroup\$ Commented Apr 7, 2018 at 14:09
  • \$\begingroup\$ "for the given test cases". Although, yes, normally it is not useful. Whether you think it's necessary is up to you, but I doubt anyone would do it. \$\endgroup\$
    – user202729
    Commented Apr 7, 2018 at 14:32
3
\$\begingroup\$

Inversion languages

Cops

For this challenge you will design two languages, A and B. Both A and B should be Turing equivalent1. When run in your two languages a program has four options:

  1. It halts in both A and B.

  2. It halts in A but not B.

  3. It halts in B but not A.

  4. It doesn't halt in either A or B.

Your goal is to try to design A and B such that as many programs as possible halt in exactly one language (options 2 and 3). Doing such for all programs is impossible2, thus there will always be programs that meet either criterion 1 or criterion 4. The robbers will attempt to find these programs.

Further rules on languages

Since we are only considering whether programs halt or not we don't care about I/O. Because of this programs should not take any input. You may produce output but really doesn't matter because it can neither hurt nor help you.

All programs should be deterministic in both languages, this means that any program that can halt must always halt and any program that can run indefinitely must do so.

Answering

Your answer should contain the following information.

  1. A concrete description of both languages

  2. Proofs that each language as described is Turing complete.

Your definitions should be rigorous and unambiguous. Meaning that a reasonable person should (given enough time) be able to workout the result of any computation. This means all edge cases should be covered and there should be no undefined behavior.

Scoring

Your score will be the time between your post and the first crack with a higher score being better.

Robbers

Robbers will score 1 point for every answer that they crack, with a higher score being better.

Your answers should include the program which cracks the cop's answer and a proof that it does.

Sandbox

This is kind of just an idea right now. I have to iron out a lot of details and I will. I'll flesh it out later I just want to get it down so I don't forget it. Right now the most useful feedback would be in broad strokes. Don't worry about details, that's my job.


1: Turing equivalent is very similar to Turing completeness, but also stipulates that the language can be simulated by a Turing machine. Turing complete languages are not Turing equivalent if they are incomputable.

2: Suppose that we did have two Turing complete languages A and B such that every program halted in exactly one of the languages. We could solve the halting problem in language A by running a program in both A and B on separate threads until one of them halted, then outputting whether it was A or not.

\$\endgroup\$
22
  • 1
    \$\begingroup\$ +1, very nice idea. But "to maintain fairness, this challenge will only be open to submissions for one week after the first cop's answer is posted" doesn't make sense to me - it seems to make it less fair, by preventing anyone from competing who comes across the challenge late or just spends time on their submission. \$\endgroup\$
    – N. Virgo
    Commented Apr 3, 2018 at 4:05
  • \$\begingroup\$ @Nathaniel The problem is that answers are scored based on how long they last answers that are late to the party have a huge advantage, since people won't be monitoring the challenge as much the older it gets. I would love to have a challenge that is open indefinitely, I strive to make that for all my challenges, so if anyone can think of a objective winning criterion that allows for this I'm all ears. \$\endgroup\$
    – Wheat Wizard Mod
    Commented Apr 3, 2018 at 4:08
  • \$\begingroup\$ I see, hmm, that makes sense even if it's unsatisfying. Nothing comes to mind as an alternative scoring mechanism for this challenge for now. \$\endgroup\$
    – N. Virgo
    Commented Apr 3, 2018 at 4:10
  • \$\begingroup\$ A separate point: I wonder if this might be a bit hard for the cops. Off the top of my head, I find it hard to think of a way to design two languages such that it wouldn't be obvious how to crack it. This might just be a failure of my imagination, however! \$\endgroup\$
    – N. Virgo
    Commented Apr 3, 2018 at 4:12
  • \$\begingroup\$ What do you mean with input [a program] into your two languages? Is this about polyglots? If so, how would you consider programs which are syntax errors in one or both of the languages? \$\endgroup\$
    – Leo
    Commented Apr 3, 2018 at 4:25
  • \$\begingroup\$ @Leo Input should probably be replaced with the verb "run". This is about polyglots. This is one of the things I plan on expanding on later on, but I'll either disallow syntax errors or consider them to be halting. \$\endgroup\$
    – Wheat Wizard Mod
    Commented Apr 3, 2018 at 4:34
  • 2
    \$\begingroup\$ Maybe avoid encrypting? (If key doesn't match, A always halt and B never halt; you hve no key lol \$\endgroup\$
    – l4m2
    Commented Apr 3, 2018 at 5:23
  • \$\begingroup\$ but once known turing complete it's usually easily converted to an ans \$\endgroup\$
    – l4m2
    Commented Apr 3, 2018 at 5:25
  • \$\begingroup\$ Although languages A and B such that all programs halt in exactly one language is impossible, A and B such that can't find one is possible \$\endgroup\$
    – l4m2
    Commented Apr 3, 2018 at 7:24
  • 2
    \$\begingroup\$ With respect to @Nathaniel's observation about "only open for a week", it's certainly true that one of the problems of C'n'R is that the robbers get bored or don't notice late cop submissions, but it's not clear what "open to submissions" means. You're surely not thinking of asking the mods to lock the question, so you can't stop people posting new submissions. Perhaps that would be better rephrased in terms of when you will award the "accepted answer". \$\endgroup\$ Commented Apr 3, 2018 at 8:47
  • \$\begingroup\$ The issue of testability is also a big one. If B is something along the lines of "Run the program through A for N steps. If it terminates, enter an infinite loop. Otherwise take the parts which are comments in language A and run them." Tune N so that it takes about a week to get any program to terminate in B. \$\endgroup\$ Commented Apr 3, 2018 at 8:52
  • \$\begingroup\$ @l4m2 I would rather not ban encrypting because I consider it an unenforcable restriction. As you pointed out proving an answer to be Turing complete becomes a large hurdle for cops to overcome if they choose to cryptography. For example it is unknown whether Malbodge Unshackled is TC. \$\endgroup\$
    – Wheat Wizard Mod
    Commented Apr 3, 2018 at 17:00
  • 1
    \$\begingroup\$ @tsh The problem with bubblegum or similar languages is that crypto functions are designed to be really hard to predict. This makes it hard to say anything concrete about their behavior, which in turn makes any language that uses them in a non-trivial manner, really hard to prove TC. TCness means it is possible to write a program for every Turing machine, and since it is almost impossible to write a program in the language it is hard to show that every program can be written. I would recommend trying to come up with a language pair that has these properties. You might run into some issues. \$\endgroup\$
    – Wheat Wizard Mod
    Commented Apr 8, 2018 at 16:05
  • 1
    \$\begingroup\$ @tsh There is no such thing as undefined behavior. \$\endgroup\$
    – Wheat Wizard Mod
    Commented Apr 9, 2018 at 2:30
  • 1
    \$\begingroup\$ Another couple of related questions: (1) to what extent does the interpreter have to meet the spec? Obviously it can't meet it completely, since the interpreter runs on a finite machine with finite addressing, and therefore can't technically be Turing complete. What about cases like integer overflow? (2) How would you handle bugs in the interpreter, and/or ambiguities in the spec? \$\endgroup\$
    – N. Virgo
    Commented Apr 9, 2018 at 3:57
3
\$\begingroup\$

Really skirting bit of sandboxing here (I haven't taken the time to develop the question):

I'd like to do a 2-d variant of this one.

Two lasers between two mirrors

The input would be an ascii maze, with a marker for the laser starting point, e.g.:

+---+------+
|*  |      |
|   |      |
|   |  ----+
|   |      |
|   |      |
|   |      |
|   +---   |
|          |
|          |
|          |
+----------+
  • Astrisk(*): laser starting point.
  • Whitespace: passable.
  • Any other character is a reflective obstacle.

Result:

+---+------+
|\  |   /\ |
| \ |  /  \|
|  \| /----+
|  /|/   /\|
| / |\  / /|
|/  | \/ / |
|\  +---/  |
| \    /   |
|  \  /    |
|   \/     |
+----------+

Rules:

  • When you can't move horizontally, reverse horizontal direction.
  • When you can't move vertically, reverse vertical direction.
  • Stop going when you meet the same laser coming the other way (e.g. when you hit a corner or reach your starting position again).I'm thinking of a golfing challenge.
  • If the laser revisits a space in the other direction, draw an upper case X.

Simplifying factors:

  • Let's just say the laser always goes the same way.
  • The map is always a rectangle.
  • Just the one laser.

It'll probably just be a golfing challenge.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ What's the goal of the program, just to draw the path? Food for thought, if you wanted a related but different challenge you could include a "start" and "goal" marker, and make the program determine if the laser ever hits the goal, returning "true" or "false" instead of a drawn maze. Or perhaps it should return how many steps it takes to hit the goal, returning either an integer, or a falsy value if it never hits it? Up to you, but some ideas. \$\endgroup\$
    – BradC
    Commented Apr 11, 2018 at 16:34
  • 3
    \$\begingroup\$ Consider removing the outside wall. You say that the laser always goes in the same direction, but I think that you should explicitly say that it always starts heading south-east (or down-right). Important test cases: All of the walls aren't connected to the border. Laser hits a 1-length wall. Laser crosses itself. Laser hits a + (on the inside). Laser barely misses a +. Laser starts next a right wall. Laser starts next to bottom wall. Laser starts at a bottom-right corner. \$\endgroup\$ Commented Apr 11, 2018 at 17:08
3
\$\begingroup\$

X1M4L got in before me and posted the very similar challenge Print the previous answer!, which I don't mind at all. However, that one seems to have turned out quite a lot more open-ended than this version would be, with answers tending to score in the tens of thousands. So after a sufficiently long delay this will probably not be considered a duplicate - I intend to leave it in the sandbox for at least a few months before posting.

Compress the previous answer

This is an challenge. The first answer must output the empty string. The second answer must output the source code of the first answer, and so on, with each answer outputting the code of the previous one.

To make this challenging, no answer may be longer than 100 bytes in length. Once the answers start getting close to this limit, it will become necessary to compress the text of the previous answers, which itself will become harder over time.

Each answer should output the exact string of bytes that forms the previous program. Because of this, if your program is in any format other than plain ASCII, you should post a hexdump as well as the source, so that the next person knows exactly what to output.

An answer's score is its position in the chain, i.e. the Nth answer scores N points. Your score is the score of your highest-scoring answer. You are encouraged to treat this challenge cooperatively, keeping the chain going as long as possible by not adding extra unnecessary entropy to your code.

The code of your answer cannot be identical to the code of any previous answer. The first answer must be at least one byte in length.

You may not post two consecutive answers. There are no restrictions on language.

tags:

\$\endgroup\$
17
  • \$\begingroup\$ that's so weird, I was thinking of this the other day, after seeing all those quine/answer chaining challenges. \$\endgroup\$
    – geokavel
    Commented Mar 21, 2018 at 16:13
  • 1
    \$\begingroup\$ You'd probably need to provide some non-empty seed, to prevent the answers from all being blank themselves. Also, would there be any restrictions on language choice - e.g. would each answer need to be in a different language than all those that came before? \$\endgroup\$
    – Sok
    Commented Mar 21, 2018 at 16:29
  • \$\begingroup\$ @user56656 just position in the chain - I've added it \$\endgroup\$
    – N. Virgo
    Commented Mar 22, 2018 at 0:30
  • \$\begingroup\$ @Sok I've fixed the "all programs empty" issue by requiring each entry to be different from the previous one. I tend towards not putting restrictions on language choice (I've added that for now) but if there's a good argument for including such restrictions I'm open minded. \$\endgroup\$
    – N. Virgo
    Commented Mar 22, 2018 at 0:31
  • \$\begingroup\$ You should probably prevent source reading. A pretty good strategy will to be to make a valid submission in language A that is also a period 2 quine in language B. Alternatively, you might want to impose the restriction that new answers are different from every previous answer instead of just the last one. \$\endgroup\$
    – Wheat Wizard Mod
    Commented Mar 22, 2018 at 0:33
  • \$\begingroup\$ Another consideration is whether consecutive answers should be permitted. It is pretty common to put restrictions on individual answerers, to prevent schemes designed to game the system. \$\endgroup\$
    – Wheat Wizard Mod
    Commented Mar 22, 2018 at 0:35
  • \$\begingroup\$ @user56656 I've implemented your idea about making them distinct from all previous answers, and I've banned consecutive answers by the same person. Does that cover all the bases? \$\endgroup\$
    – N. Virgo
    Commented Mar 22, 2018 at 0:38
  • \$\begingroup\$ I've also changed the length restriction to 100 (makes a shorter challenge, but the restriction will kick in sooner) \$\endgroup\$
    – N. Virgo
    Commented Mar 22, 2018 at 0:39
  • 1
    \$\begingroup\$ It might be prudent to try a test drive of the challenge (in chat) to test if the 100 byte limit is good. I'd be willing to help with that. Other than that I have no further thoughts at this time. \$\endgroup\$
    – Wheat Wizard Mod
    Commented Mar 22, 2018 at 0:43
  • \$\begingroup\$ @user56656 that makes sense - I'll try that when I have a chance (might be in a week or two). \$\endgroup\$
    – N. Virgo
    Commented Mar 22, 2018 at 5:40
  • \$\begingroup\$ I think you probably gain more from saying languages cannot be repeated (and including a stack snipped of used languages) than you do by adding a lot of workarounds for quines. I think it will cause the answers to become more interesting more quickly. It will also result in the challenge ending sooner, but given how the hello world answer chaining question went, I don't think you have too much to worry about with respect to longevity (though increasing the 100 may be a good idea if you decide to do this). \$\endgroup\$ Commented Mar 22, 2018 at 18:00
  • 1
    \$\begingroup\$ @FryAmTheEggman I don't think quines will be a problem in any case, because the Nth answer has to output a program that outputs a program that ... that outputs the empty string, so by definition it can't be a quine. That could be got around with polyglots, but I'd be very surprised if it would be an issue in practice - the criterion of not being identical to a previous answer is there to prevent quines not only in practice but also in theory! \$\endgroup\$
    – N. Virgo
    Commented Mar 23, 2018 at 0:59
  • \$\begingroup\$ The problem that I see is that if languages are repeatable you might get a really boring and repetitive sequence of 3-4 languages that somewhat trivialise the problem appearing quickly after each more interesting answer. I perhaps should have said "trivial modifications of near-quines" instead? Anyway, this may not happen, but I think you should focus on this as well when doing the short test run (i.e. check what portion of answers can be trivially followed by a /// or Bubblegum program). \$\endgroup\$ Commented Mar 23, 2018 at 1:31
  • 1
    \$\begingroup\$ How about making the maximum length of answer n a slowly growing function over n? \$\endgroup\$
    – Laikoni
    Commented Mar 24, 2018 at 10:43
  • \$\begingroup\$ @Laikoni that's an interesting idea. I guess probably logarithmic would be good choice. I'll give it some thought. \$\endgroup\$
    – N. Virgo
    Commented Mar 24, 2018 at 14:11
3
\$\begingroup\$

Rebuild My Scrabble Board

My daughter and I have an ongoing Scrabble tournament. We enjoy admiring the board at the end of a game. But recently we knocked over the board and didn't get a chance to get a good look or take a picture. Fortunately, we kept track of all our moves. Your challenge is to take the list of moves and use it to rebuild the Scrabble board.

Input

Each move includes 4 pieces of information

  1. Column - A - O, like the column label of a typical spreadsheet. Upper or lower case is OK, but you only need to support one or the other.
  2. Row - 1 - 15, like the row label of a typical spreadsheet. 0-indexed 0 - 14 is acceptable.
  3. Orientation - H=Horizontal, V=Vertical - Upper or lower case is OK, or you may choose any other 2 printable ASCII characters.
  4. Tiles - A - Z plus @ for blank. Upper or lower case is OK, but you only need to support one or the other. You can use a different printable ASCII character for blank if you prefer, but not the space character or a period. The tiles for a move may be a string or a list of characters - e.g., CAT or (C,A,T).

Input format may be a tuple, list, separate lines (4 per move) or any other reasonable format. Column + Row may be combined, spreadsheet-style (e.g., A1, O15), but the orientation and tiles must be separate fields. Column can't be numeric - that is easy for the computer but in the middle of a game we have enough to keep track of, so remembering which # is Row and which # is Column would be too confusing - spreadsheet notation is easy to remember.

Output

The completed Scrabble board is to be printed in a format similar to Draw an Empty Scrabble Board. However, the double/triple squares are not printed and the moves are, obviously, included. Specifically:

  • 15x15 matrix
  • Unused spaces display as a period .
  • No leading spaces allowed.
  • Trailing spaces allowed.
  • One line feed at the end of each row.
  • Up to one leading and one trailing line feed permitted.
  • Blank tiles are to be output using the same character as input (default @).

Rules

Each move is placed starting with the first tile in the specified location. Each additional tile is to be placed in the next available location. In other words, your program must keep track of filled locations and skip them, just like a player placing tiles on the board.

What you don't need to worry about:

  1. Invalid words - if my daughter and I decided it was OK, you don't have to check it.
  2. Invalid locations - these are real moves, so there will of course be enough space to place all the tiles, and you don't have to double-check that a move starts on an empty space (but you can do that if it makes your algorithm shorter since you do have to check for all the other tiles in each move).
  3. Proper use of the standard Scrabble set of tiles - e.g., you don't have to check that there are only 2 blanks, 1 Z, etc.

Examples

[Sandbox note: Plan to include a couple of complete games plus a few shorter examples to highlight particular issues]

Input:

(G,8,H,CAT)
(G,9,V,OMPUTE)
(F,9,H,RB)
(H,7,H,TIME)
(I,6,V,BE)

Output:

...............
...............
...............
...............
...............
........B......
.......TIME....
......CAT......
.....ROBE......
......M........
......P........
......U........
......T........
......E........
...............

Scoring

  • The input and output can be given by any convenient method.
  • Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
  • Standard loopholes are forbidden.
  • This is so all usual golfing rules apply, and the shortest code (in bytes) wins.
\$\endgroup\$
7
  • 3
    \$\begingroup\$ This is a very nice challenge! :-) A few suggestions/answers: yes, allow zero indexed values. I suggest that the input may optionally be numeric for both row and column, but that's up to you. You don't need to mention the next challenge. \$\endgroup\$ Commented Apr 22, 2018 at 7:01
  • \$\begingroup\$ Should you include scrabble game rules too? \$\endgroup\$
    – user202729
    Commented Apr 22, 2018 at 13:12
  • \$\begingroup\$ @user202729 I am limiting the rules to those required for the challenge. There are plenty of rules (especially scoring, but also passing/trading letters and a lot of other stuff) that isn't relevant to this challenge. If this goes well and I make another challenge for scoring then I will include the relevant rules there. I believe I have enough information here that someone could produce functional code without understanding anything else about Scrabble. \$\endgroup\$ Commented Apr 22, 2018 at 13:47
  • \$\begingroup\$ Suggest to allow other characters than . for empty board tiles. \$\endgroup\$
    – JayCe
    Commented Jun 11, 2018 at 3:45
  • \$\begingroup\$ Are trailing new lines allowed? \$\endgroup\$
    – JayCe
    Commented Jun 11, 2018 at 3:47
  • \$\begingroup\$ @JayCe ok for both. I need to finish this and turn it into an actual challenge \$\endgroup\$ Commented Jun 11, 2018 at 3:53
  • 1
    \$\begingroup\$ It is a really nice challenge indeed :) \$\endgroup\$
    – JayCe
    Commented Jun 11, 2018 at 3:55
3
\$\begingroup\$

Find the minimum set of letters to buy

Imagine that you own a board like this:

Black letter board

which lets you write any message that you want, given that you have the letters for the message. Given that you have a list of messages that you want to switch between, find the minimum number of each letter that you have to order with your board.

As an example, if your messages are Hello world and Hello aliens, you would need the letters Helloworldaiens, as both messages share the Hello part and the letter l in the second word.

For this challenge, input messages will only consist of letters a-zA-Z and space, however note that spaces are not included in the output as you don't need to buy them.

Input

Input consists of a list of strings, which all match [a-zA-Z ]+. There is no limit on the amount of messages that can be provided, or their length.

Output

Output consists of a string of a list of characters, where the letters in the output can be rearranged to create all the input messages, and is of minimal length. The output does not need to be sorted.

Examples
['Hello world', 'Hello aliens'] => Hadeeilllnoorsw
['foo', 'bar', 'baz'] => abfoorz
['Eat more tacos', 'Drink more tequila'] => DEaaceeiiklmnooqrrsttu
['Golfing is a fun activity', 'Code should be readable'] => CGaabbcdddeeeeffghiiiillnnoorsttuvy
['a', 'b', 'c', 'd', 'e', 'f', 'g'] => abcdefg

This would of course be a code-golf challenge

\$\endgroup\$
4
  • \$\begingroup\$ Hmm ... this is ringing a bell; I think we might have had it before but asking how many of each letter was needed. \$\endgroup\$
    – Shaggy
    Commented May 9, 2018 at 21:50
  • \$\begingroup\$ I tried searching for similar questions, but I couldn't find anything. This question would also ask for how many of each letter is needed, but I guess the output format might be different. \$\endgroup\$
    – maxb
    Commented May 10, 2018 at 6:14
  • 1
    \$\begingroup\$ It's this, isn't it? \$\endgroup\$ Commented May 10, 2018 at 10:53
  • \$\begingroup\$ Darn it, here I thought I had a good challenge going, but I guess the topic was too common. Thanks for the help! \$\endgroup\$
    – maxb
    Commented May 10, 2018 at 10:55
3
\$\begingroup\$

Note: I'm putting this challenge on the back burner for a indefinite time in favor of the Hierarchies challenge. Go check that or the Formic Forest out if you're interested in a Formic sequel.


Formic Functions 3: Memory

This is a preliminary write-up of a new challenge heavily inspired by Formic Functions. The spec is based on the original challenge's spec - credits for most of what you'll read here to trichoplax.

Each player starts with one ant - a queen, who collects food. Each piece of food can be held or used to produce a worker. Workers also collect food to be brought back to the queen.

All players compete in one arena. The winner is the queen holding the most food after she has taken 8,000 10,000 [Thanks @Draco18s] turns. Ants can communicate by changing the colors of the arena squares (which can also be modified by rivals), as well as by storing messages for their peers.

The arena

The arena is a toroidal (edge wrapping) grid of hexagonal cells arranged in a rhombus of side length 1000. All cells start as color 1.

Initially exactly 1% 0.5% of cells will contain food. The 5000 pieces of food will be scattered uniformly randomly. No new food will be introduced during the game.

The queens will be placed randomly on empty cells, with no guarantee that they will not be adjacent to each other (although this is very unlikely).

Ant abilities

  • Sight: Each ant sees the 7 cells in its neighborhood. It has no knowledge of any other ants outside this neighborhood. It sees the contents of each of the 7 cells (other ants and food), and also each cell's color.
  • Memory: Each ant has access to a string as its memory. It is initially empty for the queen, and must be initialized by the queen when spawning a worker. For ways to change the memory after initialization, see Output below.
  • No orientation: An ant does not know where it is or which way it faces - it has no concept of North. The neighborhood will be presented to it at a randomly rotated orientation that changes each turn so it cannot even walk in a straight line unless it has colors to guide it. (Making the same move every turn will result in a random walk rather than a straight line.)
  • Moving, color marking, producing workers and transferring food: See Output below.
  • Immortality: These are highland ants that cannot die. You can confuse rival ants by changing the colors around them, or constrain them from moving by surrounding them with 6 ants of your own, but they cannot be harmed apart from this. [Should ants be able to die? If so, how?]
  • Carrying food: A worker can carry up to 1 piece of food. A queen can carry an arbitrary amount of food.

Coding

Provide a function body

Each ant is controlled by an ant function. Each turn the player's ant function is called separately for each ant (not just once per player, but once for the queen and once for each worker that player controls). Each turn, the ant function will receive its input and return a move for that particular ant.

Post an answer containing a code block showing the body of a JavaScript function, and it will be automatically included in the controller. The name of the player forms the title of the answer, in the form # PlayerName.

No access to outside data

Functions must be fully deterministic. When called with a given input, they must return the same output every time. A function must not access global variables and must not store state between turns in other ways than through the provided memory string. It may use built in functions that do not involve storing state or accessing data from the outside. For example, the use of Math.abs() is fine, but Date.getTime(), Math.random() must not be used.

An ant function may only use a pseudo random number generator that it supplies itself, that utilizes data provided through input. For example, it may implement its own pseudo RNG via its memory string, seeded by the environment (or statically).

A simple random strategy is still possible due to the random orientation of the input - an ant that always chooses the same direction will perform a random walk rather than a straight line path.

An ant function is permitted to contain further functions within its body.

Input and output

Input

The orientation of the input will be chosen at random for each ant and for each turn. The input will be rotated by 0, 60, 120, 180, 240 or 300 degrees, but will never be reflected.

Cells are numbered in this order:

 0 1
5 6 2
 4 3

The ant function will receive an array called view, containing an object for each of the 7 visible cells. Each object will have the following:

color: a number from 1 to 8
food: 0 or 1
ant: null if there is no ant on that cell, or otherwise an ant object

[Is 8 colors perhaps too many?]

If a cell contains an ant, the ant object will have the following:

food: 0 or more (maximum 1 for a worker)
queen: true or false
friend: true or false
memory: memory string when friendly, otherwise undefined

[Should ants be able to read rivals' memories? This would cause rampant edit wars. Rejected.]

The ant can determine its own details by looking at the ant in the central cell, view[6].ant. For example, view[6].ant.memory contains the memory of the executing ant.

Output

Output is returned as an object representing the action to take. This can have any of the following:

cell: a number from 0 to 6 (mandatory)
color: a number from 1 to 8 (optional)
spawn: a string (optional)
memory: a string (optional)

If color and spawn are omitted or non-truthy, then cell indicates the cell to move to.

If color is a number, the indicated cell is set to that number.

If spawn is a string, a worker ant is created on the indicated cell. The new worker will have its memory initialized to that string. The string cannot be longer than 256 characters. Only a queen can create a new worker, and only if she has food, as this costs one piece of food per worker.

If memory is a string, the executing ant will have its memory immediately changed to that string. The string cannot be longer than 65,536 characters for the queen, and 256 characters for workers. An ant may change its memory while also performing a different action - changing memory does not take a turn.

[Should changing own memory take a turn?]

[Should ants be able to send a message directly to another ant's inbox? For example, a message could look like this: {title:"help", content:view_array_of_sender}. An ant should also be able to perform an action while sending a message, otherwise the described behavior could be emulated.]

[Should ants be able to see the age of an ant? This behavior will often be emulated with memory. Is there a reason not to do that?]

[Is 65,536 characters a good number to pick for the max length of memory? Thanks to @Draco18s's and @dzaima's advice, workers now have significantly less memory than a queen.]

Example outputs:

{cell:0}: move to cell 0
{cell:5, memory:"abc"}: move to cell 5 and set own memory to "abc"
{cell:6}: move to cell 6 (that is, do nothing, as 6 is the central cell)
{cell:6, color:8}: set own cell to color 8
{cell:2, color:1, memory:"hey"}: set cell 2 to color 1 and set own memory to "hey"
{cell:1, spawn:"def", memory:"5252"}: create a worker with its memory initialized to "def" on cell 1 and set own memory to "5252"
{cell:3, color:0}: equivalent to just `{cell:3}` - move rather than set color
{cell:1, spawn:0}: equivalent to just `{cell:1}` - move rather than create worker
{cell:4, color:0, spawn:0}: move to cell 4 - color 0 and type 0 are ignored

Invalid outputs:

{cell:7}: cell must be from 0 to 6
{cell:0, color:9}: color must be from 1 to 8
{cell:0, spawn:true}: spawn must be a string
{cell:6, spawn:"254"}: cannot create a worker on a non-empty cell
{cell:0, color:1, spawn:"77"}: cannot set color and create worker in the same turn
{cell:3, memory:true}: cannot set memory to non-string
{cell:2, spawn:true}: cannot create a worker with a non-string memory
{cell:0, memory:long_string}: (if long_string is a string of length > 65536) cannot set memory to a string of length greater than 65536

[Missed any?]

An ant moving onto a cell containing food will automatically pick up the piece of food. If that ant is a laden worker, it will move onto the cell without picking up the piece of food.

An unladen worker trying to move onto an enemy queen with food will steal one piece of food from her instead. A laden worker trying to move onto an unladen friendly worker or a friendly queen will give its food to their target instead.

Turn order

Ants take turns in a set order. At the start of a game the queens are assigned a random order which does not change for the rest of the game. When a queen creates a worker, that worker is inserted into the turn order at the position before its queen. This means that all other ants belonging to all players will move exactly once before the new worker takes its first turn.

Limit on number of players

Obviously an unlimited number of players cannot fit into the arena. If there are more than 8 answers, only 8 of them will play in any one game.

[Good max number of players?]

Time limit per turn

Each time the ant function is called, it should return within 20 milliseconds. Since the time limit may be exceeded due to fluctuations outside the ant function's control, an average will be calculated. If at any point the average is above 20 milliseconds and the total time taken by that particular ant function across all calls so far is more than 10 seconds, the relevant player will be disqualified.

[Enough time?]

Disqualification

This means the player will not be eligible to win and their ant function will not be called again during that game. They will also not be included in any further games. If a player is disqualified on the tournament machine during a leaderboard game then it will be excluded from all future leaderboard games until edited.

A player will be disqualified for any of the following for any of its ants (queen or worker):

  • Exceeding the time limit as described.
  • Returning an invalid move as described under Output.
  • The cell to move to contains an ant and the case isn't defined under Output.
  • The cell to produce a worker on contains an ant.
  • A worker is trying to produce a worker.

[Did I miss any?]

It may seem harsh to disqualify for invalid moves, rather than simply interpreting this as no move. However, I believe that enforcing correct implementations will lead to more interesting strategies over time. This is not intended to be an additional challenge, so a clear reason will be displayed when a player is disqualified, with the specific input and output alongside to aid in fixing the code.

Multiple answers and editing

You may provide multiple answers, provided that they do not team up against the others. Provided each answer is working solely towards its own victory, you are permitted to tailor your strategy to take advantage of weaknesses in specific other strategies, including changing the color of the cells to confuse or manipulate them. Bear in mind that as more answers come in, the likelihood of meeting any particular player in a given game will diminish.

You may also edit your answers whenever you choose. It is up to you whether you post a new answer or edit an existing one. Provided the game is not flooded with many near-identical variations, there should be no problem.

If you make a variation of another person's answer, please remember to give them credit by linking to their answer from yours.

Scoring

At the end of each game, a player's score is the number of other players who have less food carried by their queen. Food carried by workers is not counted. This score is added to the leaderboard, which is displayed in order of average score per game.

Joint places indicate that the order of players is not yet consistent between 6 subsets of the games played so far. The list of games is split into 6 subsets because this is the minimum number that will give a probability of less than 5% that a given pair of players will be assigned distinct places in the wrong order.

[Scoring mechanism subject to change.]

[New feature/modification recommendations are very welcome! I want this challenge to be as different from the original Formic as possible, while keeping its spirit.]

\$\endgroup\$
9
  • 2
    \$\begingroup\$ 8000 turns is too few, 65k of memory is way too much. \$\endgroup\$ Commented Mar 7, 2018 at 22:12
  • \$\begingroup\$ I feel like the food density being so high is compensation enough for 8k moves. This was also chosen out of speed concerns - no caching like the previous Formic. 65k memory was designed as a "use all you want". I wanted to allow doing some crazy stuff, like storing large portions of the map. After some consideration, however, limiting this to for example 1k could be a good idea. \$\endgroup\$
    – Alion
    Commented Mar 7, 2018 at 22:21
  • 1
    \$\begingroup\$ One thing that might make this challenge stand out would be if food "respawns" over time. That is, every N turns Y food is added to the board. Also, I still don't like the hex layout for the reasons dzaima pointed out in chat. \$\endgroup\$ Commented Mar 8, 2018 at 0:38
  • \$\begingroup\$ That would encourage periodically re-searching parts of the board for more complex entries... It would be simple to do, considering you have a lot of memory, but... Isn't this just complexity tacked on for the sake of complexity? Hmm, I'm not sure how I feel about this. \$\endgroup\$
    – Alion
    Commented Mar 8, 2018 at 9:17
  • 1
    \$\begingroup\$ I'd suggest that the queen has the 65k memory but the workers - maybe ~500. Also do consider that each character is (IIRC) 2 bytes as JS uses UTF-16 \$\endgroup\$
    – dzaima
    Commented Mar 8, 2018 at 9:21
  • \$\begingroup\$ I was just thinking about more memory for the queen. Great idea! \$\endgroup\$
    – Alion
    Commented Mar 8, 2018 at 9:22
  • 3
    \$\begingroup\$ Saying that a "grid of hexagonal cells" is "toroidal" and has a specific "height" and "width" is somewhat ambiguous. I think I understand now, but it bears some more detailed explanation. \$\endgroup\$ Commented Mar 8, 2018 at 15:42
  • \$\begingroup\$ Oh, good point. I thought it was obvious enough. I'll find a way to explain it better. \$\endgroup\$
    – Alion
    Commented Mar 8, 2018 at 16:41
  • \$\begingroup\$ @KamilDrakari Is it clear enough now? \$\endgroup\$
    – Alion
    Commented Mar 21, 2018 at 16:48
3
\$\begingroup\$

How many times was the function called?

Inspired by this question.

Using your language of choice, write a function that takes no argument and returns the number of times it was called.

Specifics:

Your language needs to support something callable (multiple times) that takes no argument (or an empty unused argument) and returns a number or a string representing the number of times it was called, for example 1, 1.0 or "1". Standard I/O applies.

Samples:

f() returns 1
f();f() returns 1 2
f();f();f();f() returns 1 2 3 4

Note that f(f(f(f()))) (function composition with itself) is not in the scope of this challenge.

As this is code-golf, the winning solution in any language is the one that uses the fewest number of bytes in this language.

\$\endgroup\$
10
  • \$\begingroup\$ My first question ever - interested to know if is this too trivial or a duplicate. I am aware that a function-oriented challenge restricts the number of languages sadly. related but not a dupe of this one \$\endgroup\$
    – JayCe
    Commented Jun 9, 2018 at 13:55
  • \$\begingroup\$ Can we use a program instead of a function? \$\endgroup\$
    – user202729
    Commented Jun 10, 2018 at 3:06
  • \$\begingroup\$ @user202729 I am just not sure how to state it with a program... \$\endgroup\$
    – JayCe
    Commented Jun 10, 2018 at 3:22
  • \$\begingroup\$ Make the program take no input and output number of times it's called. (require file I/O or something) \$\endgroup\$
    – user202729
    Commented Jun 10, 2018 at 3:23
  • 1
    \$\begingroup\$ I'm left feeling like I have seen a question for a function which gives a different output each time it is run but I can't seem to find it. \$\endgroup\$ Commented Jun 11, 2018 at 22:20
  • \$\begingroup\$ @fəˈnɛtɪk maybe this ? \$\endgroup\$
    – JayCe
    Commented Jun 11, 2018 at 23:29
  • \$\begingroup\$ @fəˈnɛtɪk or this one maybe \$\endgroup\$
    – JayCe
    Commented Jun 11, 2018 at 23:36
  • \$\begingroup\$ How may we store the state between calls? Self-modifying code? File? Global variable? \$\endgroup\$
    – Adám
    Commented Jun 12, 2018 at 9:26
  • 1
    \$\begingroup\$ So this is the one I thought it was a duplicate of \$\endgroup\$ Commented Jun 24, 2018 at 13:38
  • \$\begingroup\$ @fəˈnɛtɪk thanks i will take a look at this one and related questions. \$\endgroup\$
    – JayCe
    Commented Jun 24, 2018 at 19:45
3
\$\begingroup\$

Mixed alphanumeric sort

Can't decide if you want to sort by letter or by number? Just do both!

Create a program that, given a series of strings composed of the characters _, 0-9, and a-z, sorts them and returns them in order.


Sorting is done according to the following algorithm:

  • A token is any character among _a-z or a contiguous series of numerals
  • The empty string is sorted first
  • Single token strings are sorted as follows:
    • _ is sorted before numbers, and numbers are sorted before letters
    • Numbers are sorted in numeric order, and letters are sorted from A to Z
    • If two numbers have the same value, the shorter one is sorted first
  • Multi token strings are sorted according to the first token. If the first token is the same, then use the second, then third, etc.

Here is an example of a sorted list. You can use newlines, commas, or whatever else to separate the items, or you can just use a standard array type.

_first
5
5x
5y
123
0123
124
ab_
ab5
ab10
abc
abc
abc00b
abc000a

Rules

  • Input list can contain empty strings, but is always at least 1 element long
  • Input and output may be a list, or a string with separator characters of choice
  • Output can also be in-place (modifying the input list), as long as the changes are readable from outside the program
  • You can choose to process uppercase characters instead of lowercase ones
  • Standard loopholes apply
  • Lowest byte count wins

Sandbox questions

  • Is the description clear enough, or could anything be added to it?
  • It turns out this is a near duplicate of this one, but with the addition of a character that must be sorted before numbers, which changes the strategy. Is this different enough to be its own question?
\$\endgroup\$
3
\$\begingroup\$

Diagonalize a Blackbox

todo: test cases

more math explaination?

better challenge definition?

The function \$f(x_1,x_2,x_3)=(3x_1,x_1+2x_2,x_1+x_2+x_3)\$ is a linear transformation on \$\mathbb{R}^3\to\mathbb{R}^3\$. We can prove this, because like all linear transformations, it satisfies:

  • \$f(x_1+y_1,x_2+y_2,x_3+y_3)=f(x_1,x_2,x_3)+f(y_1,y_2,y_3)\$
  • \$f(\alpha x_1,\alpha x_2,\alpha x_3)=\alpha f(x_1,x_2,x_3)\$

Or, more compactly:

  • \$f(\alpha x+\beta y) = \alpha f(x)+\beta f(y)\$

All linear transformations like this can be represented by a matrix multiplication, such as:

$$ M = [f(x)] = \begin{bmatrix} 3 & 0 & 0 \\ 1 & 2 & 0 \\ 1 & 1 & 1 \end{bmatrix} \begin{pmatrix} x_1 \\ x_2 \\ x_3 \end{pmatrix} = (x_1,x_1+x_2,x_1+x_2+x_3) $$ One way to find this matrix is by feeding each of the members of the standard basis for \$\mathbb{R}^3\$, which is \$B = \{(1,0,0),(0,1,0),(0,0,1)\}\$, into \$f(x)\$ to get the columns. This can be for any linear transformation and any basis to get a matrix which represents the transformation in that basis.

For some linear transformations, there is a basis \$B'\$ in which \$M'\$ is diagonal - this requires that \$M\$ in \$B\$ be diagonalizable which requires it have unique eigenvalues. However, in this challenge all transformations you have to deal with will fulfill these requirements.

Continuing with the same example, we can determine the eigenvalues of \$M\$ by finding solutions to \$|M-\lambda I_3|=0\$, and the eigenvectors by solving \$Mv=\lambda v\$ for each \$\lambda\$:

$$ |M-\lambda I_3| = (3-\lambda) \begin{vmatrix} 2 - \lambda & 0 \\ 1 & 1 - \lambda \end{vmatrix} = (3-\lambda)(-(2-\lambda)(1-\lambda))\\ (\lambda-3)(-(2-\lambda)(1-\lambda)) = 0 \implies \lambda_1,\lambda_2,\lambda_3 = 3,2,1$$ This gives us a diagonal matrix \$M' = \begin{bmatrix}3&0&0\\0&2&0\\0&0&1\end{bmatrix}\$ $$ \begin{bmatrix} 3 & 0 & 0 \\ 1 & 2 & 0 \\ 1 & 1 & 1 \end{bmatrix}\begin{pmatrix} a\\b\\c \end{pmatrix} = \begin{pmatrix}3a\\a+2b\\a+b+c\end{pmatrix}\\ \lambda_1\begin{pmatrix}a\\b\\c\end{pmatrix}=\begin{pmatrix}3a\\3b\\3c\end{pmatrix}=\begin{pmatrix}3a\\a+2b\\a+b+c\end{pmatrix}\implies v_1=(1,1,1)\\ \lambda_2\begin{pmatrix}a\\b\\c\end{pmatrix}=\begin{pmatrix}2a\\2b\\2c\end{pmatrix}=\begin{pmatrix}3a\\a+2b\\a+b+c\end{pmatrix}\implies v_2=(0,1,1)\\ \lambda_3\begin{pmatrix}a\\b\\c\end{pmatrix}=\begin{pmatrix}a\\b\\c\end{pmatrix}=\begin{pmatrix}3a\\a+2b\\a+b+c\end{pmatrix}\implies v_3=(0,0,1) $$ This gives us a basis \$B'=\{(1,1,1),(0,1,1),(0,0,1)\}\$ where the matrix \$M'\$ represents \$f(x)\$.

In this basis, a vector that would be \$(5,6,7)\$ in \$B\$ is instead \$(5,1,1)\$, as shown here: $$(5,1,1)_{B'} = 5(1,1,1)+1(0,1,1)+1(0,0,1) = (5,6,7)_B$$

This affects the transformation as well:

$$ \begin{bmatrix} 3&0&0\\ 1&2&0\\ 1&1&1 \end{bmatrix} \begin{pmatrix} 5\\6\\7 \end{pmatrix} =\begin{pmatrix} 15+0+0\\ 5+12+0\\ 5+6+7 \end{pmatrix} =(15,17,18)_B\\ \begin{bmatrix} 3&0&0\\ 0&2&0\\ 0&0&1 \end{bmatrix} \begin{pmatrix} 5\\1\\1 \end{pmatrix} =\begin{pmatrix} 15+0+0\\ 0+2+0\\ 0+0+1 \end{pmatrix} =(15,2,1)_{B'}\\ (15,2,1)_{B'}=15(1,1,1)+2(0,1,1)+1(0,0,1)=(15,17,18)_B $$

Caveats

Notice how when we were finding \$v_1\$ above we picked \$(1,1,1)\$ to simplify. Unfortunately \$v_1=(7,7,7)\$, \$v_2=(0,-3,-3)\$ (and infinitely many more) are also valid in this context.
To make every solution uniform, we normalize each of the vectors:

$$ v_1=\frac{(1,1,1)}{\sqrt{1^2+1^2+1^2}}=(\frac{1}{\sqrt{3}},\frac{1}{\sqrt{3}},\frac{1}{\sqrt{3}})\\ v_2=\frac{(0,1,1)}{\sqrt{1^2+1^2}}=(0,\frac{1}{\sqrt{2}},\frac{1}{\sqrt{2}})\\ v_3=\frac{(0,0,1)}{\sqrt{1^2}}=(0,0,1) $$

So we get a basis \$B'=\{(\frac{1}{\sqrt{3}},\frac{1}{\sqrt{3}},\frac{1}{\sqrt{3}}),(0,\frac{1}{\sqrt{2}},\frac{1}{\sqrt{2}}),(0,0,1)\}\$, which corresponds to:

$$(5,1,1)_{B'} = 5(\frac{1}{\sqrt{3}},\frac{1}{\sqrt{3}},\frac{1}{\sqrt{3}})+1(0,\frac{1}{\sqrt{2}},\frac{1}{\sqrt{2}})+1(0,0,1)\\ = (\frac{5}{\sqrt{3}},\frac{1}{\sqrt{2}}+\frac{5}{\sqrt{3}},1+\frac{1}{\sqrt{2}}+\frac{5}{\sqrt{3}})_B$$

Additionally, we also add a restriction so that the first non-zero element of each eigenvector must be positive, flipping the signs of the rest of the vector if it was initially negative.

The Challenge

Your task is to write a function or program which takes a black-box function or program and either:

  1. outputs a function or program which accepts arguments in a special basis \$B'\$ as described above, performs the transformation on them, and returns the result in the standard basis \$B\$

  2. outputs the result in \$B\$ directly and takes the secondary arguments in \$B'\$ itself

Input

You are given a function (via one of the standard IO methods applicable) taking a vector as input and returning another vector in the same form, as the same data type.

Alternatively, you can take a program (via the name of an executable in the current working directory, or a process ID) which takes a vector as input through one of the standard input methods for programs, and outputs a vector in a whitespace-separated string.
(The executable can be in a different language, so don't try to read it.)

The input and output vectors for this function or program are in \$\mathbb{R}^n\$ with basis \$B\$.
You are also given a number specifying the size of the lists to be used (\$n\$ in \$\mathbb{R}^n\$).

If you follow the second option you will additionally receive a vector in basis \$B'\$.

Output

Otherwise, output a function taking a vector as input and returning another vector, where the function you output uses the standard IO methods for your language. Your submission may output this function as a literal function, function pointer, or as source code for such a function in your language. Instead of a function, you may output a whole program as source code or compiled binary, which takes a vector as input and returns another vector via the standard IO methods for your language.

The input and output vectors for this function or program are in \$\mathbb{R}^n\$.
The input vectors have basis \$B'\$, and the output vectors have basis \$B\$.

If you follow the second option then the above statement applies to your submission instead of the output, and you do not need to output a function nor a program but instead the specified vector.

Criteria

As this is , the shortest code in bytes for each language, further subdivided by combination of function / program as input / submission / output, wins!

Test Cases

todo

Notes

While it's a bit math-y, there are multiple interesting routes to go for a solution to this:

  • Transform \$B'\to B\$ and pass to the input function or program
  • Follow the question closely and apply the transformation via \$M'\$
  • More I won't disclose
  • Probably more I haven't thought of
\$\endgroup\$
3
\$\begingroup\$

Making a Mountain out of a Molehill

\$\endgroup\$
4
  • \$\begingroup\$ I'm not clear where the molehills start and end. Based on the description I thought they'd just be /\ without any of the surroundings. \$\endgroup\$
    – xnor
    Commented Sep 28, 2018 at 23:03
  • \$\begingroup\$ @xnor does the edit clarify it? \$\endgroup\$
    – RamenChef
    Commented Oct 1, 2018 at 13:59
  • \$\begingroup\$ No, I'm still confused. Being flat counts as going down? Also, from the examples I take it that "down" is taken looking towards the mountain? And what if you have two molehills separated by a flat area, are both molehills considered to include that flat area? \$\endgroup\$
    – xnor
    Commented Oct 2, 2018 at 0:03
  • \$\begingroup\$ @xnor no, being flat doesn't count as going down. Where did you get that notion? \$\endgroup\$
    – RamenChef
    Commented Oct 3, 2018 at 11:45
3
\$\begingroup\$

Recognize the hardest context-free language


A context-free language is a class of strings that can be recognized by a pushdown automaton, or equivalently produced by a BNF grammar. In her 1973 paper, Sheila Greibach showed that there exists in some sense a "maximally complex" context-free language. In this challenge, your task is to recognize this language.

The language

The words of the language \$L\$ use the seven characters \$\mathtt{()[]ABC}\$. You may use any seven printable ASCII characters in their place, but we use these in the explanation and test cases. A string \$s\$ is in the language if:

  1. It can be broken into \$n\$ pieces: \$s = w_1 \mathtt{C} w_2 \mathtt{C} \cdots w_n \mathtt{C}\$ where the \$w_i\$ do not contain \$\mathtt{C}\$s.
  2. Each \$w_i\$ has a substring of the form \$\mathtt{B} x_i \mathtt{B}\$ where \$x_i\$ does not contain \$\mathtt{B}\$s.
  3. The concatenation \$x_1 x_2 \cdots x_n\$ has the form \$\mathtt{A} b\$, where \$b\$ is a balanced string over \$\mathtt{()[]}\$.

Note that each \$w_i\$ may have several substrings that begin and end with \$\mathtt{B}\$, but we require that the third condition holds for at least one choice of the \$x_i\$. Also, some of the \$x_i\$ may be empty.

Here is an example of a string in \$L\$ and an explantion for it:

]BA[]BA[](BCB[]BA]B()(BC]B][BB]BCB)BAAB))C
           C           C        C        C    Split by C
     BA[](B B[]B            BB   B)B          Find substring surrounded by B in each part
      A[](   []                   )           Their interiors give A + balanced string

Here is a BNF grammar for \$L\$: [TODO: verify that this is correct]

<L>        ::= <trash> "BB" <trash> "C" <L>
             | <trash> "BA" <balanced> "B" <trash> "C"
<balanced> ::= <skip-c> <balanced>
             | "(" <balanced> ")"
             | "[" <balanced> ")"
             | <balanced> <skip-cs> <balanced> <skip-cs>
<skip-cs>  ::= <skip-c> <skip-cs> | ""
<skip-c>   ::= "B" <trash> "C" <trash> "B"
<trash>    ::= <not-c> <trash> | ""
<not-c>    ::= "A" | "B" | "(" | ")" | "[" | "]"

The task

Your input is a non-empty string over the alphabet of \$L\$. As stated above, you may use any 7 printable ASCII characters. Your program/function shall do one of the following:

  • Output a truthy value if the input is in \$L\$, and a falsy value if not.
  • Output a consistent value if the input is in \$L\$, and a different consistent value if not.

The lowest byte count wins, and other standard rules apply.

Test cases

TODO

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

Number of Unit Squares Intersecting a Circle

https://i.sstatic.net/3KdLe.gif

(Credit to user202729 for the illustration)

OEIS sequence A234300 is defined thusly:

  • A radius range is either a single real number at which the circle centered at \$(0,0)\$ passes through some lattice point, or an interval between two such consecutive numbers.
  • The first radius range is the number \$0\$.
  • The \$n\$th term of the sequence is the number of unit squares on the upper right quadrant of the Cartesian grid whose interior contains some segment of the circle of radius \$r\$, where \$r\$ is in the \$n\$th radius range.

This table shows the radius range and corresponding sequence terms for the first 11 terms of the sequence.

Range       Term
0           0
(0,1)       1
1           1
(1,√2)      3
√2          2
(√2,2)      3
2           3
(2,√5)      5
√5          3
(√5,√8)     5
√8          4

Input

A positive integer n (or nonnegative for zero-indexed).

Output

Either the \$n\$th term of the sequence, or a list of the first \$n\$ terms. You may index from \$n=0\$ or \$n=1\$.

\$\endgroup\$
5
  • \$\begingroup\$ I made a picture. /// I still don't get why integral radius is important, that appears to be a special-case rather than a rule. \$\endgroup\$
    – user202729
    Commented Dec 1, 2018 at 3:31
  • \$\begingroup\$ @user202729 wow, what did you use to generate it? \$\endgroup\$
    – lirtosiast
    Commented Dec 1, 2018 at 3:45
  • 1
    \$\begingroup\$ Logo (source code) \$\endgroup\$
    – user202729
    Commented Dec 1, 2018 at 4:14
  • \$\begingroup\$ I would be pedantic and qualify "on the Cartesian grid" as "in the upper-right quadrant of the Cartesian grid". \$\endgroup\$ Commented Dec 1, 2018 at 10:50
  • \$\begingroup\$ Surprisingly, this doesn't look like a dupe... \$\endgroup\$
    – lirtosiast
    Commented Dec 2, 2018 at 21:19
3
\$\begingroup\$

Non-overlapping Matrix Sum

Given k arrays of length n, output the maximum sum possible using one element from each matrix such that no two elements are from the same position. It is guaranteed that k<=n.

Input

A nonempty list of nonempty arrays of integers.

Output

An integer that represents the maximum sum.

Examples

Input -> Output
[[1]] -> 1
[[1, 3], [1, 3]] -> 4
[[1, 4, 2], [5, 6, 1]] -> 9
[[-2, -21],[18, 2]] -> 0
[[1, 2, 3], [4, 5, 6], [7, 8, 9]] -> 15
[[1, 2, 3, 4], [5, 4, 3, 2], [6, 2, 7, 1]] -> 16
\$\endgroup\$
4
  • \$\begingroup\$ @lirtosiast I’m not quite sure what that means. \$\endgroup\$
    – Quintec
    Commented Dec 13, 2018 at 18:59
  • \$\begingroup\$ @lirtosiast Sorry, still don't understand. If ((3,1),(4,1)) and ((5,9)(2,6)) are the arrays, the function should return 13, but it returns 20? \$\endgroup\$
    – Quintec
    Commented Dec 13, 2018 at 20:01
  • \$\begingroup\$ I understand the challenge now. Test cases would definitely be useful. I would consider changing to a version with 1d vectors instead of matrices, as the matrix structure doesn't seem to add much. \$\endgroup\$
    – lirtosiast
    Commented Dec 13, 2018 at 20:26
  • \$\begingroup\$ @lirtosiast Yeah, makes sense. This actually came up when thinking about programming AI for a game, which is why I wrote it as a matrix to start. I'll change it to 1d arrays \$\endgroup\$
    – Quintec
    Commented Dec 13, 2018 at 21:52
3
\$\begingroup\$

Output Hello, World! ... sometimes

On PPCG, we typically do not allow programs to work only part of the time. That is, all programs must work with 100% probability unless otherwise stated.

This challenge is going to state otherwise. Your program must, with nonzero probability, output this exact string to STDOUT:

Hello, World!

However, a simple Hello, World! program will not do. Your program must also have nonzero probability to behave in any other way than outputting the above string. This could be printing another string, printing Hello, World! surrounded by junk text, outputting Hello, World! to STDERR instead of STDOUT, outputting nothing, crashing, etc. Your program may have many different behaviors than printing the desired string.

This is a , so the shortest program in bytes wins.

Example program

The following program in JavaScript is a valid submission. It will output Hello, World! half the time, and the other half of the time output a float >= 0.5.

const THRESHOLD = 0.5;
let randomFloat = Math.random();

let output;

if(randomFloat < THRESHOLD) {
    output = "Hello, World!";
}
else {
    output = randomFloat.toString();
}

console.log(output);

Try it online!

\$\endgroup\$
10
  • \$\begingroup\$ Good to have a catalog for IMO. \$\endgroup\$
    – lirtosiast
    Commented Dec 28, 2018 at 3:38
  • \$\begingroup\$ Should there be a requirement that HW should be outputted with probability > 0.5 or some threshold? \$\endgroup\$
    – user202729
    Commented Dec 28, 2018 at 9:02
  • \$\begingroup\$ @user202729 Good idea. \$\endgroup\$
    – Adám
    Commented Dec 28, 2018 at 12:06
  • \$\begingroup\$ I'm not sure how this would be different than codegolf.stackexchange.com/q/114520/42963 or codegolf.stackexchange.com/q/66922/42963 \$\endgroup\$ Commented Dec 28, 2018 at 17:01
  • \$\begingroup\$ What's to stop me from outputting 13 random characters? There's a nonzero probability of that outputting "Hello, World!" \$\endgroup\$
    – Beefster
    Commented Dec 28, 2018 at 19:25
  • \$\begingroup\$ @Beefster nothing, is there something wrong with that approach? \$\endgroup\$ Commented Dec 28, 2018 at 21:29
  • \$\begingroup\$ @user202729 I don't see why enforcing a threshold is a good idea. \$\endgroup\$ Commented Dec 28, 2018 at 21:29
  • \$\begingroup\$ @AdmBorkBork I'm not sure why they'd be considered the same as this challenge. \$\endgroup\$ Commented Dec 28, 2018 at 21:31
  • 2
    \$\begingroup\$ Perhaps the requirement should be made that the desired output should appear more frequently than any other possible output. \$\endgroup\$ Commented Dec 28, 2018 at 21:35
  • \$\begingroup\$ @ConorO'Brien That's another way (that way the challenge becomes strictly harder than HW for most languages) // About the threshold - depends on whether you want to avoid solutions that generate a random string. \$\endgroup\$
    – user202729
    Commented Dec 29, 2018 at 9:12
3
\$\begingroup\$

Speeding up powers of 2

Create a function or program that indefinitely prints outs successive powers of 2 separated by newlines. However, the nth term of the sequence (2^n) must have a delay of 1/n seconds either before or after it is printed, but please specify this in your answer. If you choose to add the delay before the number is printed, the first number may optionally have a delay before it is printed.

Your program may begin with 1 or 2 as the first printed number, but if you include 1, it is considered the 0th term, and your delays must be before each print and skip any initial delay (1/0 as a delay would not work, hence this rule).

Your program should run properly until it either reaches the integer limit of your language, or until n = 1000 (a 1 ms delay)

Expected output if 1 is included:

1 # after, wait 1/1 seconds
2 # after, wait 1/2 seconds
4 # after, wait 1/3 seconds
8 # after, wait 1/4 seconds
16 # after, wait 1/5 seconds
# etc...

Expected output if 1 is not included:

2 # before/after, wait 1/1 seconds
4 # before/aftert, wait 1/2 seconds
8 # before/after, wait 1/3 seconds
16 # before/after, wait 1/4 seconds
# etc...

Sandbox

  • How should I improve the wording?
  • What potential ambiguities or language limits are there?
  • Is this too similar to a preexisting challenge?

EDITS: Clarified that n refers to the term number, not the power of 2

\$\endgroup\$
13
  • \$\begingroup\$ I like the idea, but any language with arbitrary precision integers is disqualified because it's not possible (and it's not a small set of languages, a lot of languages support).. \$\endgroup\$ Commented Jan 10, 2019 at 2:12
  • \$\begingroup\$ @BMO How is this impossible with arbitrary precision integers? Does it make it difficult to calculate the delays or is there some way in which printing some larger numbers make this impossible? Also, should I require that programs theoretically work for integers beyond the limit of the language (with minor modifications to account for this)? \$\endgroup\$
    – Neil A.
    Commented Jan 11, 2019 at 4:31
  • \$\begingroup\$ The delay needs to be \$\frac{1}{n}\$, any system imposes some \$t_{\min}\$ which is required to output anything at all, as \$n\$ gets larger there will be some \$n_0\$ where \$\frac{1}{n_0} < t_{\min}\$ which is not possible. In short: The delay gets arbitrarily small while the work gets arbitrarily large and at some point this becomes infeasible. \$\endgroup\$ Commented Jan 11, 2019 at 10:02
  • \$\begingroup\$ Are we allowed to sleep 1/1 seconds before printing 2 in the first iteration? Or are we allowed to print 1 and sleep 1/2 seconds afterwards in the first iteration? \$\endgroup\$ Commented Jan 11, 2019 at 12:18
  • \$\begingroup\$ @BMO is indeed right that fairly quickly 1/n will become 0 in loads of languages. Java for example has a maximum precision of 16 decimal digits after the comma for floats/doubles (it does have BigDecimals for higher precision, but let's ignore those for now). The 64th iteration (number 18446744073709551616) will have a delay of 5.421010862427522e-17 ms, which is basically 0 in programming languages with 16 decimal digit precision. \$\endgroup\$ Commented Jan 11, 2019 at 12:37
  • 1
    \$\begingroup\$ I do like the challenge in general, though (and have prepared a solution if it goes live), so +1 from me. :) \$\endgroup\$ Commented Jan 11, 2019 at 12:37
  • \$\begingroup\$ @KevinCruijssen: You would have to either sleep for 1/1 and then print 1 initially, or sleep 1/2 seconds then print 2 initially, i.e. you must include the term associated with the delay. As for the second point, I would consider that to be starting with 1 and having the delay imposed before printing the `nth term, so it is valid. \$\endgroup\$
    – Neil A.
    Commented Jan 11, 2019 at 15:26
  • \$\begingroup\$ @BMO: Should I instead make the sleep duration something like n^2, (2^n)/n, or another function that could make this interesting? (I want to avoid using simply n to make it a bit more interesting). I would change the title of the challenge appropriately, of course. \$\endgroup\$
    – Neil A.
    Commented Jan 11, 2019 at 15:29
  • \$\begingroup\$ Choosing \$n^2\$ or even \$\frac{2^n}{n}\$ changes things massively. I like the idea of having less time for more work, but: 1) You need to set a boundary, st. the mentioned problem will not occur, if a submission chooses the right approach. 2) To make it interesting, I would balance the boundary and function in a way that the last iteration isn't too easy. \$\endgroup\$ Commented Jan 11, 2019 at 17:17
  • \$\begingroup\$ A starting point (using a Unix system): Investigate how many CPU cycles a write syscall takes (let's assume \$1000\$ - I haven't checked though and it will depend a lot on the environment), assume a standard CPU clocked at \$1.5\$GHz, this gives you \$\frac{1000}{10^{9}\text{Hz}}=1\mu\text{s}\$ for a single write. A delay of \$\frac{1}{2^{31}}\$ (maximum power of two for \$\texttt{uint32}\$) is already half of that. \$\endgroup\$ Commented Jan 11, 2019 at 17:17
  • \$\begingroup\$ @BMO: I may have messed up on my specifics, but what I intended was something along the lines of: when printing 2^31, there should be a delay of 1/31 seconds, not 1/(2^31). (n=the term number, not the power of two). \$\endgroup\$
    – Neil A.
    Commented Jan 11, 2019 at 17:46
  • \$\begingroup\$ Ah, I misunderstood the challenge (I screwed up, not you). Delaying for \$\frac{1}{31}\$ of a second should be easy. You will still need to add a bound though. \$\endgroup\$ Commented Jan 11, 2019 at 17:52
  • \$\begingroup\$ @BMO: Edited for clarity, limit is n=1000 (1 ms delay, should be handled by most languages fine) \$\endgroup\$
    – Neil A.
    Commented Jan 11, 2019 at 17:59
3
\$\begingroup\$

Static Code Analysis Battle!

Your programs will play a friendly game of rock, paper, scissors. There's a catch though; you can not use randomness and the combatants can see each other's source code.

That is, you will write a python program that, when imported, provides a function named rps. Given two combatants, say player1.py and player2.py, the controller will import them, and execute player1.rps(player2sourceCode) and player2.rps(player1sourceCode). These should output R, P, or S. The winner is then whoever would win in rock paper scissors with those moves. If one player makes a valid move, and the other does not, that player wins. If both players make an invalid move, it is considered tie. Additionally, taking more than 1 second to move is considered an invalid move.

Here are the rules:

  1. Both the action of importing your module and your rps function should be pure functions. This means for example that you can not do the following:
    1. Use randomness or other non-deterministic code.
    2. Interfere with or receive information from the file system, I/O, peripherals, etc...
    3. Use time.sleep.
    4. Alter or access the state of the controller.
    5. Use other functions to do impure actions. For example, you can not call eval on the source code of an impure function call. An exception to this is if the only impure thing it does is interact with your program's state (i.e. it is permitted to change variables in your program's namespace). You can, however, call it on pure function call source code.
    6. Anything else that a pure function could not do.
  2. Other functions in your source code, however, may be impure.
  3. You may assume that the source code passed as an argument to rps obeys rule 1. You may not, however, assume that the rps in the passed source code is a pure function when you pass it source code that does not obey rule 1. Additionally, other functions in the module may be impure.
  4. Additionally, going into an infinite loop is perfectly fine, although if it happens when the caller calls your program, your move will be considered invalid. If the opponent calls your program and it causes them to go into an infinite loop, however, their move will be considered invalid, and vice versa.

This is , so the program that defeats the other programs wins! In particular, I will run a match between each program and each other program. The winner will be the condorcet winner if one exists. Otherwise, the result will be a tie between the Schwartz set members.

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

Classic VCS ASCII Adventure

Moved to main. Thanks everyone for your input. Happy golfing!

\$\endgroup\$
6
  • 1
    \$\begingroup\$ This seems like a nice challenge! I'm not as experienced as other people around here, but you should publish it to main. \$\endgroup\$
    – MilkyWay90
    Commented Jan 26, 2019 at 16:28
  • \$\begingroup\$ These question are likely to be asked: Can input be in decimal (some languages don't have "hex"-numbers and in other languages it's most of the time just a different literal but represents the same)? Can input be binary (maybe even as string)? Does "any character" include spaces? Is it restricted to printables only? Is returning an array of strings allowed or does it need to be a single newline-separated string? \$\endgroup\$ Commented Jan 28, 2019 at 13:27
  • \$\begingroup\$ Maybe you could add an example with both x- and y-stretch factors being negative? \$\endgroup\$ Commented Jan 28, 2019 at 13:30
  • \$\begingroup\$ @BMO thank you for your suggestions! I've updated the description to address your points. \$\endgroup\$
    – 640KB
    Commented Jan 28, 2019 at 14:41
  • \$\begingroup\$ I've clarified a few things and added some better test cases. I'll wait to get a few more up-votes before submitting it though. \$\endgroup\$
    – 640KB
    Commented Jan 28, 2019 at 17:36
  • \$\begingroup\$ Nice challenge! I've already prepared a solution in case it goes to main. Only perhaps slightly confusing part is where you use the byte-format 018H/024H in the circle example at the top, but then the format 0x18/0x24 in your test cases. I would change the 018H/024H in that first example to 0x18/0x24 as well to remain consistent across the entire challenge description. Apart from that everything is clear to me. \$\endgroup\$ Commented Jan 29, 2019 at 13:42
3
\$\begingroup\$

The Forest Game (KotH, WIP)

Summary

You have been given a space of land to plant trees in. Unfortunately, due to an administrative mix-up, so have 4 other people. You are in a competition with them to make the most money out of your trees within the next 100 years.

The map

A 10 by 10 grid, representing the area of land. Each square will be one of the following:

  • A number, 0 to 4, representing a player
  • ., representing a seed (more later)
  • i, representing a sapling
  • T, representing a tree
  • F, an ongoing fire
  • , an empty space

Actions

Actions, given by your program, are 1 or 2 characters long. The first is the type:

  • . - plant a seed, costs 1
  • i - plant a sapling, costs 10
  • F - start a fire, costs 5
  • m - move, costs 0
  • w - work, gains 1 (what you do for easy points/to do nothing)
  • - - harvest, variable gains (see below)

Anything else as the first character will result in ignored command. The second character is one of `^'<>,v., a direction, which refers to the relative location of the square on which to perform the command:

` ^ '     NW N NE
<   > --> W     E
, v .     SW S SE

For the work command, the second character need not be present, but must be one of the eight if it is. An invalid command is ignored.

Growing

Seeds become saplings, saplings trees. After 5 rounds (25 turns), a seed becomes a sapling with the probability \$\frac{8 - C}8\$ where \$C\$ is the number of nearby (diagonally or orthogonally adjacent) saplings or trees. Saplings become trees after 7 rounds, with the same probability (\$C\$ here is only trees). This is worked out from the top left, going across each row in turn, meaning that each seed/sapling growth may be affected by saplings/trees created that turn.

Value

When harvested, saplings/trees add to your score. Saplings are valued at 15, trees at 20. After every round, a tree gains 1 point of value, up to a maximum of 40 points. Seeds cannot be harvested, nor can other players' saplings/trees.

Fires

Fires spread from the point you set them to all nearby trees and saplings, unless there is a player other than you also nearby. Example:

  T          T          T          T        
  i5         i5         F5          5       
TTTTTT --> FFTTTT -->   FTTT -->    TTT
F1 ii       1 ii       1 ii       1 ii      
  i          i          i          i        

Where 1 is you and 5 is the other player. Each step represents one turn (not one round).

Tournament

Each game, you start with 15 points, and loose/gain them as described in the 'actions' and 'value' sections. The aim is to be the player with the most points at the end of 100 rounds (500 turns in total). Each game will be played 6 times, and then repeated until one player has won more than any of the others. This collection of 6+ games is a 'match'. Every two days, if there have been new players added, the players will be split up into groups of 5, padded out with simple bots of mine if necessary. The winners of each of these will be split into groups of five and the above process repeated until there is only one group of five, the winner of which is the victor!

I/O

Your submission should be a Python 3 program, with a method run defined in the global scope. This method will be called with the following parameters:

  • map_ - a list of ten lists of single character strings. This will be a deep copy of the map, each string is one of 01234.iTF, representing that square.
  • round_ - the round number
  • points - a list of integers, representing the number of points each player has, in order.
  • num - whereabouts on the points list you come, also the number representing you and where you come in the turn order.

It should output the two/one character string mentioned above.

Controller

WIP, extremely buggy

'''
Rules
---
map, 20 by 20 squares,
starts empty with randomly placed players
square can be:
' ' - empty
'1' - [0-4], player
'.' - seed
'i' - sapling
'T' - tree
'F' - flames

actions:
'm' - move
'i' - plant sapling
'.' - plant seed
'-' - harvest tree
'F' - start fire
'w' - work (dir optional and ignored)
'?' - other, nothing

each action other than move should be accompanied by
a direction, [<>^v`,'.O] = (W,E,N,S,NW,SW,NE,SE,O)

flames:
 - go out if person nearby other than starter
 - turn every nearby tree/sapling to flames, 33% each
 - go out, leave ' '

costs/bonuses:
'm' - none
'i' - -10
'.' - -1
'-' - +15 for sapling, +20 for tree + turns living max. +40
'F' - -1
'w' - +1
'?' - none

growing:
. > l - (8-nearby [lT])/8 chance, after 5 turns
l > T - (8-nearby [T])/8 chance, after 7 turns
   T+ - +1 value every turn, max. 40

every five turns, tree drops a seed in an empty nearby square
start at 10 points
game end after 100 rounds

I/O
---
'''

import random, os, time, sys


class Item(object):
    def __init__(self, x, y, game, creator=None):
        self.x = x
        self.y = y
        self.game = game
        self.creator = creator


class Flame(Item):
    def update(self, around):
        burn = []
        for i in around:
            if str(i) in map(str, range(6)):
                if str(i) != str(self.creator):
                    return
            elif str(i) in 'Ti':
                burn.append(i)
        for i in burn:
            self.game.place(Flame, i.x, i.y, self.creator)
        self.game.place(Empty, self.x, self.y)

    def __str__(self):
        return 'F'


class Seed(Item):
    def __init__(self, x, y, game, creator, count=25, _next=None):
        _next = _next or Sapling
        super(Seed, self).__init__(x, y, game, creator)
        self.counter = count
        self.creator = creator
        self.next = _next

    def update(self, around):
        self.counter -= 1
        if self.counter:
            return
        pos = sum(str(x) in 'Ti' for x in around)
        if random.randrange(8) in range(pos):
            self.game.place(Empty, self.x, self.y)
            return
        self.game.place(self.next, self.x, self.y, self.creator)

    def __str__(self):
        return '.'


class Sapling(Seed):
    def __init__(self, x, y, game, creator):
        super(Sapling, self).__init__(x, y, game, creator, 35, Tree)

    def __str__(self):
        return 'i'

    def __int__(self):
        return 15


class Tree(Item):
    def __init__(self, x, y, game, creator):
        super(Tree, self).__init__(x, y, game, creator)
        self.val = 20

    def update(self, around):
        self.val += 1
        if self.val > 40:
            self.val = 40

    def __str__(self):
        return 'T'

    def __int__(self):
        return self.val


class Empty(Item):
    def update(self, around): pass

    def __str__(self):
        return ' '


class Player(object):
    def __init__(self, x, y, name, game):
        self.game = game
        self.x = x
        self.y = y
        self.name = name
        self.around = (None,) * 8
        self.points = 15

    def update(self, around):
        self.around = around

    def command(self, text):
        text = "mv"
        if len(text) != 2:
            if len(text) != 1:
                return
            else:
                self.points += text[0] == 'w'
                return
        dirs = "`^'<p>,v." #p = placeholder
        if text[1] not in dirs:
            return
        ny = self.y + (dirs.index(text[1]) % 3) - 1
        nx = self.x + int(dirs.index(text[1]) / 3) - 1
        if (nx, ny) == (self.x, self.y):
            return
        itm = self.around["`<,^v'>.".index(text[1])]
        if text[0] == 'w':
            self.points += 1
        elif ny < 0 or nx < 0 or not itm:    #remove for wrapping
            return
        if text[0] == 'm':
            if str(itm) == ' ':
                self.game.move(self.x, self.y, nx, ny)
        elif text[0] == 'F' and self.points > 0:
            if str(itm) in 'Ti':  #never!!!
                self.game.place(Flame, nx, ny, self)
                self.points -= 1
        elif text[0] == '.' and self.points > 0:
            if str(itm) == ' ':
                print('.')
                self.game.place(Seed, nx, ny, self)
                self.points -= 1
        elif text[0] == 'l' and self.points > 9:
            if str(itm) == ' ':
                print('l')
                self.game.place(Sapling, nx, ny, self)
                self.points -= 1
        elif text[0] == '-':
            if str(itm) in 'Ti':
                if itm.creator == str(self):  #never!!
                    self.game.place(Empty, nx, ny)
                    self.points += int(itm)

    def __str__(self):
        return str(self.name)


class Game(object):
    def __init__(self, players, names, size=20):
        self.map = []
        choose = []
        self.names = names
        for x in range(size):
            self.map.append([])
            for y in range(size):
                self.map[-1].append(Empty(x, y, self))
                choose.append((x, y))
        self.players = {}
        random.shuffle(choose)
        for i in range(len(players)):
            pos = choose.pop()
            p = Player(*pos, str(i), self)
            self.players[players[i]] = p
            self.map[pos[0]][pos[1]] = p
        self.round(1)

    def round(self, number):
        for i in self.players:
            self.updatemap()
            self.turn(i, number)
            if not 'idlelib.run' in sys.modules:
                time.sleep(0.04)
                os.system('cls')
                print(' |0 1 2 3 4 5 6 7 8 9')
                print('---------------------')
                [print(str(self.map.index(i)) + '|' + ' '.join(str(j) for j in i)) for i in self.map]
        if number != 100:
            self.round(number+1)
        else:
            [print(' '.join(str(j) for j in i)) for i in self.map]
            for i in self.players:
                print(names[i], self.players[i].points, sep=': ')

    def turn(self, player, rn):
        points = []
        n = 0
        for i in self.players:
            if i == player:
                num = n
            points.append(self.players[i].points)
        text = player(map_=[x[:] for x in self.map], num=num, points=points, round_=rn)
        self.players[player].command(text)

    def place(self, item_t, x, y, creator=None):
        try:
            itm = item_t(x, y, self, creator)
            self.map[x][y] = itm
            return itm
        except IndexError:
            pass

    def move(self, ox, oy, x, y):
        try:
            self.map[x][y]
            itm = self.map[ox][oy]
            self.place(Empty, ox, oy)
            self.map[x][y] = itm
            itm.x = x
            itm.y = y
        except IndexError:
            pass

    def updatemap(self):
        for x in range(len(self.map)):
            for y in range(len(self.map[x])):
                around = []
                for rx in (-1, 0, 1):
                    for ry in (-1, 0, 1):
                        if rx or ry:
                            try:
                                around.append(self.map[x+rx][y+ry])
                            except IndexError:
                                around.append('')
                if str(self.map[x][y]).strip():
                    print(' '.join(str(i) for i in around[:3]),
                          ' '.join(str(i) for i in around[3:6]),
                          ' '.join(str(i) for i in around[6:]),
                          str(self.map[x][y]), sep='\n', end='-----')
                self.map[x][y].update(around)


import burnitall, flamingworker, hardworker, plantandwait, seedandreap
allnames = ('Burn It All', 'Flaming Worker',
            'Hard-worker', 'Plant And Wait',
            'Seed And Reap')
allplayers = (burnitall, flamingworker, hardworker, plantandwait, seedandreap)

players = []
names = {}
for i in allplayers:
    players.append(i.run)
    names[i.run] = allnames[allplayers.index(i)]
Game(players, names, 10)
input()

Game results

Nothing yet!

Sandbox

  • Any thoughts? Do you like it?
  • All numbers, rules are undecided, tell me what you think I should change.
  • I know the controller has many bugs, I posted it here to show that one is being made but it's very much not ready to use.
  • That doesn't mean I don't want bug reports, if you use it and spot one, please tell me.
  • If you don't like Python - tough. It's all I've got on my computer*1, and I don't have space for much else.

*1 I tell a lie, I have got Java, but so much fuss in implementing it for one more language? I'll think about it...

\$\endgroup\$
2
  • \$\begingroup\$ I'd recommend cutting the probability aspect of saplings growing into trees and make it a variable growth rate based on neighbors. \$\endgroup\$
    – Beefster
    Commented Apr 12, 2019 at 18:30
  • \$\begingroup\$ @Beefster Interesting. I'll think about that. \$\endgroup\$
    – Miriam
    Commented Apr 12, 2019 at 19:51
3
\$\begingroup\$

Ragtag Band of Misfits

(Guaging interest)

This is a sort of sequel to Adventurers in the Ruins, taking place in a 2D dungeon, using a multi-agent team


A group of five adventurers enters a dungeon and wants to get the best loot. There are other parties competing for loot. Each party member has different abilities, health, stamina amounts, and carry capacity. Each has independent knowledge and must exchange information via a speak action.

The dungeon is made of rooms connected on a 2D grid. A room may have 1-4 doors. Some doors may be one-way. Rooms may have treasures, monsters, and traps.

As in the prequel challenge, treasure requires bidding and all actions resolve simultaneously with a specific priority on action types.

Party members

There are five classes of characters comprising each party

  1. Quartermaster
    • 100kg carry capacity, 10 HP, 1000 stamina, 5 power
    • Can heal party members in the same room
  2. Ranger
    • 50kg carry capacity, 10 HP, 1000 stamina, 8 power
    • Can see and attack monsters in adjacent rooms that are connected by a door
  3. Fighter
    • 50kg carry capacity, 25 HP, 1000 stamina, 8 power
    • Double damage to monsters
  4. Thief
    • 30kg carry capacity, 10 HP, 1500 stamina, 5 power
    • Automatically detects booby trapped treasures and can take them without triggering the trap
    • Can steal treasure from enemy adventurers in the same room
    • Can booby trap a treasure, making it appear twice as valuable, but dealing damage to whoever picks it up.
    • Effective bid on treasures is doubled. Wins ties on treasure bids except against other thieves.
  5. Wizard
    • 20kg carry capacity, 8 HP, 1500 stamina, 4 power
    • Can communicate telepathically with any single teammate without needing to be in the same room. This is a two-way channel of communication.
    • Can telepathically visit the room a teammate is currently in, seeing its contents and doors and enabling teleportation to that room
    • Can teleport self or ally in same room to any previously visited room or the same room as any ally.
    • Can teleport any ally to the current room
    • Carried treasure does not increase cost for moving between rooms or teleporting
    • Deals half damage to monsters

Actions available to adventurers of all classes

  • Move between rooms
  • Exit the dungeon (if in the starting room)
  • Speak (can be combined with certain actions)
  • Send a message to the wizard
  • Pick up a treasure (bidding rules work the same as the first challenge)
  • Gift a treasure to another party member in the same room
  • Drop a treasure
  • Attack a monster
  • Attack a rival adventurer in the same room
  • Guard (prevent oncoming attacks and theft attempts)
  • Wait

Communication

Adventurers can communicate by speaking, which will be heard by all teammates in the same room. Speaking requires no stamina and can be combined with movement or gifting, but is limited to be a 20-character string. (Use of emojis for increased message density is fair game)

Combat

A power must be specified when attacking a monster. This cannot be higher than the adventurer's power rating. That amount of stamina will be expended and the monster will be damaged by that amount. If the monster is still alive after all attacks have resolved, the monster will then deal its damage split among all combatants that attacked that turn, minimum of 1 damage.

If adventurers are outnumbered by monsters in any room, the monsters will attack anyone attempting to pick up treasure for 1 damage each.

Defeating a monster will cause the monster to drop up to 3 treasures (typically more valuable than the others in the room) and the characters who attacked the monster that turn will level up, gaining 1 power.

Attacking a rival adventurer will deal one fifth of the damage normally dealt to monsters, but will not result in a counterattack. Attacking an adventurer who either guards or moves into another room will result in a miss. It is possible for adventurers to kill each other on the same turn since attacks resolve simultaneously.

Coding

You will write a bot for each party member. They may not share data (other than constants and libraries).

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

Battle of Wits (Where is the Poison?)


The battle of wits is a well-known scene from the Princess Bride.

Two bots will face off in a battle of wits: one poisons a wine goblet and the other chooses which to drink from (the other player drinks from the other goblet). Whoever drinks the poison loses. This will be repeated until one bot wins 20 rounds, with who poisons the goblet being randomized each time. Each match, you will be able to see the entire history of which goblet was chosen and you will also have access to the other player's decision function (Related). All submissions will be evaluated in a round-robin tournament, with ties being broken by who has the fewest losses across all games. Further ties will be resolved by who has the fewest losses to the contesting opponents. If there is a perfect intransitive relationship among three or more bots, all of them will be considered tied for first place.


This is equivalent to the matching pennies game in terms of who wins a round. The poisoner is equivalent to the penny matcher and the chooser is equivalent to the non-matcher.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ How about, to make it more interesting, let the bots read each other's source code? \$\endgroup\$
    – Jo King Mod
    Commented Apr 19, 2019 at 4:51
  • 1
    \$\begingroup\$ @JoKing ooh. That's genius! Similar to this? \$\endgroup\$
    – Beefster
    Commented Apr 19, 2019 at 6:00
3
\$\begingroup\$

Output the Visible Spectrum in RGB

Inspired by http://www.physics.sfasu.edu/astro/color/spectra.html

Light with wavelength between ~380 and 780 nanometers is considered to be within the visible spectrum. One can approximate the colors of the visible spectrum in RGB space by linearly interpolating the wavelength at specific ranges. The ranges and corresponding formulae for a wavelength wl are given below, assuming each color value is a real between 0 and 1:

  • [380-440): r = (440 - wl) / (440 - 380), g = 0, b = 1
  • [440-490): r = 0, g = (wl - 440) / (490 - 440), b = 1
  • [490-510): r = 0, g = 1, b = (510 - wl) / (510 - 490)
  • [510-580): r = (wl - 510) / (580 - 510), g = 1, b = 0
  • [580-645): r = 1, g = (645 - wl) / (645 - 580), b = 0
  • [645-780): r = 1, g = 0, b = 0

Note that in this system, the interpolation formula is cyclic with the color components, and changes sign with respect to the range maximum or minimum.

The challenge

Given an integer wavelength between 380 and 780, output the RGB value using the above interpolations.

Output may be a list of floats in [0,1] or integers between [0,255] in the format (r,g,b), or a valid RGB hex code.

This is code golf, so the shortest code in bytes wins!

Test cases

Rounding errors to within 0.01 in float format or to within 1 in integer format are acceptable.

wl=400 --> (0.29, 0.0, 0.65) or (73,0,165) or #4900A5
wl=530 --> (0.28, 1.0, 0.0)  or (72,255,0) or #48FF00
wl=640 --> (1.0, 0.07, 0.0)  or (255,19,0) or #FF1300
wl=750 --> (1.0, 0.0, 0.0)   or (255,0,0)  or #FF0000

Bonus

At extreme ranges of the visible spectrum, human perception is not as good. This can be modeled as a loss of intensity by multiplying the RGB values computed above by a factor f for specific cutoff points:

  • wl < 420: f=0.3+0.7*(wl-380)/(420-380)
  • wl > 700: f=0.3+0.7*(780-wl)/(780-700)

The total (r,g,b) including the perception factor is therefore (f*r, f*g, f*b)

\$\endgroup\$
2
  • \$\begingroup\$ I changed your post slightly; feel free to revert if you dislike my changes. \$\endgroup\$ Commented May 3, 2019 at 20:19
  • \$\begingroup\$ I also want to notify you of the fact that we have MathJax enabled, so you could TeX your equations. \$\endgroup\$ Commented May 3, 2019 at 20:22
3
\$\begingroup\$

Approximating Roots

(If you can think of a better title, then please suggest it!)

One day, when I was bored in maths class, I learned of a neat trick for solving the real cube root of a number!

Let's use the number \$79,507\$ as an example.

First, take digit in the one's place and compare it to this table:

\begin{array} {|r|r|} \hline \text{Extracted Digit} &\text{Resulting Digit} \\ \hline \text{1} &\text{1} \\ \text{2} &\text{8} \\ \text{3} &\text{7} \\ \text{4} &\text{4} \\ \text{5} &\text{5} \\ \text{6} &\text{6} \\ \text{7} &\text{3} \\ \text{8} &\text{2} \\ \text{9} &\text{9} \\ \text{0} &\text{0} \\ \hline \end{array}

In this example, the Resulting Digit will be \$3\$ since the digit in the one's place is \$7\$.

Next, remove all digits that are less than \$10^3\$:

$$ 79507 → 79 $$

Then, find the largest perfect cube that does not exceed the input:

$$ 64 < 79 $$

\$64=4^3\$, thus the next digit needed is \$4\$.

Finally, multiply the digit found in the previous step by \$10\$ and add the Resulting Digit found in the first step:

$$ 10*4+3=43 $$

Thus, the cube root of \$79,507\$ equals \$43\$.

However, there a neat quirk about this trick: it doesn't apply to only cubed numbers. In fact, it works with all \$n>1\$ where \$n\bmod2\ne0\$.

The steps mentioned above can be summed up in this generalization for an \$n\$ power:

  • Step 1) Take the digit in the one's place in the input. Compare it to the one's place digit of the \$n\$th powers of \$1\$ to \$10\$, then use the corresponding digit.

  • Step 2) Remove all digits of the input less than \$10^n\$. Compare the resulting number to the perfect powers definied in Step 1. Use the \$n\$th root of the largest perfect power less than said number.

  • Step 3) Multiply the number from Step 2 by 10 then add the number from Step 1. This will be the final result.

Task

Given two positive integers \$n\$ and \$m\$, return the \$n\$th root of \$m\$.

Input:

  • Two positive integers \$n\$ and \$m\$.

  • \$m\$ is guaranteed to be a perfect \$n\$th power of an integer.

  • \$n\$ is guaranteed to be odd and greater than \$2\$. (This method doesn't work if \$n\$ is even.)

Output:

  • The \$n\$th root of \$m\$.

Rules:

  • This is , so the fewer bytes, the better!

  • Standard I/O rules apply.

  • The output must be calculated using the aforementioned method.

  • No builtins allowed that already calculate this. A prime example being TI-BASIC's x√ command.

\$\endgroup\$
9
  • \$\begingroup\$ That's a pretty neat trick! I guess I'm not the only one who gets bored in math class. Also, I think you made an error on your test case, it says 10 x 4 + 4 rather than + 3 \$\endgroup\$
    – rydwolf
    Commented May 5, 2019 at 14:03
  • \$\begingroup\$ @RedwolfPrograms yes, I believe so! Guess my finger slipped on the keyboard \$\endgroup\$ Commented May 5, 2019 at 16:31
  • \$\begingroup\$ Is there anything else I should change about this post before I post it on main? Not sure what to call this challenge tbh \$\endgroup\$ Commented May 5, 2019 at 20:05
  • \$\begingroup\$ At the beginning of the question, it states that the method only works on perfect cubes, but it later says that it works on all odd numbers > 2. Other than that I don't see many issues, but I'd leave it here for a day or so just in case. \$\endgroup\$
    – rydwolf
    Commented May 5, 2019 at 20:09
  • \$\begingroup\$ Good point! I think that I should remove that line, as it is invalidated later on, as you said. \$\endgroup\$ Commented May 5, 2019 at 20:18
  • \$\begingroup\$ Posting to main! Let's hope that this challenge fares well. \$\endgroup\$ Commented May 7, 2019 at 13:25
  • \$\begingroup\$ "The output must be calculated using the aforementioned method" falls foul of Things to avoid: Non-observable program requirements. \$\endgroup\$ Commented May 7, 2019 at 14:18
  • \$\begingroup\$ @PeterTaylor it may not be observable directly, but the source code will be able to indicate whether the method was used or not. \$\endgroup\$ Commented May 7, 2019 at 14:25
  • \$\begingroup\$ @Tau, read the answer I linked. It explicitly addresses that point. \$\endgroup\$ Commented May 7, 2019 at 14:51
3
\$\begingroup\$

Golf my Ada arrays

Background

Ada is a programming language that is not exactly known for its terseness.

However, its array literal syntax can in theory allow for fairly terse array specifications. Here is a simple EBNF description of the array literal syntax (passable to bottlecaps.de:

array ::= positional_array | named_array
positional_array ::= expression ',' expression (',' expression)*
named_array ::= component_association (',' component_association)*
              | expression (',' expression)* ',' 'others' '=>' expression
component_association ::= discrete_choice_list '=>' expression
discrete_choice_list ::= discrete_choice ('|' discrete_choice)*
discrete_choice ::= expression ('..' expression)?

We will limit ourselves to 1-dimensional arrays of integers for simplicity. This means that we will use only integers for the expression values. Perhaps in a future challenge we could try something more advanced (like declaring variables and multidimensional arrays). You do not have to golf the integer literals.

Challenge

The goal of this challenge is to output the shortest byte-count Ada array literal for a given input array. Note that Ada arrays can start from whatever index is desired, so you can pick what you wish the starting index to be as long as each value is sequential. In this example I choose to start at 1, which is idiomatic for Ada, however you can choose to start at any other integer.

Input

Your input will consist of a list of integers, in whatever form is convenient.

Output

Your output will be a string of text representing the shortest valid Ada array literal that represents the list of input integers. You may use any starting index you wish on this array, but your choice (whatever it is) must be specified in your answer (the starting index may also be dynamic).

Do not modify the representation of the input integers, keep them in decimal format. This challenge does not cover golfing of integer values.

Examples

Here are some examples:

Simple: [1, 2, 3] -> (1,2,3)
Range: [1, 1, 1, 1, 1, 1, 1,] -> (1..7=>1)
Others: [1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1] -> (6=>2,others=>1)
Multiple Ranges: [1,1,1,1,1,2,2,2,2,2,1,1,1,1,1,2,2,2,2,2,1,1,1,1,1] -> (6..10|16..20=>2,others=>1)
Tiny Ranges: [1,1,2,2,1,1,1,1,1] -> (3|4=>2,others=>1)
Far Range: [[1]*5, [2]*100, [3]*5] -> (1..5=>1,6..105=>2,others=>3)
Alternation: [1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2,1,2] -> (1|3|5|7|9|11|13|15|17=>1,others=>2)
Big Number: [1234567890,1,1234567890] -> (2=>1,1|3=>1234567890)
Big-ish Number: [1234567,1,1234567] -> (1234567,1,1234567)

Minimum Requirements

  • Support at least 100 numbers and inputs of at least 256 numbers in length.

  • Produce the correct result for all such inputs (including putting 'others' at the end)

  • Terminate (preferably on TIO) for each of the above inputs in under a minute.

Reference Implementation

Try it online!

This implementation uses the input as its array, with each character being a number. Capital letters are special constants for large values. The program argument is the 'start index' to use.

The "code" section in the TIO link is a correct solution to the problem, while the "header" and "footer" implement the test structure.

\$\endgroup\$
6
  • \$\begingroup\$ Your syntax doesn't match the examples; although I don't know Ada, I do know VHDL (which uses the same array syntax), and I think allowing others => in a named array (like the examples do, and the syntax doesn't) is correct. As for the challenge more generally, the specification is clear but you're missing a victory condition. code-golf is our most common victory condition here because it works well for a wide range of problems; I don't see any reason why it would work badly for this one, and don't think any of the usual alternatives are better. \$\endgroup\$ Commented May 7, 2019 at 22:43
  • \$\begingroup\$ Oh, one other suggestion is that having more functionality in the reference implementation than is required in users' answers is confusing. You might want to try explaining more clearly what the linked TIO program does, and explaining it as something like "a tool to try out various inputs, supporting abbreviations for some larger inputs, and seeing what the intended output is". \$\endgroup\$ Commented May 7, 2019 at 22:50
  • \$\begingroup\$ One other thing that could improve the question: specify what sort of input the program should take (presumably a list of integers), and what sort of output the program should produce (presumably a string). You don't need to define terms like "list" and "string" precisely; people will use whatever definitions make sense for their language. You should probably say something like "for the purposes of this challenge, numbers in the output should be in decimal; you do not have to golf them", because golfing of the output integers could change their length and thus which array syntax is optimal. \$\endgroup\$ Commented May 7, 2019 at 22:53
  • \$\begingroup\$ I've added some clarifications. \$\endgroup\$
    – LambdaBeta
    Commented May 9, 2019 at 14:51
  • \$\begingroup\$ "Do not modify the representation" is a bit unclear: the language that people use might be taking input in a format other than decimal, but in that case we still want decimal in the output. Apart from that, I think everything is fine now (and that particular issue isn't unclear enough to make the question closeable, IMO, although close votes are often hard to predict). \$\endgroup\$ Commented May 13, 2019 at 16:22
  • \$\begingroup\$ I see what you mean, I'll adjust that and post it. Thanks for the help! \$\endgroup\$
    – LambdaBeta
    Commented May 13, 2019 at 16:35
3
\$\begingroup\$

Arithmetic quine

Write a quine.
Well that's not very original challenge so let's spice things up.

Challenge

Write a quine which when once or multiple times appended to itself (see Appending) then performs an arithmetic operation of your choice.
You can implement as many operations from the as you want (see Scoring, Operations)

Example:
Let's say my code were foobar. This would return foobar because it's a quine.
Now foobarfoobar would preform + operation on two input numbers.
foobarfoobarfoobar could preform a * operation.

Note: which operation you choose for whatever number of appended copies doesn't matter but you have to write it down in your answer.

Example: Your code might be 4 times appended to preform addition, or it might need to be appended 5 times. It doesn't matter as long as you write the full list of the operations you implemented and the number of concatenations needed.

Operations

The list of operations you are allowed to implement is:

Addition
Subtraction
Multiplication
Integer Division
Integer exponentiation
Integer Factorial

Scoring

score = bytes/(n_operations + 1)

Bytes mean the bytes of the initial un-appended program.

Appending

All languages (even if 2D) must be appended by simply concatenating the program two or more times.

\$\endgroup\$
15
  • \$\begingroup\$ What operations should I add or how should I make this more clear? \$\endgroup\$
    – IQuick 143
    Commented Apr 29, 2018 at 7:37
  • 2
    \$\begingroup\$ If not duplicate it be good \$\endgroup\$
    – l4m2
    Commented Apr 29, 2018 at 11:14
  • \$\begingroup\$ I expect that this would be extremely difficult. Hyperprogramming is a similar challenge with only addition, multiplication, and exponentiation where its achievability was called into question. \$\endgroup\$ Commented Apr 30, 2018 at 6:19
  • 3
    \$\begingroup\$ In my opinion, all languages should be treated equally. Otherwise there would be a lot of disputes (for example: (1) what about Cubix or Hexagony or Wumpus or Quadrefunge, where the layout is not directly rectangular but still >1D? (2) if my language is not 2D can I append horizontally? (3) Can I use a codepage where newline is a different character from \x10? ) \$\endgroup\$
    – user202729
    Commented May 2, 2018 at 12:22
  • \$\begingroup\$ Can we read our own source code, or do default loopholes and quine rules apply? \$\endgroup\$ Commented May 8, 2019 at 13:30
  • 1
    \$\begingroup\$ @EsolangingFruit I have the feeling this challenge is easier than that one though. Appending the entire source code allows you to utilize the length, whereas duplicating every character gives all kind of trouble which is harder to overcome/ignore. PS: I've prepared a solution which works with all six operations. Those operations are just examples, right? I could add more if I want to? \$\endgroup\$ Commented May 8, 2019 at 13:49
  • \$\begingroup\$ Prepared a solution with nine operations, and will add more later on. :) Looking forward seeing this go live. \$\endgroup\$ Commented May 8, 2019 at 13:57
  • \$\begingroup\$ @KevinCruijssen May I know which operations, I'll probably add them to the list \$\endgroup\$
    – IQuick 143
    Commented May 8, 2019 at 14:05
  • \$\begingroup\$ @KevinCruijssen The list was supposed to be a full list but I don't see why we couldn't expand it, also I'm considering adding a score to each operation, since some are harder to accomplish than others. \$\endgroup\$
    – IQuick 143
    Commented May 8, 2019 at 14:09
  • 1
    \$\begingroup\$ @IQuick143 Well, the ones I have right now are: addition; subtraction; multiplication; integer division; exponentiation; factorial; square; square-root; 1/n. But I could easily add more like regular division; modulo; +1; +2; -1; -2; signum; absolute difference; base-conversion to; base-conversion from; xor; bitwise-and; bitwise-or; negate; halve; double; length; etc. etc. haha ;p So maybe it's good to have a list instead of leaving the choice to everyone. ;) I would personally use add; subtract; divide; int-divide; multiply; exponent; modulo (all requiring two inputs) \$\endgroup\$ Commented May 8, 2019 at 16:48
  • 1
    \$\begingroup\$ But I'll leave the choice to you. If you want to keep the original six operators that's fine as well. (In which case I would change the sentence to "The list of operations you are allowed to implement:") \$\endgroup\$ Commented May 8, 2019 at 16:50
  • \$\begingroup\$ @KevinCruijssen I was thinking of changing the metric to score = bytes * (operations_language_can_implement - implemented_operations + 1), because some languages might not be able to handle floats for instance, what do you think? \$\endgroup\$
    – IQuick 143
    Commented May 11, 2019 at 13:46
  • \$\begingroup\$ @JoKing Thanks for the grammar help. \$\endgroup\$
    – IQuick 143
    Commented May 11, 2019 at 13:47
  • \$\begingroup\$ @IQuick143 Doesn't that give an unfair advantage to those languages? Let's say language A can and has implemented 5 operations in X+5 bytes. And language B can and has implemented 10 operations in X+10 bytes. Although both will get get 1 in the (operations_language_can_implement - implemented_operations + 1) part of your scoring, the byte-count of B is X+10, so 5 bytes higher than A's X+5, even though it implemented more operations.. I would keep the scoring as is, and have a select list of operations to implement. If a language can't handle it, it's score would be higher to reflect that. \$\endgroup\$ Commented May 13, 2019 at 9:06
  • \$\begingroup\$ And if you want to keep it with integers only, you could perhaps use the following six operation all requiring two inputs: add; subtract; int-divide; multiply; exponent; modulo? \$\endgroup\$ Commented May 13, 2019 at 9:07
3
\$\begingroup\$

Print some very large numbers

Not sure if this has been done before. Write a program that takes in a scientific format number (as two inputs, a mantissa and an exponent), and outputs a decimal representation of that number (as a string). The trick is that this must go far beyond most languages number limits.

The mantissa will always be within 1 ≤ mantissa ≤ 10 or mantissa = 0.

The exponent will always be a 32-bit signed integer.

Example:

1, 100 -> 10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

3.543235, 200 -> 354323500000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

3.3333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333, 10 -> 33333333333.333333333333333333333333333333333333333333333333333333333333333333333333333333333333333333

5.3282, -71 -> 0.000000000000000000000000000000000000000000000000000000000000000000000053282

0, 999999 -> 0
\$\endgroup\$
5
  • 3
    \$\begingroup\$ Nice challenge, but can we use our language's scientific notation, E.g. some languages don't use the +, or use a different minus? \$\endgroup\$
    – Adám
    Commented May 20, 2019 at 11:09
  • 2
    \$\begingroup\$ Maybe even allow taking mantissa and exponent as separate inputs? \$\endgroup\$
    – Adám
    Commented May 20, 2019 at 11:12
  • 1
    \$\begingroup\$ Don't forget to add some example cases with negative exponent and one with an integer mantissa. Oh, and also a 0 case. \$\endgroup\$
    – Adám
    Commented May 20, 2019 at 11:13
  • 1
    \$\begingroup\$ Will input always be in canonical format; 1≤|mantissa|<2 or mantissa=0. Can there be leading and trailing 0s in input? How about in output? \$\endgroup\$
    – Adám
    Commented May 20, 2019 at 11:15
  • 2
    \$\begingroup\$ I like the idea of taking the mantissa and exponent as seperate inputs. Then we can do away with the string parsing part of the challenge and just focus on handling big numbers (by giving the inputs as floating point numbers). \$\endgroup\$
    – Omegastick
    Commented May 21, 2019 at 1:15
1
17 18
19
20 21
162

You must log in to answer this question.

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