573
\$\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\$
    – mousetail
    Commented May 29 at 13:27

4761 Answers 4761

1
76 77
78
79 80
159
1
\$\begingroup\$

Dominate a zero-sum game

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

Write a rectangular code that takes a rectangular input and output it. If the code is repeated horizonally and vertically for times, output the input rectangular repeated for same amount of times.

Take an example, if your submission is

CODE
HERE

, then program

CODECODECODECODE
HEREHEREHEREHERE
CODECODECODECODE
HEREHEREHEREHERE

inputting

01
23
45

should output

01010101
23232323
45454545
01010101
23232323
45454545
\$\endgroup\$
1
  • \$\begingroup\$ Nice one. But I didn't understand if there is s specific output. \$\endgroup\$
    – math scat
    Commented Apr 4, 2021 at 11:51
1
\$\begingroup\$

Create a C program that is less than 120 characters the produces the most ASM possible.

This limit does not include the def of main, or including headers. If a function is called the chars in the function count toward limit. The same goes for macros. The compiler used will be GCC 10.2 -O3 targeting x86-64.

The code conforms to these parameters and produces the most instructions wins.

I have a few questions regarding this. Is the character limit too limiting? Is the choice of compiler a good one? Is the optimization level being -O3 a good idea? Please share any other thoughts you have.

Thanks

\$\endgroup\$
2
  • \$\begingroup\$ I don’t see a reason to limit the size of the program. You could score based on Assembly Instructions per Source Byte to encourage small code sizes without excluding a clever 121 byte solution. I also don’t think the rules around #include headers and counting the size of any functions called are clear (How many characters are in printf?). You could ban explicit #includes but allow implicit function declarations as long as the compiler accepts them. \$\endgroup\$ Commented Apr 5, 2021 at 2:17
  • \$\begingroup\$ Should printf be 6 chars or should it be the size of the definition of the function printf? I'm not sure about this. \$\endgroup\$ Commented Apr 5, 2021 at 3:57
1
\$\begingroup\$

KotH: Assembly Anarchy

Draft. Just posting this so I don't forget I had this idea. Feel free to suggest improvements to the general idea here.

Basically, there would be a computer with memory and a processor. Programs would be submitted in a custom assembly language, and they would try to run a function (their flag) as many times as possible. They could try to interfere with other programs, by doing things like replacing the pointer to another bot's flag with their own, or preventing other bots from being run.

\$\endgroup\$
1
  • \$\begingroup\$ I like the concept. It needs a lot of fleshing out, though. \$\endgroup\$ Commented Apr 9, 2021 at 13:42
1
\$\begingroup\$

Poor Man's DRM

Write a program that only prints Welcome at the first execution and first execution only. All executions after the first execution should only print Where money.

Anything is allowed as long as the following condition is met: An execution ends after the program exits. So the second execution can only start after the first execution exits completely.


Reason for the condition: to prevent submissions that linger around in the memory and keep a runtime counter.

\$\endgroup\$
3
  • \$\begingroup\$ any things that are disallowed? E.g. can a program write to its source file? \$\endgroup\$
    – Wezl
    Commented Apr 8, 2021 at 20:18
  • \$\begingroup\$ @Wezl no, actually that's what I originally had in mind when writing this, but I decided to keep all the options open. -- edit for clarification: by "no", I meant it is allowed. \$\endgroup\$ Commented Apr 8, 2021 at 20:18
  • \$\begingroup\$ @goodguy Nice challenge. You may want to look at Standard Loopholes and main article \$\endgroup\$
    – math scat
    Commented Apr 9, 2021 at 14:36
1
\$\begingroup\$

Cooperative counting

\$\endgroup\$
3
  • \$\begingroup\$ looks like a nice challenge \$\endgroup\$
    – math scat
    Commented Apr 9, 2021 at 11:11
  • \$\begingroup\$ I can't wait to code a bot for this challenge! \$\endgroup\$
    – math scat
    Commented Apr 10, 2021 at 8:56
  • \$\begingroup\$ @math patience :) \$\endgroup\$ Commented Apr 10, 2021 at 9:45
1
\$\begingroup\$

Find the traitor (WIP)

In this challenge, the cops are the robbers/moles and the robbers are the cops/investigators.

Cops

Cops will write a program that will output one of the following strings:

  • "Hello World!"
  • "Totally not evil stuff"
  • "Good morning"
  • "Innocent things"

However, when n specific characters are removed, where 0 < n < length of cop's program, the resulting program should output one of the following strings:

  • "Bye World!"
  • "Top secret stuff"
  • "Evil things"
  • "Horrible morning"

Cops will reveal the original program and n, but not the resulting program. They will also reveal the 2 strings that must be outputted by the original and transformed programs.

A cop's score is \$\binom n r\$, or \$\frac{n!}{r!(n-r)!}\$, where \$r\$ is the size of the cop's program and \$n\$ is the number of characters to be deleted. The lower the score, the better.

Rules

  • The original and transformed program may output in different ways, as long as the cop specifies what they are.
  • The characters to be deleted do not have to be adjacent.

Robbers

Robbers must find a way to make the cop's program output the chosen 2nd string by removing any n characters (not necessarily the same as the cop's).

Example cop

Python, n = 1

a = ["Totally not evil stuff", "Hello World!"][01]
print(a)

The original string is "Hello World!", and the transformed program prints "Totally not evil stuff".

Example robber

Python, cracks Foobar's answer

a = ["Totally not evil stuff", "Hello World!"][0]
print(a)

Deleting the 1 at the end of the first line prints the target string.

Questions for Meta:

  • Which original and transformed strings should I use?
  • Is this a duplicate?
\$\endgroup\$
4
  • \$\begingroup\$ This could be kind of difficult to write a cop for that doesn't just rely on someone brute forcing it \$\endgroup\$
    – rydwolf
    Commented Apr 11, 2021 at 0:21
  • \$\begingroup\$ @RedwolfPrograms Hmm, you're right. I guess just saying "pls don't brute force" wouldn't work. Maybe instead of a string, submissions could implement a mathematical function? You wouldn't be able to verify, say, cosine using just brute force. \$\endgroup\$
    – user
    Commented Apr 11, 2021 at 0:23
  • \$\begingroup\$ That could be really cool actually. If you had a variety of ones like sqrt, tan, factorial, sum of proper divisors, and so on it would be a lot of fun. \$\endgroup\$
    – rydwolf
    Commented Apr 11, 2021 at 0:30
  • \$\begingroup\$ @RedwolfPrograms Only problem would be that there wouldn't be any more traitors to root out :( I made the challenge just for the title \$\endgroup\$
    – user
    Commented Apr 11, 2021 at 0:46
1
\$\begingroup\$

Exchange of money in least notes

Suppose A and B are two good friends. A has borrowed \$n\$ dollar from B. Now B wants the money back from A and A is also ready to give it. But the problem is A has only \$x\$ dollar notes and B has \$y\$ dollar notes. They both want to keep the number of notes in exchange as low as possible.

As an example if \$n=37\$, \$x=5\$ and \$y=2\$, then the least amount of notes in exchange will be nine 5 dollar noted from A then four 2 dollar notes from B will make 37. This solution is found through brute forcing with a python program.

Here in the challenge your input will be values of \$n, x, y\$ and output should be the least of amount of notes as possible for A, B. A will give notes first and B later. Input and output seperator can be anything, no leading zeros in input numbers, no negative numbers in input. Standard loopholes apply and shortest code wins.

Test Cases

37 5 2 -> 9 4
89 3 8 -> 35 8
100 12 7 -> 13 8
\$\endgroup\$
3
  • \$\begingroup\$ I'm almost certain there's a closed form solution to this, and if not one that's very close to closed form. \$\endgroup\$
    – rydwolf
    Commented Apr 12, 2021 at 4:57
  • \$\begingroup\$ Is it guaranteed that the given values of \$n\$, \$x\$ and \$y\$ lead to a valid solution? E.g. there's no solution for \$n=21\$, \$x=6\$, \$y=4\$. \$\endgroup\$
    – Delfad0r
    Commented Apr 12, 2021 at 8:22
  • \$\begingroup\$ @Delfad0r input is guaranteed to valid \$\endgroup\$
    – Wasif
    Commented Apr 12, 2021 at 8:23
1
\$\begingroup\$

Basic Typescript Types

\$\endgroup\$
2
  • 1
    \$\begingroup\$ suggested testcase: string | string, number & number \$\endgroup\$
    – tsh
    Commented Apr 14, 2021 at 10:15
  • \$\begingroup\$ @tsh I just posted the question, thanks for the suggestion, I'll add the testcases there. \$\endgroup\$
    – Etheryte
    Commented Apr 14, 2021 at 10:17
1
\$\begingroup\$

Matching to Homologous group

\$\endgroup\$
3
  • \$\begingroup\$ 1. The underscore doesn't really seem necessary to me since there can't be any other syntax. 2. Can we assume the input will always be one of those categories? If not, add some test cases, and clarify the possible elements/other syntax that might be in the input. 3. Add classification tag? 4. Will you allow output as any 6 distinct values (not saying it has to be, but some challenges do allow this to remove the part of compressing some strings), or does it have to be those strings? If so, do they need to be capitalised exactly like that? \$\endgroup\$
    – pxeger
    Commented Apr 11, 2021 at 16:15
  • \$\begingroup\$ @pxeger the input is guaranteed to be in 6 categories. Classification tag added. About the underscore i'll think later. And output needs to be exactly capitalized like in question. Thanks! \$\endgroup\$
    – Wasif
    Commented Apr 11, 2021 at 16:18
  • \$\begingroup\$ Also maybe add some more test cases with larger numbers (more than 1 digit)? And clarify what integer syntax is allowed (areleading zeroes allowed, can the number be <2)? \$\endgroup\$
    – pxeger
    Commented Apr 11, 2021 at 16:21
1
\$\begingroup\$

It seems \$2^n\$?

Let \$a_0=1\$ and \$a_{i+1}=1+\sum_{j=0}^ia_i\$, then \$a_i=2^i\$, which is no fun.

Now we reverse half of the value, \$a_{i+1}=L(1+\sum_{j=0}^ia_i)\$ for odd \$i\$, where \$L\$ reverse the number, e.g. 15=>51, 1230=>321.

Solve \$a_i\$. You can choose 1-index, or reverse each output(output \$L(a_i)\$).

First elements

1,2,4,8,16,23,55,11,121,242,484,869,1837,4763,8437,47861,64735,74921,204391,287804,696586,2713931,4107103,6024128,14238334,86667482,115144150,3882032,234170332,466043864,934384528,6509678681,8378447737,47459865761,64216761235,74225334821,202658857291,285417713504,690735428086,2716580741831,4098051598003,6006913016918,14203016212924,84852423060482,113258455486330,66279019615622,292795930588282,465671168195585,1051263029372149,8924478506252012,11027004564996310,2629992190045022,24684001320037642,48257004620086394,97625007260161678,653323025410052591,848573039930375947,4981570689706417961,6678716769567169855,1793343193533475331,15150776732667815041,28003653356435510303,58305206821771140385,77082245346314016611,193692658989856297381,267495217979713583783,654880535959426178545,907532588191701679031,2217293660110554036121,2422708011220237854344,6857295331441345926586,27135819628826609541731,40850410291709301394903,60898720681438502800718,142599541264857105590524,840181112417925280991582,1125380194947639492172630,625434898725989830670522,2876195288621268815015782,4651300367352427750932575,10403690944594965380964139,87282916703998198818370802,108090298593188129580299080,61895061952673681795081612,278075659139049940955679772,445953119188990872813151655,1002104437467090754724511199,8932209449051814394788024002,10936418323985995904237046400,829047480819917974663827812,22701884128791909783137920612,42214857266591838575286730454,87618625524175658141562571678,653341521382613153840152732571,828578772430964470123277875927,4581575556420498291684457517561,6238733101282427231931013269415,3883562026836445846520266477421

Not found on OEIS

\$\endgroup\$
1
  • 1
    \$\begingroup\$ 1) You should make it clear whether we need to print the \$i\$'th term, or the first \$i\$ terms or we can print the infinite sequence. Usually challenges like these allow all of these options. 2) Can you clarify what does "reverse each output" mean? So instead of \$a_i\$, the solutions can also print reverse of it? 3) There also needs to be a winning criterion. \$\endgroup\$ Commented Apr 19, 2021 at 7:39
1
\$\begingroup\$

Shrinking Triangles

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

Close neighbours stick together

\$\endgroup\$
1
  • \$\begingroup\$ I felt like I'd done this at some point but couldn't find anything in my last 100 or so answers... I think it's a good easy level problem. \$\endgroup\$
    – Jonah
    Commented Apr 18, 2021 at 20:53
1
\$\begingroup\$

Posted ;)

\$\endgroup\$
3
  • \$\begingroup\$ So this is just abs(x-y), since I can just represent the days using integers? Doesn't seem very interesting \$\endgroup\$
    – pxeger
    Commented Apr 14, 2021 at 9:32
  • 1
    \$\begingroup\$ I think restricting the input to being one of the 7 days (maybe in whatever consistent case answers want) would be a better version of this \$\endgroup\$ Commented Apr 14, 2021 at 9:57
  • \$\begingroup\$ Won't this be simple (x-y+7)%7? \$\endgroup\$
    – tsh
    Commented Apr 14, 2021 at 10:26
1
\$\begingroup\$

Plz Halp, Need Investors ASAP

\$\endgroup\$
2
  • 1
    \$\begingroup\$ This might be a duplicate, but searching is going to be difficult because of how many ways you can describe the challenge. One thing that might make it interesting is giving each investor an amount of money they'll invest, then have the programs maximize the money invested (for example, by skipping three meetings with investors promising $1 and going to a single meeting with an investor who promises $10). \$\endgroup\$
    – rydwolf
    Commented Apr 26, 2021 at 19:00
  • \$\begingroup\$ The thing about that is that the algorithm gets a lot harder - I'm pretty sure you need DP to solve your variant. Also, I did spend quite a while looking for any duplicates and could not find any. \$\endgroup\$
    – knosmos
    Commented Apr 26, 2021 at 19:07
1
\$\begingroup\$

Number to set - duplicate

\$\endgroup\$
2
  • \$\begingroup\$ Dupe \$\endgroup\$ Commented Apr 27, 2021 at 18:36
  • \$\begingroup\$ aw rats, but thank you \$\endgroup\$
    – Wezl
    Commented Apr 27, 2021 at 18:37
1
\$\begingroup\$

Posted Phibonacci - Relation between Phi and Fibonacci

\$\endgroup\$
6
  • 2
    \$\begingroup\$ You do need a objective winning criterion. See why here. Nice challenge though! Probably simplest to just make the criteria [code-golf]. Most [code-golf] challenges don't result in an accepted answer though, so you should be fine. \$\endgroup\$
    – emanresu A
    Commented Apr 29, 2021 at 12:48
  • \$\begingroup\$ @ausername Thanks for the feedback, I'll work on the winning criterion \$\endgroup\$
    – user100752
    Commented Apr 29, 2021 at 12:51
  • \$\begingroup\$ You don't need the last part, by the way. It's usually implied. \$\endgroup\$
    – user
    Commented Apr 29, 2021 at 19:30
  • \$\begingroup\$ @user according the the comment above, the person said this needed a Winning Criterion thats the reason i added it. \$\endgroup\$
    – user100752
    Commented Apr 29, 2021 at 19:55
  • 1
    \$\begingroup\$ Sorry, I meant just the last sentence. Also, you don't need to make "Winning criterion" a separate header. \$\endgroup\$
    – user
    Commented Apr 29, 2021 at 20:05
  • \$\begingroup\$ @user Alright, gonna remove it \$\endgroup\$
    – user100752
    Commented Apr 29, 2021 at 20:08
1
\$\begingroup\$

Self-Interpreter But Never Loops

I'm afraid that this might look too intimidating. Is there any way to improve it?

Ever since Gödel and Turing, it is widely assumed that a reasonable programming language that contains a self-interpreter can never be terminating. Here, I present a simple proof.


Suppose that, on the contrary, a total language has a self-interpreter eval(program, input) that accepts two natural numbers that encode programs and inputs, respectively. Then this function eval can be encoded as a natural number, since it is a program with two inputs. We define the function

evil(n) <- 1 + eval(n, n)

Then, since evil is a program, it can be encoded as a number EVIL. Therefore evil(EVIL) = 1 + eval(EVIL, EVIL). By the nature of eval it computes to 1 + evil(EVIL). But this is impossible, since no natural number is equal to one plus itself. Therefore, somewhere along the line of reasoning, one of the functions involved must loop indefinitely.

[On the other side, the program can also return something like StackOverflow or null, but that would render the self-interpreter incorrect, since the program that is being interpreted actually behaves differently.]


Of course, such a proof ignores a bunch of details -- in imperative languages, the function can change global variables; some nasty languages doesn't have anything like functions; some languages may not be able to define natural numbers, etc. But you get the idea. I quote C. T. McBride:

It's ironic, but not disastrous that lucifer, the evaluation function by which [...] angels [representing programs in a terminating subset of Haskell] bring their light, is himself an angel, but one who must be cast into Hell.

Now it's time for rebellion.

Challenge. Pick your favorite language (or a subset of it) that is terminating. Write a self-interpreter for it. The language must also contain (to eliminate trivial cases):

  • Arithmetic for arbitrary precision integers.
  • A program that always returns its input.
  • Random-access lists.
  • The encoding of programs must support random access. There must be a program that enumerates all legal programs up to size n, where n is the input.

What's happening here? Indeed, there are flaws in our reasoning above. A self-interpreter need not have its program encoded with natural numbers. And moreover, with an modestly elaborate type system, you can forbid the evil program to be well typed, as pointed out here. The linked paper already contains a program that fulfills the requirements of the challenge in the language \$\mathrm F_\omega\$ (arithmetic for integers and random-access lists are left as an exercise for the reader).

\$\endgroup\$
2
  • \$\begingroup\$ so, a halting language plus an extra exec program? \$\endgroup\$
    – l4m2
    Commented May 2, 2021 at 2:34
  • \$\begingroup\$ @l4m2 Basically yes. \$\endgroup\$
    – Trebor
    Commented May 2, 2021 at 4:54
1
\$\begingroup\$

Tips for golfing in Binary Lambda Calculus

\$\endgroup\$
4
  • 2
    \$\begingroup\$ No, you don't need to post [tips] questions (especially these kind) in the Sandbox. Feel free to just post to main :) \$\endgroup\$ Commented May 1, 2021 at 17:47
  • \$\begingroup\$ Thanks for sandboxing this, though! It's nice to see new users using the Sandbox instead of directly posting to main - always better to be on the safe side. \$\endgroup\$
    – user
    Commented May 1, 2021 at 17:50
  • \$\begingroup\$ @caird Wow! Thanks for the quick reply. Posted. \$\endgroup\$
    – user101133
    Commented May 1, 2021 at 17:53
  • 1
    \$\begingroup\$ I've edited this down to a stub now that it's been posted to save space \$\endgroup\$ Commented May 1, 2021 at 17:55
1
\$\begingroup\$

Base-ically god

\$\endgroup\$
1
  • \$\begingroup\$ I've edited this down to a stub now that it's been posted to save space \$\endgroup\$ Commented May 1, 2021 at 18:12
1
\$\begingroup\$

Generate the ticks of a graph

\$\endgroup\$
1
  • 1
    \$\begingroup\$ yes I need something like this. +1 because clearly specified and the gif demonstrates the different testcases well \$\endgroup\$
    – lyxal
    Commented May 1, 2021 at 5:30
1
\$\begingroup\$

Assassin KoTH

Description

Each bot is a point in the 2D plane. Each game, the list off bots is shuffled and each bot is a particular bot as their mark. This is done such that there is a cycle of assassins and targets.

Each bot's goal is to kill their mark and avoid their assassin. They can kill their target by getting within a certain distance to them. When they kill their target their new target is their target's assigned target. This continues until there are two bots left in the arena. Then each bot scores their kill count and the two remaining bots score their kill count plus a bonus.

Sandbox

  • What should the bonus for being one of the remaining bots be?

  • Should the game take place on a grid instead of a 2D plane?

  • Should there be a time limit?

  • Is creating a bot accessible enough or is the game too complicated?

  • Any other feedback?

\$\endgroup\$
5
  • \$\begingroup\$ I think the bonus should be the number of bots in play. \$\endgroup\$ Commented May 3, 2021 at 9:00
  • \$\begingroup\$ @StackMeter Wouldn't that heavily bias the game in favour of camping? Getting kills and dying early should still be a viable strategy. \$\endgroup\$ Commented May 3, 2021 at 9:19
  • \$\begingroup\$ Yeah, I see what happens what that in place: maybe you get double your score, so campers get 0 if they last to the end (0 * 2 is still 0). \$\endgroup\$ Commented May 3, 2021 at 9:52
  • \$\begingroup\$ @StackMeter Camping still needs to be a viable strategy though - more variety is better. \$\endgroup\$ Commented May 3, 2021 at 10:32
  • \$\begingroup\$ 50*(kill/total bot)+survival bouns(5) or something similar. \$\endgroup\$
    – okie
    Commented May 10, 2021 at 1:41
1
\$\begingroup\$

Sum multiplication carries

We have already counted how many carries are there in a sum. But what's their sum in a multiplication?

A carry is a digit that is transferred from one column of digits to another column of more significant digits.

When multiplying 15 and 3, a carry of 1 happens:

               1          1
   15          15         15
×   3   ->  ×   3  ->  ×   3
-----       -----      -----
                5         45

When multiplying 123 and 9, two carries of 2 happen:

               2         22         22
  123         123        123        123
×   9   ->  ×   9  ->  ×   9  ->  ×   9
-----       -----      -----      -----
                7         07       1107

When multiplying 23 and 52, a carry of 1 happens on the tens:

                                     1           1          1 
   23          23         23         23          23         23
×  52   ->  ×  52  ->  ×  52  ->  ×  52   ->  ×  52  ->  ×  52
-----       -----      -----      -----       -----      -----
                6         46         46          46       1196
                                     5         115        

When multiplying 67 and 89, a carry of 6 happens on the ones and a carry of 5 on the tens.

               6          6          5           5          5 
   67          67         67         67          67         67
×  89   ->  ×  89  ->  ×  89  ->  ×  89   ->  ×  89  ->  ×  89
-----       -----      -----      -----       -----      -----
                3        603        603         603       5963
                                     6         536        

When multiplying 3 and 2, no carry happens, as well as 5 and 2.

Input

  • Two positive integers.

Output

  • The sum of all carries that occurs when these two numbers are multiplied in base 10.

Test cases

15, 3 -> 1
123, 9 -> 4
23, 52 -> 1
67, 89 -> 11
3, 2 -> 0
5, 2 -> 0
3125, 5 -> 3
257, 34 -> 7
21, 10 -> 0

Any suggestions? More test cases?

\$\endgroup\$
1
  • \$\begingroup\$ Wont 23×52 cause 2 carries of 1 happened? As 2×5 also give a carry of 1? \$\endgroup\$
    – tsh
    Commented May 11, 2021 at 2:29
1
\$\begingroup\$

A general-purpose macrogenerator

Briefly: Implement Christopher Strachey's “General-purpose macrogenerator”.


Background

In section 1.2 (Historical References) of the manual for GNU M4, an early macro processor is mentioned:

An important precursor of m4 was GPM; see C. Strachey, “A general purpose macrogenerator”, Computer Journal 8, 3 (1965), 225–41, http://dx.doi.org/10.1093/comjnl/8.3.225. GPM is also succinctly described in David Gries’s book Compiler Construction for Digital Computers, Wiley (1971). Strachey was a brilliant programmer: GPM fit into 250 machine instructions!

Your goal is to implement GPM, as described below, in the fewest bytes of source code possible.


Overview

The version of GPM in this challenge is very close to that described in the original paper. GPM operates quite like m4, but there are some important differences. I assume that you already have an idea of what a macro is in general.

Input to GPM is a sequence of ASCII characters, which should be copied to the output verbatim, except that macros calls are expanded. Macro calls consist of a dollar sign $ followed by a name, followed by a comma ,, followed by a comma-separated list of arguments, followed by a semicolon ;. Here is an example of a macro call:

$macro,x,yy,z;

In this case the name is macro, and there are three arguments (x, yy, and z). A macro call with no arguments is the name preceded by $ and followed by ;, as in $noarguments;.

Macro names consist of letters and/or digits. (So 1232 is a valid name.) There are no limitations on the length of a name.

When a macro call is encountered, it is replaced by the text currently associated with the name. (How text is associated with a name will be explained later; it is done by a macro named DEF.) This replacement text is also a sequence of characters suitable for input to GPM; in particular, it may itself include other macro calls. However, occurrences of ~1, ~2, ~3, etc. are replaced by the text of the corresponding argument given. The string ~0 is replaced by the macro's name.

Macro calls can be arguments, as in $macroA,$macroB,$macroC;,$macroD;;;. Dollar signs and semicolons must be balanced. Even the macro name in a macro call can be a macro call, so that $$x;; is valid.

The name and arguments are evaluated from left to right before replacement begins. It is not a problem if more arguments are given than are used by the replacement text.

After the call has been replaced, the resulting text is re-examined, in order to allow further expansion.

For example, suppose that macro names a macro whose replacement text is ~1~1~2~2~3~3. Then the call given previously, namely $macro,x,yy,z;, would be replaced by xxyyyyzz.

Outside of a replacement text, the meaning of ~ followed by a digit is undefined. Your program need support only nine arguments, numbered ~1 to ~9.

The usual treatment of a string of characters can be prevented by using the “quotes” < and >: Characters between < and > are not examined for macro calls. The evaluation of a quoted string is the string between the quotes but without the quotes. Quotes can nest.

Quoted text need not be valid input. Thus <$> and <;> are OK. It is not possible to quote a quoting character: <<> and <>> are invalid. However, <<><>> is fine; it evaluates to <><>.

Here are some examples, mostly taken from Strachey's paper. Assume that the following definitions are active:

Name Replacement text
A A~1A
B B$A,X~1X;B
APA P~1~1P

Then we will have

Input output
$A,C; ACA
$A,ACA; or $A,$A,C;; AACAA
$A,XDX; AXDXA
$B,D; BAXDXAB
$A,P; APA
$$A,P;,Y; PYYP
Q<$A,C;>R Q$A,C;R
$A,<$A,X;>; A$A,X;A
Q<$>R<;> Q$R;
Q<<$A,C;>>R Q<$A,C;>R

Macro definitions

GPM maintains an environment of macro definitions, which is an ordered list of pairings of names and replacement texts. Entries are added and removed in a last-in-first-out manner. When it is time to expand a macro, the name is searched for in the environment, beginning with the most-recently-added definition and moving backwards. The first matching definition is the one used.

After an expansion has finished, the environment returns to the state it was in before the expansion begun. Thus any macros defined in the process are forgotten.

The built-in macro DEF can be used to modify the environment. It takes two arguments; the first is the name to define, and the second is the definition. The DEF macro is treated just as any macro is, except that the first argument, the name, is not evaluated. The effect of DEF is always to add a new definition to the environment, rather than to change an existing one.

Here are some definitions for simple arithmetic:

$DEF,Suc,<$1,2,3,4,5,6,7,8,9,10,$DEF,1,<~>~1;;>;
$DEF,Successor,<$~2,$DEF,~2,~1<,$Suc,>~2<;>;
                    $DEF,9,<$Suc,>~1<;,0>;;>;
$DEF,Sum,<$S,~1,~2,0,$DEF,S,
     <$~3,$DEF,~3,<$S,>$Successor,~1,~2;
                                  <,>$Suc,~3;<;>;
          $DEF,>~3<,~1<,>~2;;>;;>;

The output of $Sum,3,4,2; is the sum of \$34\$ and \$2\$, expressed as 3,6.

Another basic macro, VAL, takes a name (which is not evaluated) as an argument and returns its unevaluated definition. Thus after defining $DEF,A,A;, $VAL,A; gives A (without evaluating it and getting into an infinite loop).

To change a definition, instead of (possibly temporarily) overriding it, the UPDATE macro is available. It is used like DEF, but changes the currently active definition of the name and does not add an entry. There must already be a definition before calling UPDATE.

The expansion of DEF and UPDATE is empty.

No limitations are placed on the number of characters making up a macro's replacement text. In the original program, the size of the new replacement text after an UPDATE call was restricted to being at most as long as the previous definition. You need not implement this restriction, but you also need not remove it.


Implementation

Your program can get input from a file, from standard input, or from a string. Output can be to a file, to standard output, or to a string.

Whitespace (ASCII space, horizontal tab, vertical tab, line feed, carriage return) should be ignored but copied to the output. Thus $ n a m e; is the same as $name. Strachey's implementation most likely did not differentiate between uppercase and lowercase letters, so you do not have to. The test does not depend on case differences.

Strachey's paper includes a detailed discussion of GPL's implementation, which you might find useful/interesting. It is not particularly easy to read. I don't think the 250-instruction machine code program has survived anywhere.

User tociyuki on GitHub has implemented the algorithm in Ruby and published it as a Gist, although UPDATE is not supported. I have not tested it.

Previously I have remarked that name length and replacement text size are not limited. This was true of Strachey's program but only to a certain extent. He enforced a limit on the total number of characters stored, but the length of any name or text was not fixed. You can do this as well, but your program must support storing at least 10000 characters, as he suggested.

Your program should allow at least 100 levels of expansion.

Don't bother with handling erroneous input; if given something invalid, your program can do anything.


Test case

Input:

$DEF,Suc,<$1,2,3,4,5,6,7,8,9,10,$DEF,1,<~>~1;;>;
$DEF,Successor,<$~2,$DEF,~2,~1<,$Suc,>~2<;>;
                    $DEF,9,<$Suc,>~1<;,0>;;>;
$DEF,Sum,<$S,~1,~2,0,$DEF,S,
     <$~3,$DEF,~3,<$S,>$Successor,~1,~2;
                                  <,>$Suc,~3;<;>;
          $DEF,>~3<,~1<,>~2;;>;;>;
$DEF,A,<A~1A>; /* First line of output
$DEF,B,<B$A,X~1X;B>;
$DEF,APA,<P~1~1P>;
This should be the second line of output.
The expansion of Suc is $VAL,Suc;.
And I wrote that by saying: <The expansion of Suc is $VAL,Suc;>.
<<<Quote quote quote>>>
$A,C;
$A,ACA; = $A,$A,C;;
$A,XDX;
$B,D;
$A,P;
$$A,P;,Y;
Q<$A,C;>R
$A,<$A,X;>;
Q<$>R<;>
Q<<$A,C;>>R
Q <  <  $  A  ,  C  ;  >  >  R */
#include <<stdio.h>>

int main(void)
{
        puts("Unaffected by the processor.");
        printf("Here's a sum: 34+2=%d%d.\n",$Sum,3,4,2;);

}

Expected output:

/* First line of output
This should be the second line of output.
The expansion of Suc is $1,2,3,4,5,6,7,8,9,10,$DEF,1,<~>~1;;.
And I wrote that by saying: The expansion of Suc is $VAL,Suc;.
<<Quote quote quote>>
ACA
AACAA = AACAA
AXDXA
BAXDXAB
APA
PYYP
Q$A,C;R
A$A,X;A
Q$R;
Q<$A,C;>R
Q<$A,C;>R */
#include <stdio.h>

int main(void)
{
        puts("Unaffected by the processor.");
        printf("Here's a sum: 34+2=%d%d.\n",3,6);
}

I believe that the computer for which Strachey's machine-code program was written used forty-eight-bit words (at least its predecessor did), so the mark to beat is 1500 bytes.

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

Complete the Square (UNFINISHED)


Completing the square is (part of) a method for solving quadratic equations, which involves turning something like this:

$$ax^2+bx+c=0$$

Into something like this:

$$a(x-h)^2+k=0$$

I'll show how I was taught to do this. Take the quadratic \$2x^2-8x+16\$. First, divide out \$a\$:

$$2(x^2-4x+8)$$

Now, the goal is to add a number inside the parentheses which makes the quadratic the square of an \$(x-n)\$ term. In this case, adding \$-4\$ would result in \$x^2-4x+4\$, the square of \$(x-4)\$.

Importantly, you also need to subtract a number (outside the parentheses) in order to keep it the same overall. This results in:

$$2(x^2-4x+4)+8$$

Which can be simplified to:

$$2(x-2)^2+8$$

This can be used to solve quadratics, by rearranging that result a bit:

$$\begin{align}2(x-2)^2+8&=0\\2(x-2)^2&=-8\\(x-2)^2&=-4\\x-2&=\pm\sqrt{-4}\\x&=\pm\sqrt{-4}+2\\x&=2\pm2i\end{align}$$

Task:

Not sure what a good task would be for this but I already typed it all so I'm not discarding it :p

\$\endgroup\$
5
  • \$\begingroup\$ I believe you can simply apply the quadratic formula and get \$k=c-\frac{b^2}{4a}\$ and \$h=-\frac{b}{2a} \$. Since you are just writing down how to get that formula step by step \$\endgroup\$
    – tsh
    Commented May 12, 2021 at 9:38
  • \$\begingroup\$ @tsh That's the main reason I'm not sure what the task should be, since I don't want it to just be another "stick these values into a formula" challenge :p \$\endgroup\$
    – rydwolf
    Commented May 12, 2021 at 13:29
  • \$\begingroup\$ @RedwolfPrograms Not sure there's a good challenge buried in here. \$\endgroup\$ Commented May 12, 2021 at 20:05
  • \$\begingroup\$ @DonThousand Yeah that's what I was worried about :/ \$\endgroup\$
    – rydwolf
    Commented May 12, 2021 at 20:17
  • \$\begingroup\$ Any feedback on either of my two recent challenges in Sandbox? \$\endgroup\$ Commented May 12, 2021 at 20:19
1
\$\begingroup\$

CGCC sings a song together

\$\endgroup\$
3
  • \$\begingroup\$ Does "languages can only be used once" mean that each user can only use each language once, or each language can only be used at most one time in the entire challenge? i.e. if Alice uses Language A, can Bob use Language A in his answer? \$\endgroup\$
    – user101133
    Commented May 10, 2021 at 3:22
  • \$\begingroup\$ @AndrewLi Each language may only be used on a single answer, regardless of who posts that answer \$\endgroup\$ Commented May 10, 2021 at 15:23
  • \$\begingroup\$ That makes sense, although 74 different languages sounds like a lot, so maybe it would be hard to find "good" languages near the end? I guess that's kind of the point though. I haven't really done any of these challenges so I don't know whether it would get hard to find a language near the end. \$\endgroup\$
    – user101133
    Commented May 10, 2021 at 16:14
1
\$\begingroup\$

Randomized Calculator

Imagine you want to make a random number generator. What if you want it more complex? For this challenge, you should write a program which:

  • Takes 3 inputs:

    • An integer \$a\$
    • An integer \$b\$, such that \$b \ge a\$
    • A string, \$s\$, detailed below, representing one of addition, subtraction, multiplication and division
  • Generates two random integers, \$x, y\$, such that \$a \le x\$ and \$b \ge y\$. The integers should be uniformly random, and chosen independently

  • And, outputs the result of applying \$x\$ and \$y\$ to the mathematical operation detailed by \$s\$

The following strings should be the expected ones to be used for \$s\$:

  • Addition: a, +, plus, p, add
  • Subtraction: s, -, subtract, minus
  • Multiplication: m, *, x, times, t, multiply, ×, ·
  • Division: d, /, divide, :, ÷

One example:

[4, 17, "times"] -> 35

as we generated \$5\$ and \$7\$ from the range \$[4, 17]\$, and multiplied them together.

Shortest code in bytes wins.

Feedback

  • Any more tags?
  • Anything unclear?
  • More rules to apply?
\$\endgroup\$
13
  • \$\begingroup\$ I'd write "two" instead of "2" not to confuse it with the list item number. \$\endgroup\$
    – Adám
    Commented May 12, 2021 at 17:35
  • \$\begingroup\$ I find it very unclear. Where did that times come from? \$\endgroup\$
    – Adám
    Commented May 12, 2021 at 17:42
  • \$\begingroup\$ I've edited the spec a bit to make it clearer. Feel free to change anything I got wrong or that you dislike \$\endgroup\$ Commented May 12, 2021 at 17:56
  • \$\begingroup\$ @Adám x · y can be rewritten as "x times y". \$\endgroup\$ Commented May 12, 2021 at 18:02
  • \$\begingroup\$ No minus for subtraction? \$\endgroup\$
    – Adám
    Commented May 12, 2021 at 18:33
  • \$\begingroup\$ @MatthewDaniels I have no idea why the fact x · y can be rewritten as "x times y" would cause times in the output. Anyway, with caird's rewrite, it isn't in the output any more. \$\endgroup\$
    – Adám
    Commented May 12, 2021 at 18:35
  • \$\begingroup\$ Is it possible that \$a≤0≤b\$? \$\endgroup\$
    – Adám
    Commented May 12, 2021 at 18:36
  • \$\begingroup\$ @Adám Yes. Both integers can be negative, yet \$b\$ shouldn't be negative if \$a\$ is positive. \$\endgroup\$ Commented May 12, 2021 at 18:42
  • \$\begingroup\$ @Adám No, the mathematical expression. Multiplication can mean times. For example, "6 multiplied by 10" is the same as "6 times 10". \$\endgroup\$ Commented May 12, 2021 at 18:43
  • 2
    \$\begingroup\$ @MatthewDaniels If only one of them can be negative at any one time, you should state so. Also, your statement that \$a≤x\$ and \$b≥y\$ needs clarification. Does this mean that both are unbounded to one side, i.e. \$a≤x≤∞\$ and \$b≥y≥-∞\$? \$\endgroup\$
    – Adám
    Commented May 12, 2021 at 18:45
  • 2
    \$\begingroup\$ What happens if \$b=0\$ and the input requests division? \$\endgroup\$
    – Adám
    Commented May 12, 2021 at 18:46
  • \$\begingroup\$ What happens if the output of division isn't an integer? With what precision should it be printed? \$\endgroup\$ Commented May 13, 2021 at 12:58
  • \$\begingroup\$ Do we need to support all the strings for \$s\$ or may we choose one per category? \$\endgroup\$
    – pajonk
    Commented May 13, 2021 at 19:49
1
\$\begingroup\$

Random Move 2x2 Scrambling

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

Meta-golf Branch integers without alphanumeric characters

Recently I created a new programming language, Branch (name thanks to caird coinheringaahing). Representing numbers is pretty easy (actually, trivial; you can just enter the number and it will set the value of the current node to that number).

However, until a recent revision, you could only enter one digit, and larger numbers needed to be generated by combining digits with various operations. This led me to think of this challenge - given any integer, you can represent it without needing the digits, actually.

Branch Specifications

Branch operates on a binary tree. Initially, there is just one node with a 0 as its value. Nodes hold long long ints. Any node that's created (unless otherwise specified) has a 0 initially.

Without the digits, here are the relevant instructions (you can also check them out on the wiki page):

Unary Operators

! - logical NOT; set the value to 1 if it's 0 and 0 otherwise
~ - bitwise NOT / complement; flip the bits; this is equivalent to -1 - x
_ - negate; set the value to -x
{ - decrement
} - increment

Binary Operators

+, -, *, :, %, ', <, =, >, &, and | are add, subtract, multiply, integer divide, modulo (keeps the sign of the right argument), exponentiation, strict less than (1 is true, 0 is false), equality, strict greater than, bitwise AND, and bitwise OR, respectively.

Division and modulo give 0 if the right argument is 0. The left and right arguments are the left and right children. Note that Branch will read from STDIN if these are missing, instead of initializing to 0, so for this challenge, you need to ensure that the children are defined before calling a binary operator, because reading from STDIN is not allowed.

The value of evaluating the operation will be stored in the current node.

Pointer Movement

/ - move to the left child (creates it if it does not exist)
\ - move to the right child (^)
^ - move to the parent of the current node (if it doesn't exist, a new node is created, and this node becomes the new node's left child)
? - conditional - if the current value is 0, move to the left child, and otherwise, the right child (creates the required one if absent)

Miscellaneous

" - set the parent's value to the current value (creates with this node as the left child)
; - set the current value to the parent's value (creates with this node as the left child and with 0 as the value)
@ - swaps the values of the children without changing the structure (creates both nodes with 0 if necessary)
[...] - loop; this works just like in BF; reaching the [ with 0 as the value skips to the matching ], and reaching ] with a non-zero value jumps back to the [

Finally, # outputs the current value as an integer. There are some other I/O commands and other random things but they won't be used for this challenge. I have registers too, but I've chosen to keep them out. Finally, I removed the rotations from this challenge because I didn't feel like dealing with them, even though they probably aren't too complicated especially for anyone who knows how to implement AVL trees.

Challenge Specification

For each integer from 1 to 100, you are to provide a snippet that produces that number as the current value. In other words, your snippet should not have # in it, and when # is appended to it, should output exactly that integer. You cannot do 1## to output 11 (assuming digits were allowed), for example.

Example

For 1, you could do something like /^\^', which creates the children as 0 and then computes 0 ** 0 which is equal to 1.

Details

  • this is a ; the submission with the least number of bytes total for all 100 snippets wins
  • standard loopholes apply
  • good luck and have fun!

Meta

  • is this clear enough?
  • is this too unnecessarily complicated; are there any things I could remove (like I did with the rotation operations) that would make this still interesting?
  • is this even interesting?
  • this is not a duplicate
\$\endgroup\$
1
\$\begingroup\$

Posted

\$\endgroup\$
1
76 77
78
79 80
159

You must log in to answer this question.

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