481
\$\begingroup\$

What is the Sandbox?

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

To post to the Sandbox, scroll to the bottom of this page or click on the "Add Proposal" link below, 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. 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, replace the post here with a link to the challenge and delete it.

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

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

Add Proposal

Search the Sandbox

Browse your pending proposals

Get the Sandbox Viewer to view the sandbox more easily

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

| |
\$\endgroup\$

2877 Answers 2877

1
22 23
24
25 26
96
2
\$\begingroup\$

Draw an American flag for any amount of states

The flag of the United States of America goes by many names. The Stars and Stripes. Old Glory. The Last Known Non-Erotic Usage Of The Verb 'To Spangle'.

It is also one of the few flags semi-regularly updated. The red and white stripes represent the 13 original states, but one more star has been added to the blue canton for every state that joined the union later. This last happened in 1960, when Hawaii got in. Flag designs with 51 stars are already waiting for when Puerto Rico or Washington D.C. are made states, but this vexillologist is lazy. You are to make a program that can draw the flag with any number of stars desired!

Specification

Here's a neat image of the official, government-standardised design for the current U.S. flag: flag design

Disregard the contents of the canton for now. Your program must draw a flag that adheres to only the ratios I give here:

  • A (the height of the flag) = 1
  • B (the width of the flag) = 19/10
  • C (the height of the canton) = 7/13
  • D (the width of the canton) = 19/25
  • L (the height of any stripe) = 1/13

Because raster solutions are not exact and this flag is commonly misdrawn anyway, there's tolerance of 2% for every ratio, taking the flag height as the base.

Furthermore, the correct colours must be used.

  • Every odd-numbered stripe must be this shade (hex): #B22234
  • The blue canton must be in this shade: #3C3B6E
  • Every even-numbered stripe, and every star, must be in this shade: #FFFFFF

Conversions to other colour coordinate systems can be found on the wiki page as well.

Stars

Your program must takes as input any integer between 0 and 200, and draw that number of stars within the canton. The following rules apply.

  • Each star must have five outer points and be five-fold rotationally symmetrical.
  • Each star must be the same size.
  • The bounding circles of stars may overlap, but the surface of the stars itself may not overlap.
  • The bounding circles of the stars may go outside the canton, but the surface of the stars itself may not go outside the canton.
  • I don't want solutions that just place every star on the same line; that would leave a lot of blue canton untouched, which would be a waste. So, as a rule, the combined surface area of the bounding circles of every star in the canton must be at least 20% of the surface area of the canton.

    Since overlapping bounding circles still count, you get a formula for the minimum width w of the star, where a is the area of the canton and n the number of stars: formula. See here for how it's derived.

Other specifications

There's no minimum or maximum size for your output image, though I recommend something that will allow 200 stars to fit but still be demonstrably star-shaped. When they are only a few pixels high, it becomes hard to argue that they have the required amount of points. Obviously, for vector solutions any size is permissible.

This is , so the smallest program wins!

Test cases

Because I gave no specific arrangement of the stars (you may arrange them however you want), there is an infinite number of correct and incorrect solutions for each number of stars. These are just examples of valid and invalid solutions:

Valid:

valid1

Invalid (stars too small):

invalid1

Valid:

valid2

Invalid (stars of unequal size, going out of the canton):

invalid2

Invalid (stars have too many points, stripes have wrong colours, colours are the wrong hue, proportions are wrong):

invalid3

Sandbox

Do I need more test cases? Any other feedback?

| |
\$\endgroup\$
  • 2
    \$\begingroup\$ If you really want to allow 0 as an input, you'll need an exception to the rule that the combined areas of the bounding circle must be at least 20% of the area of the canton. (If there aren't any stars, there aren't any bounding circles, so the combined areas would be 0.) \$\endgroup\$ – Mitchell Spector Mar 7 at 2:19
  • 4
    \$\begingroup\$ I know it's less thematic, but maybe the task could be just to draw the canton? Arranging and drawing the stars is the interesting part, whereas the stripes aren't changing, so in terms of golfing the stripes seem somewhat extraneous. I guess you could also have the number of stripes be variable. \$\endgroup\$ – xnor Mar 7 at 17:40
2
\$\begingroup\$

Excessively complicated Game of Life

In the excessively complicated version of the Game of Life, the world is a \$W \times H\$ square torus with a grid of squares. Each square has a rulestring attached to it - by default, B/S. Each square has a dead or alive cell in it. Each alive cell is controlled by a player. Every turn, if there is not an alive cell in a square, it is born iff the part between B and / contains the number of alive neighbours. Every turn, if there is an alive cell in a square, it survives iff the part after S contains the number of alive neighbours. Cells are considered adjacent if they have a common edge or a corner. A cell is not adjacent with itself. Cells controlled by other players also count as alive neighbours.

For example, normal Conway's Game of Life cells have the B3/S23 rulestring: cells are born if they have exactly 3 alive neighbours, and survive if they have 2 or 3.

Each player starts with a B/S012345678 cell, placed uniformly randomly.

Each cell knows a 3x3 array of numbers from \$-1\$ to \$1\$, representing adjacent cells (including self). \$1\$ in it means an ally cell, \$0\$ means a dead cell, and \$-1\$ means an enemy cell, and a 3x3 array of rulestrings for adjacent cells.

Every turn, every cell can alter one bit of the rulestring of any adjacent square (including its own) - that is, remove or add a number from it (or, alternatively, it can do nothing).

When cells are born, the player they belong to is chosen semi-randomly: the odds of the cell being assigned to a player are proportional to the number of cells they contributed to the cell's birth.

A player is eliminated when all their cells die. When \$N\$ turns passed, or when only one player remains, the game ends. A full point is distributed between all remaining players proportionally to the number of cells they control (dead cells don't count).

Clarifications

  • Rulestrings are attached to squares, not to cells. When a cell dies, the rulestring on its square is not changed.
  • No cell can be born with zero alive adjacent cells (that is, rulestrings cannot start with B0).
  • When multiple cells attempt to alter the same bit in a rulestring, it is only affected once.

Challenge

Define a pure function \$(nearbyStates, nearbyRules)\to(\Delta x, \Delta y, index)\$ to be used as the algorithm for your cells. To do nothing, output an index of 0.

Otherwise, an index of 1 corresponds to toggling B1, 2 to B2 and so on until B8, the index 9 is skipped, then an index of 10 corresponds to toggling S0, 11 to S1 and so on until S8.

Winning criterion

\$X\$ games are run, and the leaderboard is formed by sorting participants by the total number of points.

This is , so whoever wins wins!

Sandbox stuff

  • Is this a good idea?
  • Is the description of the game clear?

I think I decided that the language for submissions will be Javascript. Now I have to write a controller.

Besides the obvious Javascript option, I am considering C++ with a Javascript engine (probably V8). This can multiply the performance by \$\%NUMBER\_OF\_PROCESSORS\% \cdot \frac{cppPerformance}{jsPerformance} \cdot \frac{myC++skill}{myJSskill}\$, which can be quite large. Unfortunately, that might also muptiply the challenge's popularity by \$\frac{webBrowserLoadingSpeed}{programInstallationSpeed}\$, which can be quite small! Would that be a good idea?

| |
\$\endgroup\$
  • \$\begingroup\$ Disclaimer: I'm biased in both categories. Language: Leaning towards JS, especially since this challenge seems to be of the "hack around and see what works" type, and I believe browser-based ones shine here the most. Python seems to be popular as well, but AFAIK it's usually used for challenges that don't need rich visualization. Other languages, like Java, .NET, C++, etc., can also be considered, of course (higher performance)... Orientation: Removing orientation does seem to be a good fit. It increases the amount of interactions that can happen between any two entries. \$\endgroup\$ – Alion Mar 26 at 18:31
  • \$\begingroup\$ Regarding C++: You can have your cake and eat it too. Have you heard of Wasm and Web Workers? This combination lets you get near-native peformance along with multithreading all in the browser. \$\endgroup\$ – Alion Mar 29 at 13:40
  • \$\begingroup\$ Note that improving controller performance only gets you so far. You're gonna have to go the Formic route and cache entry responses in some smart way to extract all the potential of C++. \$\endgroup\$ – Alion Mar 29 at 13:48
  • \$\begingroup\$ @Alion I include "caching in some smart way" in "improving controller performance". I have also considered using Emscripten (and started using it, starting with the renderer first, because I randomly decided so) but then I got worried because I thought calling JS from WASM and WASM from JS is going to be too slow. After reading the comment, I googled and it turned out Emscripten has multithreading. I guess I'll continue now. \$\endgroup\$ – my pronoun is monicareinstate Mar 29 at 13:50
  • \$\begingroup\$ I'd like to see a good C/C++ KoTH. I'm always excluded from them because I don't know any languages that they're in. \$\endgroup\$ – S.S. Anne Apr 1 at 20:15
  • \$\begingroup\$ @SSAnne I do not understand your comment. Are you proposing a C/C++ KoTH, or are you stating that they cannot be good because you don't know these languages? \$\endgroup\$ – my pronoun is monicareinstate Apr 2 at 0:09
2
\$\begingroup\$

Are these the same time?

Context

When asked about the time (i.e. hours and minutes), people naturally reply with any one of a given set of fairly common sentences:

  • (A) it is M past H
  • (B) it is M to H
  • (C) it is H minus M

Where M above refers to some amount of minutes and H to some amount of hours. Concrete corresponding examples, all referring to the time 3:40 pm:

  • (A) it is 40 past 3
  • (B) it is 20 to 4
  • (C) it is 4 minus 20

Task

Given two of these sentences, output a Truthy value if they represent the same time and a Falsy value if they do not.

Input

Your input will be two sentences of the above, where references to minutes will always be rounded to the nearest multiple of 5 (i.e. the minutes will always be one of 5, 10, 15, 20, ..., 50, 55.

Because all sentences start with "it is " you may ommit that from your input sentences.

Output

A Truthy value if the two times are the same, a Falsy value otherwise.

Test cases

Here is a sample program for checking the test cases.

Sandbox

Should the minutes and hours in the input com as integers instead of English words?

| |
\$\endgroup\$
  • \$\begingroup\$ Interesting challenge. Yes, the minutes and hours in the input should come as integers. Otherwise, this becomes a chameleon challenge that appears to be about parsing relation words, but actually is about parsing English numbers. I think you can make the challenge more interesting by adding (D) it is H M. Please address 1) how to distinguish AM/PM or that we don't need to, 2) how to deal with roll-overs like "5 to 0", and 3) if H and M have upper and lower bounds. \$\endgroup\$ – Adám Apr 1 at 6:29
  • \$\begingroup\$ I kid you not, I have never heard any one call it "H minus M". Still, I agree with @Adám that y'all need to ensure that input and output formats are what I like to call "reasonable and convenient", with extra emphasis on the "convenient" part. \$\endgroup\$ – Lyxal Apr 1 at 6:52
  • 1
    \$\begingroup\$ @Lyxal Me neither. But actually, that can be fixed by changing "minus" to "in", as in "4 in 20 [minutes]" \$\endgroup\$ – Adám Apr 1 at 6:55
  • \$\begingroup\$ An alternative you might consider to checking if two sentences represent equal times, is to have code take just one and produce any "canonical form" of it, such that the canonical form can be anything where two inputs give the same canonical form if and only if they are equal. \$\endgroup\$ – xnor Apr 1 at 9:15
  • \$\begingroup\$ @petStorm thanks for your edit but I would prefer if you did not edit any reference programs into my sandboxed posts (you may comment with a TIO link) nor edited the challenge to cope with the feedback I get from commenters. The feedback is very good and I will take care of it, but I prefer to do it myself so I can do the changes I see necessary: e.g. if I am accepting hours and minutes as integers, I no longer want the minutes to be in the set 5, 10, 15, ..., 55. \$\endgroup\$ – RGS Apr 1 at 11:48
2
\$\begingroup\$

Similar Numbers

posted

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

Compactify the input

Posted

| |
\$\endgroup\$
  • \$\begingroup\$ Off topic: BASIC programmers were often recommended to name their variables this way. \$\endgroup\$ – Third-party 'Chef' Apr 8 at 14:26
  • \$\begingroup\$ I agree that it's better to compress a single word instead. \$\endgroup\$ – Third-party 'Chef' Apr 8 at 14:26
  • \$\begingroup\$ hmm ok, I'll do that \$\endgroup\$ – Command Master Apr 8 at 17:42
  • \$\begingroup\$ I think the mention of compression and natural language is misleading, since it leads the reader to expect some compression based on the statistical properties of text. \$\endgroup\$ – xnor Apr 8 at 18:36
  • \$\begingroup\$ hmm ok, do you have an idea for a better name? \$\endgroup\$ – Command Master Apr 9 at 4:53
  • \$\begingroup\$ Do you think Compactify the name is a good idea? \$\endgroup\$ – Third-party 'Chef' Apr 9 at 8:44
  • \$\begingroup\$ Related. \$\endgroup\$ – Third-party 'Chef' Apr 9 at 8:46
  • \$\begingroup\$ yes, I like that name, maybe Compactify the input though? As it doesn't have to be a name \$\endgroup\$ – Command Master Apr 9 at 9:02
  • 2
    \$\begingroup\$ I like Compactify the input \$\endgroup\$ – xnor Apr 10 at 12:12
  • \$\begingroup\$ Just an FYI, the regex \B[aeiou] matches each character to be removed. You may receive a lot of answers that are basically just that. \$\endgroup\$ – FryAmTheEggman Apr 12 at 5:10
2
\$\begingroup\$

Symmetrical difference

Post'd.

| |
\$\endgroup\$
  • 2
    \$\begingroup\$ If a language supports it, can we take output and input as sets instead of a lists? \$\endgroup\$ – Chas Brown Apr 9 at 8:08
2
\$\begingroup\$

Compress Numbers

Write two programs, a compressor and a decompressor.

The compressor

  • The compressor will accept a sequence of integers of any value from 0 to 263-1, expressed in any convenient format.
  • You may specify the required format as long as any arbitrary sequence of integers in the required range may be expressed in this format.
  • Behaviour is undefined for any input that does not conform to your required format.
  • The output will be a self contained sequence of bytes.

The decompressor

  • The input will be an unmodified sequence of bytes produced by a valid input to the compressor.
  • Behaviour is undefined for any other sequences of bytes.
  • The output will be the same input to the compressor program that produced the provided sequence of bytes.

Judging

The winning entry will be the valid entry that produces the smallest intermediate sequence of bytes for a sequence of integers that will be produced by the question setter that will be revealed after some number of entries have been submitted and only entries submitted prior to that reveal will be eligible to win.

This sequence will be generated by joining these following sequences into a single sequence and then randomly shuffling that single sequence.

  • 1000 repetitions of the same randomly selected number from 0 to 9.
  • 1000 repetitions of the same randomly selected number from 262 to 263-1.
  • For each x in (8, 16, 32, 63):
    • 1000 random numbers from 0 to 2x-1.

The question setter will answer the challenge with GZIP/GUNZIP at the highest compression setting with no additional processing. If that entry wins, the glory of winning will belong to the authors of GZIP.

Tie-Breaker

If two or more entries produce produce byte sequences of the same size, the following criteria will decide the winner:

  1. If one of those entries is the GZIP entry posted by the question setter, that entry will win.
  2. The entry with the highest voting score wins.
  3. The entry posted first wins.
| |
\$\endgroup\$
2
\$\begingroup\$

Vampire Bats

TwilightSparkle needs help controlling COVID-19 in Equestria.

The bats are spreading the virus in the APL orchard. The orchard is an N×M rectangle of APL trees and the bats are on some of the trees.

The "Asdfjklio" spell can be casted to travel through a specified path starts on a bat and ends on a bat and destroy every bats it reaches. Asdfjklio can only move horizontally or vertically.

Your task is to output how many paths are there to destroy all of the bats.

They crossed the line, it's time to fight them back!

This is , so shortest code wins.

An example

Suppose there are two bats on respective grids, where X stands for the bats and . stands for empty spaces:

.X
X.

The Asdfjklio spell can travel in any path specified, although it has to start with a bat grid and end with a bat grid.

So there are 4 possible ways to destroy all the bats:

>>| ^| v|<<|
^ |>>|<<|v |

Sandbox

  • Is this task a dupe? If so I would change it to other (less interesting) candidates.
  • Input format?
| |
\$\endgroup\$
  • 2
    \$\begingroup\$ 0 paths, because there are no bats in Equestria! \$\endgroup\$ – Third-party 'Chef' Apr 28 at 2:36
  • \$\begingroup\$ @petStorm Okay. How do I clarify the question? \$\endgroup\$ – HighlyRadioactive Apr 28 at 2:38
  • \$\begingroup\$ So it is about counting all paths that starts and ends with a bat, and goes through every single bat on the grid, not visiting any grid cell twice, right? Do we count all paths regardless of the path lengths (e.g. if the grid is XX\n.., the U-shaped path does count too)? What if there is only one bat or no bats? \$\endgroup\$ – Bubbler Apr 28 at 3:26
  • \$\begingroup\$ If you have problem describing the I/O format, look for existing challenges on main that have similar kind of I/O. As it involves a 2D grid, checking out grid will help. \$\endgroup\$ – Bubbler Apr 28 at 3:28
  • \$\begingroup\$ @Bubbler Yep, regardless of the path length. \$\endgroup\$ – HighlyRadioactive Apr 28 at 3:58
  • \$\begingroup\$ I wonder whether is this NP-hard (and, if so, what related problems exist). \$\endgroup\$ – my pronoun is monicareinstate May 1 at 2:27
2
\$\begingroup\$

Posted on the main site.

| |
\$\endgroup\$
  • \$\begingroup\$ I don't think it's a dupe. Post it. \$\endgroup\$ – HighlyRadioactive Apr 27 at 0:02
2
\$\begingroup\$

Help, I've mixed my week up!

My dog ate my calendar, and now my days are all mixed up. I tried putting it back together, but I keep mixing up the days of the week! I need some help putting my calendar back together, with the days in the correct order.

And since I need my calendar put together as fast as possible, don't waste my time by sending me superfluous bytes. The fewer bytes I have to read, the better!

Input

The days of the week, in any order. Input can be taken as a list of strings, or a space separated string, or any reasonable way of representing 7 strings (one for each day of the week).

The strings themselves are all capitalized, as weekdays should be, so the exact strings are:

Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
Sunday

Output

The days of the week, in sorted order (Monday - Sunday). Output can be as a list of strings, or printed with some delimiter.

Disclaimer

Note that this is a challenge, with the added benefit of being able to use the input to shorten your code. You are not required to use the input if you don't want to.

Examples

To see example input and output, you can consult this python script.

For the sandbox

If there are any issues with the input/output specification, or if anything is unclear, please leave a comment.

Tags:

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ You cannot use 6 tags, and this still needs [code-golf]. Otherwise this seems to be a nice challenge. (I can see a 4-6 Jelly solution by sort-nth permutation though) \$\endgroup\$ – my pronoun is monicareinstate Apr 28 at 1:03
  • \$\begingroup\$ @mypronounismonicareinstate I forgot about the code-golf tag, but of course it should be there. I have my own solution in MathGolf (not quite 4 bytes), but I'm interested in different approaches. \$\endgroup\$ – maxb Apr 28 at 6:19
2
\$\begingroup\$

Integers in cosine

Posted

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ I might be completely wrong, but doesn't \$\sin(x) = -\cos(x+\frac{\pi}2)\$? \$\endgroup\$ – my pronoun is monicareinstate May 3 at 4:25
  • \$\begingroup\$ You are right, it's either -cos or -k \$\endgroup\$ – Gábor Fekete May 3 at 9:51
  • \$\begingroup\$ I think the question would be clearer if you stated that \$\sin(a) = -\cos[a+(4m+1)\frac{\pi}{2}]\$ for integer \$m\$. Also, the sentence 'Instead of pi/2 we could use integers that are near the actual value of sin(a)' is not correct: \$|\sin(a)|\le1\$. I guess you mean values of \$k\$ that are close to \$(4m+1)\frac{\pi}{2}\$ for some \$m\$. But in that case, \$k=14\$ is better than \$k=11\$ for 2 digits. (I haven't checked all 2-digit values.) \$\endgroup\$ – Dingus May 4 at 0:39
  • \$\begingroup\$ I based my challenge on this blog post: iquilezles.org/blog/?p=4760 It's for reducing coding in shader live coding session mostly. I calculated myself the closest values and |cos(33)| is much bigger than |cos(11)| so I changed that and the 5 digit one, but the other values are minimal. \$\endgroup\$ – Gábor Fekete May 4 at 8:36
  • \$\begingroup\$ You seem to be seeking integer values of \$k\$ for which \$|\cos(k)|\$ is minimal. That's a very different question from finding values of \$k\$ such that \$\sin(a)\approx-\cos(a+k)\$, which is the question you've actually posted here and what the blog post describes (with missing minus signs). \$\endgroup\$ – Dingus May 4 at 9:44
  • \$\begingroup\$ yeah sorry, I got confused how those values got calculated, let me rephrase the challenge then \$\endgroup\$ – Gábor Fekete May 4 at 15:45
  • 1
    \$\begingroup\$ Thanks for the edits. This looks better now, though I'd suggest using MathJax (\\\$ delimiters) for the maths. What is the scoring/winning criterion for this challenge? (Is it code-golf? fastest-code?) \$\endgroup\$ – Dingus May 4 at 23:10
  • 1
    \$\begingroup\$ Almost there... but you have \$\pi\$ in the wrong place. It should be in the numerator: \$\frac{(4m+1)\pi}{2}\$. \$\endgroup\$ – Dingus May 5 at 23:20
  • \$\begingroup\$ Thanks, this is my first challenge and I haven't used latex in a while so every help is appreciated :) \$\endgroup\$ – Gábor Fekete May 6 at 10:23
2
\$\begingroup\$

Bilibili AV/BV Code Conversion

| |
\$\endgroup\$
  • \$\begingroup\$ Can I share part of the two functions? (though it likely make them search) \$\endgroup\$ – l4m2 May 14 at 16:53
  • \$\begingroup\$ I would say no, because the two functions should be independent. I will clarify this in the requirements. You may have identical parts in both function, but they will be double-counted. \$\endgroup\$ – Shieru Asakoto May 15 at 1:11
  • \$\begingroup\$ Oh I meant each code should work even without the code from the other. Hope this will be clear enough for the requirement \$\endgroup\$ – Shieru Asakoto May 15 at 1:19
  • \$\begingroup\$ Consider deleting this post, as the challenge is already on main \$\endgroup\$ – RGS May 20 at 16:50
2
\$\begingroup\$

Minimise my List of Error Codes

SANDBOX - One Option for a Challenge

Given a set of error codes, formed of letters (A-Z) and numbers (0-9), output a string that represents the set of error codes in a concise format, as follows:

  • Where two or more error codes share some first characters, there is no need to repeat those characters in the output
  • Individual errors in the output are comma-separated (or in separate array indices, if preferred)

e.g:

  • E1,E2 -> E1,2
  • E1,W1 -> E1,W1
  • ERR001, ERR002, ERR101, WAR001 -> ERR001,2,101,WAR001 or WAR001,ERR001,2,101
  • WARN001, ERR001 -> WARN001,ERR001
  • EAR001, ERR001 -> EAR001,RR001
  • E001, E001 -> E001,
  • A, B, C01, D002 -> A,B,C01,D002
  • D002, DC01, DC0A, DC0B -> D002,C01,A,B or DC01,A,B,002 or DC0A,B,1,002etc.

Basically, when decoding, each character after the comma replaces the characters at the end of the previous error code.

SANDBOX - Alternative Challenge?

Decode a string of error codes, as per the above format, to extract the individual list of error codes again

SANDBOX - Questions

I know the spec is incomplete above - this is a placeholder for when I have time to write a better spec.

Is this an interesting challenge? Which of the two options would work best? Or could it be the sum of the two (encoder and decoder)?

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

Inspired by Draw this planar graph.

Your input represents an ascending sequence, e.g. 1 2 3 4. You can require the sequence as input, or you can just input the length. The explanation assumes 1-indexing but you can use 0-indexed or even a-indexed input if you adjust the algorithm appropriately.

At each step, you can exchange any digit of value n with the digit n places to its right. So the valid second steps are 2 1 3 4 and 1 4 3 2. Eventually you want to end up at the reverse sequence 4 3 2 1, which is the only permutation that has no legal steps.

Please output all possible sequences of steps from the input sequence to its reverse.

You should support sequences of up to at least 10 elements.

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

| |
\$\endgroup\$
  • \$\begingroup\$ I really like this graph's symmetries, so +1! "All such sequences"? For n=1,2,3,4 there are 0,1,2,82 such paths through the graph; I don't think enumerating all of them will be practical even for n=6. \$\endgroup\$ – retzler May 26 at 0:26
  • \$\begingroup\$ There might be some questions that can be answered for this special graph more efficient (in terms of code-size) than general graph-searching algorithms: Shortest path, longest path? - I assume there is be a function f on the graph such that f(v)<f(w) iff there's a path from v to w (but right now I don't know) - if that's interesting enough, implement that? \$\endgroup\$ – retzler May 26 at 0:47
2
\$\begingroup\$

Reduce the entropy of the input...

Spec

Given two arguments:

  • A list containing 2 or more positive integers (from 0 to artificial limit of 2^32)
  • A positive number defining the 'entropy allowance'

Return a sublist containing elements up until the entropy allowance is used up.

For this challenge, we define 'entropy' as the difference in bits between numbers in the list; also known as the Hamming distance.

Note that no 'entropy' is used up when flipping the bits in the first number, only used when flipping subsequent bits.

Examples

Worked example (MSB...LSB), keeping the numbers low to keep things simple:

Example 1:

List: [1, 2, 3, 4, 5, 6] Allowance: 4

1 => 0000 0001 - ignore implicit change from 0, total used = 0
2 => 0000 0010 - change of 2 bits, total used = 2
3 => 0000 0011 - change of 1 bit, total used = 3 
4 => 0000 0100 - change of 3 bits, total used = 6 (would exceed allowance)
5 => 0000 0101 - change of 1 bit, total used = 7
6 => 0000 0110 - change of 2 bits, total used = 9

Output: [1, 2, 3]

Example 2:

List: [255, 0, 127, 64, 32, 100] Allowance: 23

255 => 1111 1111 - ignore implicit change from 0, total used = 0
0   => 0000 0000 - change of 8 bits, total used = 8
127 => 0111 1111 - change of 7 bit, total used = 15
64  => 0100 0100 - change of 6 bits, total used = 21
32  => 0010 0000 - change of 2 bit, total used = 23
100 => 0110 0100 - change of 2 bits, total used = 25

Output: [255, 0, 127, 64, 32]

Meta

Is this interesting enough a challenge? Is it just a chameleon (is it just the hamming distance with extra steps)? Thoughts?

If it's not shot down for being a plain, any ideas for a better title?

| |
\$\endgroup\$
  • \$\begingroup\$ Guess allowing removing arbitary least item is more interesting \$\endgroup\$ – l4m2 Jun 19 at 2:38
2
\$\begingroup\$

Find the maximum flow

Given a directed network, with a single source and a single sink, it is possible to find the maximum flow through this network, from source to sink. For example, take the below network, \$G\$:

enter image description here

Here, the source is node 0 and the sink 5. We can see, from the minimum cut-maximum flow theorem, that the maximum flow through this network is \$70\$ (given by the cut \$\{0\} / \{1, 2, 3, 4, 5\}\$)

Minimum cut-maximum flow theorem

For a network, a cut is a line that divides a network in two, with the sink and source in different halves. For the above network, one such cut, \$C\$, is \$\{0, 1, 3\} / \{2, 4, 5\}\$. Every cut has a value, which depends on which edges in the network is passes through. The above cut, \$C\$, passes through the edges \$1-2, 3-2\$ and \$3-4\$, which have the weights \$40, 45\$ and \$30\$ respectively. The value of a cut is defined, for the set of crossed edges \$S\$, as

The sum of the weights of all the edges in \$S\$ which pass from the source to the sink

Therefore, the value of \$C\$ is \$40 + 45 + 30 = 115\$ but the value of the cut \$\{0, 3\} / \{1, 2, 4, 5\}\$ would be \$20 + 45 + 30 = 95\$ (Note that \$10\$ is not included as it passes from the sink towards the source).

The minimum cut-maximum flow theorem states that

The maximum flow through a network is equal to the minimum value of all cuts in that network

The minimum cut of all the cuts in \$G\$ is \$\{0\} / \{1, 2, 3, 4, 5\}\$ which has a value of \$70\$. Therefore, the maximum flow through \$G\$ is also \$70\$.

Challenge

Write a function of full program that, when given a directed network as input, outputs the maximum flow through that network. You may, of course, use any method or algorithm to compute the maximum flow, not just the minimum cut-maximum flow theorem. This was simply included as one method.

You may take input in any convenient method or format, such as an adjacency matrix, a list of nodes and edges, etc. The input will always have 2 or more nodes, and will be a connected graph. The weights of the edges will always be natural numbers, as will the maximum flow. The output should reflect this, and can also be in any convenient method or format.

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

Test cases

Both the network and the adjacency matrix are included for each test case.

Network \$G\$ (above):

[[ 0, 20,  0, 50,  0,  0],
 [ 0,  0, 40, 10,  0,  0],
 [ 0,  0,  0,  0, 25, 25],
 [ 0,  0, 45,  0, 30,  0],
 [ 0,  0,  0,  0,  0, 50],
 [ 0,  0,  0,  0,  0,  0]] -> 70 ({0} / {1, 2, 3, 4, 5})

enter image description here

[[ 0, 10, 17,  0,  0,  0,  0],
 [ 0,  0,  0,  2, 13,  0,  0],
 [ 0,  5,  0,  0,  4,  8,  0],
 [ 0,  0,  0,  0,  0,  0, 20],
 [ 0,  0,  0, 18,  0,  0,  0],
 [ 0,  0,  0,  0,  1,  0,  7],
 [ 0,  0,  0,  0,  0,  0,  0]] -> 27 (Multiple cuts e.g. {0, 1, 2} / {3, 4, 5, 6})

enter image description here

[[ 0,  6,  2,  7,  4,  0,  0,  0],
 [ 0,  0,  0,  0,  0, 10,  0,  0],
 [ 0,  8,  0,  0,  0,  0,  9,  4],
 [ 0,  0, 11,  0,  0,  0,  0,  0],
 [ 0,  0,  0,  5,  0,  0,  0,  0],
 [ 0,  0, 13,  0,  0,  0,  0, 16],
 [ 0,  0,  0, 14,  0,  0,  0, 12],
 [ 0,  0,  0,  0,  0,  0,  0,  0]] -> 19 ({0} / {1, 2, 3, 4, 5, 6, 7})

enter image description here

[[ 0, 40, 50,  0,  0,  0,  0,  0,  0],
 [ 0,  0,  0, 30, 10,  0,  0,  0,  0],
 [ 0,  0,  0, 40,  0,  0, 10,  0,  0],
 [ 0,  0,  0,  0, 15, 10,  0,  0,  0],
 [ 0,  0,  0,  0,  0,  0,  0,  0, 20],
 [ 0,  0,  0,  0,  0,  0, 15, 20,  0],
 [ 0,  0,  0,  0,  0,  0,  0, 30,  0],
 [ 0,  0,  0,  0,  0,  0,  0,  0, 50],
 [ 0,  0,  0,  0,  0,  0,  0,  0,  0]] -> 40 ({0, 1, 2, 3, 4} / {5, 6, 7, 8})

enter image description here

[[ 0, 5, 8, 3, 3, 7, 0, 0, 0, 7],
 [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 4],
 [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 9],
 [ 0, 0, 0, 0, 0, 0, 1, 0, 0, 0],
 [ 0, 0, 0, 0, 0, 0, 0, 4, 0, 0],
 [ 0, 0, 0, 0, 0, 0, 0, 0, 6, 0],
 [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
 [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 6],
 [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 5],
 [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] -> 28 ({0, 1, 3, 5, 8} / {2, 4, 6, 7, 9})

enter image description here

[[0, 5],
 [0, 0]] -> 5

Meta

  • Is everything clear enough?
  • Is this a duplicate? I can't find anything but that doesn't rule it out
  • Any suggestions for test cases?
  • Tags are , and
  • Any further feedback?
| |
\$\endgroup\$
  • \$\begingroup\$ Related, but about optimal flow. For the most part this seems clear, though I don't think the matrices you provide are what are usually called adjacency matrices (not that this is particularly important). The only other thing I'd add is that most of your answers might be like in that related challenge - dumping this into a graph theory framework - but if you are OK with that then there's no problem. \$\endgroup\$ – FryAmTheEggman May 29 at 19:41
  • \$\begingroup\$ @FryAmTheEggman That question seems to be quite different, given the input d. I don’t see too many similarities that will make this a duplicate, but a good catch anyway. I learnt them as adjacency matrices and I can’t find any other name, so I‘ll stick with it for the moment. Otherwise, thanks! \$\endgroup\$ – caird coinheringaahing May 29 at 19:48
  • \$\begingroup\$ Mathematica, unsurprisingly, has FindMaximumFlow (although it needs a source and a target -- I don't understand what are these supposed to be here - 0 and n-1 or the vertex with no incoming edges and all vertices with no outgoing edges or something else) \$\endgroup\$ – my pronoun is monicareinstate Jun 2 at 12:00
2
\$\begingroup\$

Can this month tell the day-of-the-week?

June 2020 is a month in which June 1st corresponds to Monday, June 2nd corresponds to Tuesday, ... June 7th corresponds to Sunday. For reference, here's the cal of June 2020.

      June 2020     
Su Mo Tu We Th Fr Sa
    1  2  3  4  5  6
 7  8  9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30            

Given a year and a month in the format [year, month], output two distinct values that tell whether this month can tell the day-of-the week.

Test cases

[2020,6] -> True
[2021,2] -> True
[1929,4] -> True

[1969,1] -> False
[1997,5] -> False
[2060,1] -> False
```
| |
\$\endgroup\$
  • 4
    \$\begingroup\$ Have you considered "Does this month start on Monday?" \$\endgroup\$ – Domenico Modica Jun 6 at 14:06
2
\$\begingroup\$

Pi or Phi?

Task

Given a positive integer \$n\$ where \$n \geq 10\$ as input, determine whether \$n\$ occurs in the first 100 digits of pi (after the decimal), the first 100 digits of phi, or both.

Reference

"The first 100 digits" refers to the 100 digits after the decimal place in each number

First 100 digits of Phi:

(1.)6180339887498948482045868343656381177203091798057628621354486227052604628189024497072072041893911374

First 100 digits of Pi:

(3.)1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679

Input

  • You can assume that the input will appear in the first 100 digits of at least one of the two numbers (pi or phi)

  • Input can be taken as a number, string or any other reasonable format

  • The input number will have 2 or more digits and won't exceed 100 digits

Output

Output should be one of three consistent values:

  • One to represent that the number appears in (the first 100 digits of) Pi (but not phi)

  • Another value to represent that the number appears in (the first 100 digits of) Phi (but not pi)

  • Another value to represent that the number appears in Both

Examples

Input: 113

Output: Phi since the substring 113 appears in the first 100 digits of phi, but not in the first 100 digits of pi.


Input: 793

Output: Pi since the substring 793 appears in the first 100 digits of pi, but not in the first 100 digits of phi.


Input: 84

Output: Both since the substring 84 appears both in the first 100 digits of pi and in the first 100 digits of phi.


Test Cases

113 -> Phi
793 -> Pi
84 -> Both
618 -> Phi
141 -> Pi
86 -> Both
3398 -> Phi
3993 -> Pi
39 -> Both
374 -> Phi
679 -> Pi
35 -> Both
072 -> Phi
078 -> Pi
117 -> Both
1798057628621 -> Phi
71693993751058209 -> Pi
803 -> Both
811 -> Phi
10 -> Pi
11 -> Both
| |
\$\endgroup\$
  • \$\begingroup\$ This seems like mostly a challenge to compute digits of pi or phi, which feels like a chameleon challenge. \$\endgroup\$ – xnor Jun 8 at 7:51
  • \$\begingroup\$ I think at 100 digits I agree with xnor, but if you made the number of digits smaller I would expect some kind of compression to be a better approach. That said, I'm not sure it is then terribly different from other compression based questions since I don't think phi or pi have any exploitable structure. I do think there is a good idea somewhere in here, I'm just not sure this is it. \$\endgroup\$ – FryAmTheEggman Jun 9 at 16:33
2
\$\begingroup\$

Print the SARS-Cov-2 (COVID-19) genome

Background

As you probably learned in biology class, DNA and RNA are composed of strands of nucleotides; each nucleotide consists of a chemical called a base together with a sugar and a phosphate group. The information stored in the DNA or RNA is coded as a sequence of bases. DNA uses the bases A, C, G, and T (standing for adenine, cytosine, guanine, and thymine), while RNA uses A, C, G, and U (with uracil replacing thymine).

Challenge

The genome of SARS-Cov-2, the virus that causes COVID-19, has been fully sequenced. This genome is a sequence of 29,903 bases, each base being one of A, C, G, or U, since it's an RNA virus.

The challenge is to output that sequence using as few bytes in your program as possible (code golf). You can write either a full program or a function.

Because the names A, C, G, and U are arbitrary, you can use any 4 characters you want instead:

  • You must use exactly 4 characters (they must be pairwise distinct--two or more can't be equal).
  • Each one of the 4 characters must be a printable ASCII character in the range from '!' to '~', inclusive (ASCII 33 to 126). In particular, this does not include the space character or the newline character.
  • Each of the 4 characters you use must always represent the same one of A, C, G, and U -- no changing in the middle!

Your output should be the precise text at the following link, with A, C, G, and U replaced by whichever 4 characters you selected, and you may optionally follow the entire sequence with one or more newline characters (but no newlines or other extraneous characters at the beginning or in the middle are allowed):

Click to see the required output. (Including all 29,903 characters here would cause this to exceed a StackExchange maximum size.)

Because you can use any 4 distinct characters you want, it's acceptable to use, for example, lower-case instead of upper-case, or to use T instead of U, or to use 0123 instead of ACGU, or even to output the complementary strand (with A and U switched, and C and G switched).

Restrictions

Standard loopholes are prohibited as usual. In particular, it's not allowed to retrieve information online or from any source other than your program. You also can't use any built-in which yields genomic data or protein data (these would generally retrieve data from the Internet so they wouldn't be allowed anyway, but some languages may have this facility built in internally; use of such functionality is prohibited whether implemented internally or externally).

Verifying Your Program

I've set up a way to check that your program's output is correct. Just copy and paste your program's output into the argument in this verification program on TIO and run it.

Other Info

Some facts that may or may not be of help:

  1. There are 29,903 bases in the sequence. The counts for the individual bases are:

    • A 8954
    • C 5492
    • G 5863
    • U 9594
  2. If you simply code each of the 4 bases in 2 bits, that would get you down to 7476 bytes (plus program overhead), so any competitive answer is likely to be shorter than that.

  3. The source for the data can be found at this web page at NIH; scroll down to ORIGIN. The data is written there in lower-case letters, and 't' is used instead of 'u', apparently because DNA sequencing techniques were used.

  4. There are variant strains of SARS-Cov-2 known (the base sequences are slightly different, and the length varies a bit); I believe the one here is the first one sequenced, from Wuhan.

  5. Groups of 3 consecutive bases code for particular amino acids, so it might be useful to analyze the data in groups of 3. But there are non-coding areas where the number of bytes isn't necessarily a multiple of 3, so you may not want to just divide the data into groups of 3 starting at the beginning. If it might be useful, you can find more info on the structure of the virus RNA here (but this probably isn't needed).

Disclaimer: I'm not a biologist. If anyone has any corrections or improvements on the underlying biology (or anything else, of course), please let me know!

Happy golfing!

| |
\$\endgroup\$
  • \$\begingroup\$ Mathematica has ResourceData["Genetic Sequences for the SARS-CoV-2 Coronavirus"]. It fetches data from the internet, but somebody like me could argue that it's allowed because it's sort of built-in, so I think you should disallow coronavirus genome built-ins here. I get 7846 bytes for Bubblegum with zopfli (probably because the raw storage mode in DEFLATE always stores >=1 byte per source byte, and the other ones have various LZ77 stuff in the Huffman tree, increasing overhead for non-compressible parts, assuming I understand DEFLATE correctly) \$\endgroup\$ – my pronoun is monicareinstate Jun 7 at 13:30
  • \$\begingroup\$ @mypronounismonicareinstate Thanks for pointing that out -- I added in something to handle that. The challenge now specifically prohibits any use of built-in genomic data or protein data. This should take care of somebody somehow getting, for instance, a related virus genome and then just compressing the diff. \$\endgroup\$ – Mitchell Spector Jun 7 at 18:23
  • \$\begingroup\$ I'm sorry to say that somebody has beaten you to it. \$\endgroup\$ – Dingus Jun 10 at 1:28
  • \$\begingroup\$ @Dingus Yes, I just noticed that. I voted to close the other question as a duplicate. Posting in the Sandbox for a couple of days first is the recommended procedure, after all, so my challenge has priority. I've gone ahead and moved it to the main site. (And I think it's better though thought out, and it has a verification program -- plus it benefited from mypronounismonicareinstate's comment about Mathematica built-ins.) \$\endgroup\$ – Mitchell Spector Jun 10 at 1:43
  • \$\begingroup\$ @MitchellSpector I agree that yours is better thought out. The verification program is a great feature - obviously a bit of work went into creating it. I'll leave my answer posted pending the outcome of the close vote. Not because I don't support your claim to priority, but for the sake of my own priority in posting the first answer. \$\endgroup\$ – Dingus Jun 10 at 1:52
  • 1
    \$\begingroup\$ @Dingus -- Thank you! I have no problem with answers being posted to both challenges as long as they're still open. (I think the other one should be closed, but I also don't believe in penalizing answerers for problems with a question.) If I had let it linger in the Sandbox for a month, it would be fair game, but it's only been there for a couple of days, which is the right way to do it. \$\endgroup\$ – Mitchell Spector Jun 10 at 1:55
2
\$\begingroup\$

Posted.

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

Pwning Passwords

Alice decided to improve the security of her website by sending first five characters of an SHA-1 hash to Bob's Leaked Password Detection Service. However, she made two mistakes that let Eve decode the passwords: sending passwords over HTTP and checking the password after each character of a password is typed. Eve asked you for help in decoding the passwords, however she cannot really program, so needs your help in implementing password cracking algorithm as a computer program or function.

Eve eavesdropped the requests for following hashes from Alice.

516B9
379FC
19C2A
9D4E1
08506
F808E
A7F93
5BAA6

How could you decode this password? Well, you can brute-force all lowercase letters. In this case the only letter whose hash starts with 516B9 is p. The hash of letter p is 516B9783FCA517EECBD1D064DA2D165310B19759.

Knowing that the password starts with p, you can brute-force the second character. In this case, the only possible character is a. The hash of pa is 379FC0D5299A71AC0F171FBB5AFB262829B4E765

You can continue to brute-force letters one by one to figure out the password was password (5BAA61E4C9B93F3F0682250B6CF8331B7EE68FD8). Well, that was simple.

Not all passwords are that simple however. Consider the following requests:

4DC7C
A84FD
467D7
BD79D
12D83

First three characters of this password are simple: rxr (467D7856C648A79A096D339A2CE5FC929658967D).

With the fourth character it gets more complicated. BD79D matches for rxrf (BD79DEC8435B8BA509A25F419F31CC2ACDE2FF0A) and rxrp (BD79DC20901B11468F8369B5B0D15894F3D96A5E). There is an ambiguity, but as it turns out, it can be resolved by trying both ways. If you assume the password starts with rxrp there is no valid letters to continue with. However, if you assume the password starts with rxrf, then it's possible to append a, resulting in rxrfa (12D83D3A429CD7D64E9A532C05C2C00C35032A94), which is a valid solution.

All passwords will be composed entirely out of lowercase letters. You can assume all inputs have a solution and there are no inputs that could possibly resolve to multiple passwords (for instance ["4DC7C", "A84FD", "467D7", "BD79D"] is an invalid input because it can match both "rxrf" and "rxrp").

There are no case requirements on the input. Your program is allowed to assume the input is lowercase. Your program is allowed to assume the input is uppercase.

The program must not take longer to execute than 24 hours for a 25 characters long password.

It is allowed to use external libraries or language built-in functions for computation of SHA-1 hash.

Example Input and Output

This is a JSON.

[
  {
    "input": [
      "516B9",
      "379FC",
      "19C2A",
      "9D4E1",
      "08506",
      "F808E",
      "A7F93",
      "5BAA6"
    ],
    "output": "password"
  },
  {
    "input": [
      "07C34",
      "593B7",
      "0262F",
      "CED65",
      "23612",
      "4EF76",
      "B7A87"
    ],
    "output": "letmein"
  },
  {
    "input": [
      "84A51",
      "87DDA",
      "83F67",
      "E6FB0",
      "5157D",
      "82CD7",
      "6F655",
      "43426"
    ],
    "output": "codegolf"
  },
  {
    "input": [
      "7A81A",
      "DB3D4",
      "FE05B",
      "E7280",
      "32726",
      "30AE9",
      "2C61A",
      "A9E46",
      "15D98",
      "F780A",
      "3E949",
      "F4BF2",
      "6A5C4",
      "C4554",
      "FA2EA",
      "48A40",
      "5DD7F",
      "5284E",
      "C0B8D",
      "20D59",
      "9184C",
      "32AD9"
    ],
    "output": "onetwothreefourfivesix"
  },
  {
    "input": [
      "84A51",
      "87DDA",
      "26CA7",
      "9D925",
      "08A23",
      "BE075",
      "3179A",
      "5D904",
      "54C70",
      "47790",
      "5D3B5",
      "0E4CE",
      "004C7",
      "EC8A8",
      "131A6",
      "7F47F",
      "41BC6",
      "FCF07",
      "D62BD",
      "DD14F",
      "6A141",
      "EE184",
      "595F8",
      "9D303",
      "BFD36"
    ],
    "output": "correcthorsebatterystaple"
  },
  {
    "input": [],
    "output": ""
  },
  {
    "input": [
      "4DC7C",
      "A84FD",
      "467D7",
      "BD79D",
      "12D83"
    ],
    "output": "rxrfa"
  },
  {
    "input": [
      "4DC7C",
      "A84FD",
      "467D7",
      "BD79D",
      "7B743"
    ],
    "output": "rxrpa"
  }
]
| |
\$\endgroup\$
  • 1
    \$\begingroup\$ @FryAmTheEggman fixed \$\endgroup\$ – Konrad Borowski Jun 12 at 6:43
  • \$\begingroup\$ I wonder whether MD5 might be preferred over SHA1 - as in, more likely to exist in the language without having to load external libraries? \$\endgroup\$ – streetster Jun 18 at 16:25
  • 1
    \$\begingroup\$ Languages without a hashing builtin or library would have effectively two challenges: implementing the hash and doing the key part of the challenge. There are already challenges for MD5, SHA-1, and SHA-256 e.g. codegolf.stackexchange.com/questions/81195/implement-sha-256. I see two resolutions to this: 1. not count byte count of the hash; or 2. use a simple hash, such as the digits after the decimal point in the square root of the sum of code points \$\endgroup\$ – fireflame241 Jun 18 at 22:19
  • \$\begingroup\$ You could allow a black-box function as input that computes the SHA256 hash to make this more competitive for languages without builtins. \$\endgroup\$ – S.S. Anne Jun 24 at 2:32
2
\$\begingroup\$

Posted at Baba if you, flag is win

| |
\$\endgroup\$
  • \$\begingroup\$ There are a lot of possible rules (I think a little less than 2^9, as for each X and Y either X is Y or X is not Y, and there are 3*3=9 (X, Y) choices). Is there any documentation on what's the behavior of each rule combination? // i.e., even in this simplified version there are still a lot of fuzzy details on how the rules behaves. \$\endgroup\$ – user202729 Jun 22 at 15:04
  • \$\begingroup\$ @user202729 , Thank you for your input. I’ll take out the clause about “no non-core packages” as suggested. In terms on the moves after win, I think the easiest thing will be to say that one can assume the input sequence to end on a winning move. If a longer sequence is given, that’s undefined behaviour and the program can do whatever. \$\endgroup\$ – MarcinKonowalczyk Jun 22 at 16:55
  • \$\begingroup\$ @user202729 Finally, I admit I'm not certain what is your source of confusion. The rules work just like in the main game (with the caveat of everything is stop), and I've specified a lot of tricky cases both in this post and in the accompanying GitHub repo. Arguably, the code on GitHub specifies the problem precisely (as it is an execution of it). I've also added test cases to allow one to check the behaviour. I'm not sure what else could I do? \$\endgroup\$ – MarcinKonowalczyk Jun 22 at 17:00
2
\$\begingroup\$

Logo Pack LAPACK (Posted)

| |
\$\endgroup\$
  • 2
    \$\begingroup\$ The default for kolmogorov-complexity is that the exact, constant string must be output, so I suggest no leading spaces allowed. Some languages can't output in certain forms (e.g. printing) without a trailing newline, so I'd say it's okay (instead of "print this logo", I'd suggest saying "output this logo exactly as the following string") \$\endgroup\$ – fireflame241 Jun 27 at 7:45
2
\$\begingroup\$

Polyglot: Convert Case


Your task is to write a program that performs case conversion from plain text, and other case formats, into one of the specified formats below. Inputs will be either plain lowercase text, or one of the detailed cases below. You must remove non-alphabetic characters, except (space), _ and -, split on these, or differences in case (e.g. bA), and either join on the desired chars or join on the empty string and capitalise the first char of each word (or not the first of doing camel case). Your program must be a polyglot in at least two different languages. For example, running your code in Python 2 transforms input to snake_case, running it in JavaScript transforms to kebab-case, Ruby transforms to PascalCase and 05AB1E transforms to camelCase.

Tasks

The following case conversions must be completed:

camelCase

this is a test         thisIsATest
camelCaseTest          camelCaseTest
PascalCaseTest         pascalCaseTest
snake_case_test        snakeCaseTest
kebab-case-test        kebabCaseTest
Testing!!one!!!1!!!    testingOne1
aBCDef                 aBCDef
ABCDef                 aBCDef
a_b_c_def              aBCDef
a-b-c-def              aBCDef

Try it online!

PascalCase

this is a test         ThisIsATest
camelCaseTest          CamelCaseTest
PascalCaseTest         PascalCaseTest
snake_case_test        SnakeCaseTest
kebab-case-test        KebabCaseTest
Testing!!one!!!1!!!    TestingOne1
aBCDef                 ABCDef
ABCDef                 ABCDef
a_b_c_def              ABCDef
a-b-c-def              ABCDef

Try it online!

snake_case

this is a test         this_is_a_test
camelCaseTest          camel_case_test
PascalCaseTest         pascal_case_test
snake_case_test        snake_case_test
kebab-case-test        kebab_case_test
Testing!!one!!!1!!!    testing_one_1
aBCDef                 a_b_c_def
ABCDef                 a_b_c_def
a_b_c_def              a_b_c_def
a-b-c-def              a_b_c_def

Try it online!

UPPER_SNAKE_CASE

this is a test        THIS_IS_A_TEST
camelCaseTest         CAMEL_CASE_TEST
PascalCaseTest        PASCAL_CASE_TEST
snake_case_test       SNAKE_CASE_TEST
kebab-case-test       KEBAB_CASE_TEST
Testing!!one!!!1!!!   TESTING_ONE_1
aBCDef                A_B_C_DEF
ABCDef                A_B_C_DEF
a_b_c_def             A_B_C_DEF
a-b-c-def             A_B_C_DEF

Try it online!

kebab-case

this is a test         this-is-a-test
camelCaseTest          camel-case-test
PascalCaseTest         pascal-case-test
snake_case_test        snake-case-test
kebab-case-test        kebab-case-test
Testing!!one!!!1!!!    testing-one-1
aBCDef                 a-b-c-def
ABCDef                 a-b-c-def
a_b_c_def              a-b-c-def
a-b-c-def              a-b-c-def

Try it online!

Rules

  • Your code should produce the same output as the linked examples.
  • Entries with the most conversions win, with code length being a tie-breaker.

Questions for sandbox

  • Have I missed any other major naming schemes?
| |
\$\endgroup\$
  • \$\begingroup\$ in the example, at the start, you said python 2 and javascript, while below there are 4 conversions. Must you do all of them in a different language each? Also, do language versions (python 2 / python 3) count as different languages? \$\endgroup\$ – Command Master Jul 3 at 3:27
  • \$\begingroup\$ @CommandMaster It was just a cut down example to explain the concept of a polyglot. I'm still unsure whether it makes sense to allow two or more languages or require all four. I feel like allowing two or more would enable more elegant solutions as snake Vs kebab is the same bar the delimiter and Pascal Vs camel is the same bar leading capitalisation. What're your thoughts? \$\endgroup\$ – Dom Hastings Jul 3 at 6:28
  • \$\begingroup\$ Different language versions count as different languages (not sure of there's a relevant meta post. I'll try and look for it when I'm not on mobile.) \$\endgroup\$ – Dom Hastings Jul 3 at 6:29
  • \$\begingroup\$ If the usual 'different command-line flags count as different languages' rule applies, then is there a risk that the snake vs kebab cases could be trivially solved using the command-line flag to specify the delimiter...? \$\endgroup\$ – Dominic van Essen Jul 6 at 11:23
  • \$\begingroup\$ Yeah, I guess so. Something like Perl's -i flag could enable using $^I to be either - or _. Although then doing the same would probably be tricky and potentially still at least a little ingenious. \$\endgroup\$ – Dom Hastings Jul 6 at 12:46
  • \$\begingroup\$ "Have I missed any other major naming schemes?" Yes: Ada_Ninety_Five_Case, Title Case, and (jokingly) StRaNgEcAsE. What's wrong with UPPER_SNAKE_CASE? \$\endgroup\$ – fireflame241 Jul 9 at 5:55
  • \$\begingroup\$ @fireflame241 I think that converting back from upper snake case might be slightly more tricky than just snake case, as checking for an underscore might not be enough to see if there's more transformation necessary, if for example there was already an underscore in normal text... I could state that isn't a problem though I guess? Adding more cases might make me lean towards mandating only a minimum of two transformations required as well and changing the scoring to number of transformations with code length as a tie-breaker... Thanks again, will think on this a bit. \$\endgroup\$ – Dom Hastings Jul 9 at 6:16
  • \$\begingroup\$ If you restrict words to be composed only of letters, then you could avoid that issue, and a few others. For example, how would aB_Cd be handled? It could be snake case, where the _ separates the words, or camel case, where the _ is the start of the second word. I think right now there's too many test cases, too little explanation. \$\endgroup\$ – fireflame241 Jul 9 at 6:32
  • \$\begingroup\$ @fireflame241 Yeah, I think you're right. Ok. I'll work on this. Thanks! \$\endgroup\$ – Dom Hastings Jul 9 at 6:45
  • \$\begingroup\$ Re: flags as languages again. I was more thinking of a program 'checking' to see what flags had been used (even if they have no direct effect), and modifying its behaviour accordingly. For instance, perl -m foo + then checking whether foo is loaded. This would also be similar to language+library = different language. Worst cheat of all would be awk -v mode=1... \$\endgroup\$ – Dominic van Essen 2 days ago
  • \$\begingroup\$ Along the same lines, it would be important to specify that it isn't Ok to just run different versions of a language (which currently 'count' as different languages), and for the program to determine the version & modify its behaviour. \$\endgroup\$ – Dominic van Essen 2 days ago
  • \$\begingroup\$ I don't think it's possible to rule out different language versions for polyglot challenges, and using flags to classify as different languages might be questionable too. I guess if the answers aren't in the spirit of the task or are a little boring they'll be voted on accordingly. I'm open to more input on this though! Thank you for the feedback! \$\endgroup\$ – Dom Hastings 2 days ago
  • \$\begingroup\$ "polygot in at least two different languages" so we must write 4 programs, how can there be fewer than 4 languages? \$\endgroup\$ – qwr 2 days ago
  • \$\begingroup\$ @qwr I just amended the rules to allow 2 or more languages, you don't have to have all 5. I'm hoping this will allow some creative solutions. If I missed a reference to that I'm struggling to see it, but morning eyes... \$\endgroup\$ – Dom Hastings 2 days ago
  • \$\begingroup\$ For some reason I thought there were 4 programs. So to clarify, the minimum is two languages / two conversions? \$\endgroup\$ – qwr 2 days ago
2
\$\begingroup\$

Create a Boolean Calculator

Our boolean operators are AND, OR, XOR, NAND, NOR, XNOR and, in conjunction with one of those operators, NOT.

Our numbers are 1 and 0.

The challenge is to write a program or function that calculates the results of the input.

Input

A string, array or other input; containing alternating numbers and operators, e.g. 1 NOR 1 or 1 OR 0 AND 1. It must contain the strings for the operators, and not .+^¬||&& etc. As an exception, NOT must come directly after another operator (e.g. 0 AND NOT 1).. You can't implement NOT by itself, and you won't ever get a chain of multiple NOTs (so 1 AND NOT NOT 0 is an invalid input).

Output

Return or print a single number (1 or 0), derived using the calculation below. Invalid input can lead to any output you choose, or none.

Calculation

We're ignoring any precedence rules here - just calculate them in the order they come in (i.e. left-to-right) - as if someone was typing it into a calculator and pressing Enter after each number. NOT is the only one that might cause some difficulties with that logic, as you need to figure out what it's NOT-ing before you can apply the other operator.

Truth Tables

INPUT   OUTPUT
A   B   AND NAND OR NOR XOR XNOR
0   0    0   1   0   1   0   1
0   1    0   1   1   0   1   0
1   0    0   1   1   0   1   0
1   1    1   0   1   0   0   1

IN OUT
A  NOT A
0    1
1    0

Examples

  • 1 NOR 1 = 0
  • 1 NOR NOT 0 = 0 (equivalent to 1 NOR 1)
  • 1 NOR NOT 0 AND 1 = 0 (equivalent to 0 (from above) AND 1)
  • 1 NOR NOT 0 AND 1 OR 1 = 1 (equivalent to 0 (from above) OR 1)
  • 1 NOR NOT 0 AND 1 OR 1 XNOR 1 = 1 (equivalent to 1 (from above) XNOR 1)
  • 1 NOR NOT 0 AND 1 OR 1 XNOR 1 NAND 0 = 1 (equivalent to 1 (from above) NAND 1)
  • 1 NOR NOT 0 AND 1 OR 1 XNOR 1 NAND 0 XOR NOT 0 = 0 (equivalent to 1 (from above) XNOR NOT 0 = 1 XNOR 1 = 0)

Scoring

This is code-golf, but with a twist.

Your score is the number of bytes in your code, divided by the number of operators your code implements. Smallest score wins.

For example, if you only implement AND, your score is the number of bytes of your code.

If you implement AND, OR, XOR, NAND, NOR, XNOR, NOT (the full list of operators); then you get to divide the number of bytes by 7.

You must implement at least one operator, and you cannot implement NOT by itself; as it must be preceded by another operator.

| |
\$\endgroup\$
  • 2
    \$\begingroup\$ cat, 0 bytes, score 0: implements not because not must be directly after another operator and therefore cannot be in the input. Therefore the output is the input. \$\endgroup\$ – my pronoun is monicareinstate Jul 3 at 11:32
  • \$\begingroup\$ I would argue that you're not implementing NOT there \$\endgroup\$ – simonalexander2005 Jul 4 at 12:17
  • \$\begingroup\$ You might want to clarify that you cannot only implement the NOT operator, you must implement at least one other operator besides NOT. You should also clarify that you must implement at least one operator, otherwise someone may try to divide their score by 0. Otherwise seems like it could be an interesting challenge! \$\endgroup\$ – MrSiliconGuy Jul 6 at 0:30
  • \$\begingroup\$ Thanks, I'll clarify that \$\endgroup\$ – simonalexander2005 Jul 6 at 9:15
  • \$\begingroup\$ Just noticed you didn't specify the tags. I suggest code-challenge logic and probably parsing. Just don't tag this code-golf since it is only for the plain code length scoring. \$\endgroup\$ – Bubbler Jul 6 at 10:02
  • \$\begingroup\$ @Bubbler done, thanks \$\endgroup\$ – simonalexander2005 Jul 6 at 14:22
  • \$\begingroup\$ Instead of saying "calculate them as they come in", just say "evaluate left to right" \$\endgroup\$ – qwr 2 days ago
2
\$\begingroup\$

Laguerre Polynomials

Laguerre polynomials are solutions to Laguerre's equation, a second-order linear differential equation: \$xy''+(1-x)y'+ny=0\$. For a given value of n, the solution, y, is named \$L_n(x)\$.

The polynomials can be found without calculus using recursion:

\$L_0(x)=1\$

\$L_1(x)=1-x\$

\$L_{k+1}(x)=\frac{(2k+1-x)L_k(x)-kL_{k-1}(x)}{k+1}\$

Summation can be used to the same end:

\$L_n(x)=\sum\limits_{k=0}^{n}{n\choose k}\frac{(-1)^k}{k!}x^k\$

The first Laguerre polynomials are as follows:

polynomials

Coefficients can be found here.

The Challenge

Given a nonnegative integer n and a real number x, find \$L_n(x)\$.

Rules

  • This is so the shortest answer in bytes wins.

  • Assume only valid input will be given.

  • Error should be under one ten-thousandth (±0.0001) for the test cases.

Test Cases

Here, n is the first number and x is the second.

In: 1 2
Out: 1

In: 3 1.416
Out: -0.71360922

In: 4 8.6
Out: −7.63726667

In: 6 -2.1
Out: 91.86123261
| |
\$\endgroup\$
  • \$\begingroup\$ Do you mean \$L_n(x)\$ by y(x) (under The Challenge)? Also, the challenge and rules have a conflict (four or five decimal places?) \$\endgroup\$ – Bubbler 2 days ago
  • \$\begingroup\$ hopefully it is clearer now @Bubbler \$\endgroup\$ – golf69 2 days ago
  • \$\begingroup\$ You realize that when x get huge, that means arbitrary-precision arithmetic?... perhaps require "4 decimal places for the provided examples" instead. \$\endgroup\$ – user202729 2 days ago
  • \$\begingroup\$ triangle of coefficients: oeis.org/A021010 \$\endgroup\$ – qwr 2 days ago
1
\$\begingroup\$

I've Got The Key, I've Got The Secret

A cryptography challenge in 2 parts.

Part 1

Implement a pair of programs in any language (the two programs could be in different languages if you wanted) to encode and decode a string of plaintext.

Input and Output

The encoder must take the plaintext (and an optional key) and return an encoded string. The decoder must take the cyphertext (and an optional key) and return the plaintext exactly as it was given to the encoder.

Restrictions

  • The encoding and decoding code must be entirely implemented in the language - no libraries or cryptography functions may be used.
  • The code (encoder+decoder) cannot be longer than 1024 characters.

Part 2

Implement programs (multiple programs per answer, one answer per entrant) which crack your opponents encryption algorithms.

Input

The cyphertext.

Output

The plaintext that generated the ciphertext.

Scoring

I will upvote all answers to part 1 which have working encryption and have obviously made an attempt at golfing their answer.

In order to be eligible to win, an entrant will have to have taken part in both parts of the question. Overall score will be (length of shortest program that cracks your code-(length of encoder+length of decoder)). Highest score wins and winning entrant's entries will be accepted on both questions.

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ The obvious place for this to fall flat on its face is if someone is able to implement AES or something similar within the 1024 character restriction. \$\endgroup\$ – Gareth Jun 13 '12 at 13:06
  • 1
    \$\begingroup\$ Probably better if the methods of the part one programs are disclosed in non-obfuscated language, though with the short length restriction this may not be necessary. \$\endgroup\$ – dmckee --- ex-moderator kitten Jun 13 '12 at 15:23
  • 2
    \$\begingroup\$ Forget AES: RSA is easily doable. That aside, you need to define "crack" in part 2. \$\endgroup\$ – Peter Taylor Jun 13 '12 at 15:35
  • 1
    \$\begingroup\$ Also, it's not clear whether "optional key" means that it's optional to make the algorithm unkeyed (doesn't make much sense, I admit) or optional to supply it, in which case it uses a default key. \$\endgroup\$ – Peter Taylor Jun 13 '12 at 15:42
  • 1
    \$\begingroup\$ @PeterTaylor I just put optional in to leave it up to the implementer whether or not they wanted to have the key input or hard-coded (or use no key). I'd have thought everyone would have the key input into their program, but I didn't want anyone to feel forced into it by the spec. Hmm, if RSA is doable within the character restriction I'll end up with a load of unbreakable codes which would make for a pretty crap part 2. By crack I meant cyphertext goes in, some time later plaintext comes out. Would restricting the character count further help, or is this question beyond help? \$\endgroup\$ – Gareth Jun 13 '12 at 16:05
  • 3
    \$\begingroup\$ On that definition of crack, I can brute force for the length of the decoder plus a few bytes to iterate over all keys of the right length and some heuristics to check plausibility of the plaintext. The brute force cracker might even be shorter than the decoder if the decoder wasn't written in GolfScript... I think this question may be beyond help. \$\endgroup\$ – Peter Taylor Jun 13 '12 at 16:28
  • 3
    \$\begingroup\$ @PeterTaylor Okay, thanks. I like the 'build your own - knock everyone else's down' aspect of this question though. I'll have to find another area where it could apply. \$\endgroup\$ – Gareth Jun 13 '12 at 16:34
  • 2
    \$\begingroup\$ @Gareth I too like the competitive nature of this idea. I'm looking forward to a question with this plan in mind! \$\endgroup\$ – Gaffi Jun 13 '12 at 19:31
  • 1
    \$\begingroup\$ I think it would be better to split this into a "cops" post and a "robbers" post. \$\endgroup\$ – wizzwizz4 Feb 16 '17 at 9:46
  • 1
    \$\begingroup\$ @wizzwizz4 Wow, this is another blast from the past. I think this pre-dates the cops-and-robbers tag. I always seem to be ahead of my time. :-) \$\endgroup\$ – Gareth Feb 16 '17 at 9:49
1
\$\begingroup\$

Countability of Sets of Finite Sets

The aim of this challenge is to code-golf a program which returns an iterator that will iterate over all possible non-empty finite sets of positive integers.

So if running long enough, this iterator should eventually touch on {1}, {2, 5}, {3, 6, 112} (ie none of these should occur "at infinity")

You may choose the order in which you iterate over these sets, but the order must satisfy the following requirement:

Under a particular ordering, if S is the i'th set to be returned by the iterator, then we shall call i the index of set S.

Let a restriction (k,T) be an assertion about a set S that says S has size k and T is a subset of S.

For a given restriction (k,T) and iterator IT, let the restricted iterator be the iterator which takes sets returned by IT and filters out sets that don't satisfy the assertion, iterating only over the ones that do. In other words, if IT iterates over the sequence of all sets, the restricted iterator iterates over the subsequence satisfying (k,T). Now if S is the n'th set returned by the restricted iterator, then we'll call n the restricted index of S with respect to (k,T)

Your ordering must satisfy the property that for any restriction there exists a polynomial P(x) such that for any set satisfying the restriction (with index i and restricted index n), i < P(n)

Note that the following ordering is not acceptable:

{1} {2} {1, 2} {3} {1, 3} {2, 3} {1, 2, 3} {4} {1, 4} {2, 4}...

This is the sequence that comes from counting 1, 2, 3, 4, 5, 6... and listing the set bits in the binary representation of each number.

This is because the restriction (1, {}) satisfies only the sets {1}, {2}, {3}, {4}... whose index i as a function of their restricted index is i=2^(n-1) which is not bounded by any polynomial


Sandbox Questions

The reason for the strange requirement at the end is to disqualify any variants on the most natural ordering which simply counts upwards from 1 and enumerates the set bits in each number. In this ordering, the n'th set of length-one occurs at index 2^n which is non-polynomial.

I posted this problem originally, but didn't think of the obvious solution and so I left out the final restriction. I'd like to re-post it with the extra restriction. But first I'd like to know what people think. Is there a better way I can word that restriction or a more natural restriction I could impose instead?

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ I don't understand the extra restriction, so I can't suggest a rewording, but I can say that it needs one. (In particular: what is k? And what function does T serve? Is it really a parameter of the property?) \$\endgroup\$ – Peter Taylor Jun 18 '12 at 8:25
  • 1
    \$\begingroup\$ I don't understand it either. Maybe a sample of an ordering, satisfying the requirement, and another one, violating it, would help. \$\endgroup\$ – user unknown Jun 18 '12 at 15:31
  • 1
    \$\begingroup\$ I understand the restriction now, although I haven't worked through the full implications. Does allowing T to be non-empty make a significant difference at all? \$\endgroup\$ – Peter Taylor Jun 19 '12 at 6:52
  • 1
    \$\begingroup\$ I don't know. It may not. I guess the size part is the important part. I was just thinking that the ordering should be such that you run into all kinds of sets frequently. \$\endgroup\$ – dspyz Jun 20 '12 at 7:17
1
\$\begingroup\$

The One with Two Parts

The aim of this challenge is to create a pair of functions which scramble and unscramble any given piece of text.

Part 1

In part one you post your scrambling function, along with the length in characters and language of your unscrambling function (but NOT its code). The length of the scrambler does not affect your score so you needn't golf it unless you want to. The two functions may be written in different languages if you wish.

Input/Output

The scrambling function should take one argument only - a string containing the input text - and return a string containing the scrambled text. The unscrambling function should also take only one argument - the scrambled text - and return the original text. The input text will be limited to characters in the ASCII set range from 0 to 127.

Part 2

In part two you try to beat your opponents' scores for their unscrambling functions. You MUST use the language they specify for their unscrambler in part one. Please give just one answer to this question containing all your unscrambling functions making it clear which question in part one each function unscrambles (maybe each answer in part one should give its scrambler a name for identification?).

Once the closing date (TBA) has passed all participants should post their unscrambling functions in their answer to part one to prove the length, language and functionality of their function.

Scoring The participants score will be calculated as follows: (unscrambler length from part one) - (shortest unscrambler length from part two). The participant with the lowest score wins and will have their answers accepted on both parts of the challenge. To be eligible to win a participant must have taken part in both parts of the question.

Example

In part 1:

  • Bob posts a Python answer and says his unscrambler is a 165 character Python function.
  • Fred posts a GolfScript answer and says his unscrambler is a 59 character GolfScript function.
  • Joe posts a JavaScript answer and says his unscrambler is a 180 character PHP function.
  • Jim posts a Ruby answer and says his unscrambler is 163 character Ruby function.

In part 2:

  • Bob posts an 82 character GolfScript function to unscramble Fred's scrambled text. He also posts a 175 character PHP function to unscramble Joe's scrambled text.
  • Fred posts a 181 character PHP function to unscramble Joe's scrambled text.
  • Joe posts a 150 character Python function to unscramble Bob's scrambled text.
  • Jim posts a 156 character Python function to unscramble Bob's scrambled text. He also posts a 91 character GolfScript function to unscramble Fred's scrambled text.

The scores:

  • Bob scores 165 - 150 = 15
  • Fred scores 59 - 82 = -23
  • Joe scores 180 - 175 = 5
  • Jim scores 163 - 0 = 163

so Fred wins.

Miscellaneous

I suggest that the closing date be two weeks after the challenge begins, and that unscramblers be posted to part one within 48 hours of closing date in order to be eligible.

| |
\$\endgroup\$
  • \$\begingroup\$ Are there any rules regarding scrambling? i.e. is "Stockholm"->"Stockhoml" a valid scramble? (it may not matter, but I'm curious. And to be clear, the scoring is the difference between your opponent's unscrambler length and your own for the same language? \$\endgroup\$ – Gaffi Jul 16 '12 at 16:39
  • \$\begingroup\$ @Gaffi No, you scramble however you want. If you want to just output the text as given that's ok, but you probably won't win with that strategy. The aim is to do it in a way that is easy for you to unscramble but difficult for all the others. That way your score will be smaller. Yes, the score is the difference between your score and the score of the best of your opponents' attempts. I'll add an example to make that bit clearer I think. \$\endgroup\$ – Gareth Jul 16 '12 at 21:27
  • \$\begingroup\$ I think this gives an advantage to people who use (relatively) obscure languages. If the scrambler is written in J and the descrambler in GolfScript then only people who know both can realistically attempt a descrambler. (NB the rules don't say how the score works if no-one attempts a particular unscrambler). \$\endgroup\$ – Peter Taylor Jul 17 '12 at 6:59
  • \$\begingroup\$ I did consider saying that programs that had no attempts at beating them were not eligible to win, but then I thought that if they were scored as though the shortest attempt to beat them was 0 then they wouldn't have much of an advantage. I'll add that into the example scoring. What do you think? I want to encourage answers that are clever or well obfuscated rather than written in Malbolge or something like that. \$\endgroup\$ – Gareth Jul 17 '12 at 7:28
  • 1
    \$\begingroup\$ Does it mean that since no one attempts to solve Jim's Ruby challenge his chances are minimal that he'll win? That would discourage complicated scramblers or difficult languages. \$\endgroup\$ – Howard Jul 17 '12 at 17:12
  • \$\begingroup\$ @Howard As it stands, yes that's how it would work. The alternative, as Peter Taylor points out, is that people using obscure languages have an advantage. I'm not sure how else I might score unscramblers that no-one has attempted to beat. Maybe give them a score of 0? Please, if you or anyone else has any suggestions for making the challenge as inclusive as possible, let me know. \$\endgroup\$ – Gareth Jul 17 '12 at 17:51
1
\$\begingroup\$

Compile BF to TM

Your task is to write a compiler accepting a Brainfuck program (previous challenge: Interpret Brainfuck, wikipedia: Brainfuck) as input and outputting a Turing Machine which produces identical output when supplied with the same (correct) input.

You may select the output format from among the various formats accepted by the answers to Turing Machine Simulator.

The following links may also be useful.
An introduction to programming in BF
BF is Turing-complete
Programming a Turing Machine
Programming Praxis: Turing Machine Simulator

Equivalently, you may write a Brainfuck interpreter in TM, or any partial compilation/interpretation which results in a TM program as described above.

If we consider squares of the TM tape to represent bits (blank=0, mark=1) of the BF memory, then eight squares represent a cell. Each BF instruction translates to a minimum of 8 states of the Turing Machine.

'>' "advance" (++ptr) could be implemented by eight states (sixteen transitions):

adv8 _ adv7 R _
adv8 1 adv7 R 1
adv7 _ adv6 R _
adv7 1 adv6 R 1
adv6 _ adv5 R _
adv6 1 adv5 R 1
adv5 _ adv4 R _
adv5 1 adv4 R 1
adv4 _ adv3 R _
adv4 1 adv3 R 1
adv3 _ adv2 R _
adv3 1 adv2 R 1
adv2 _ adv1 R _
adv2 1 adv1 R 1
adv1 _ link R _
adv1 1 link R 1

where 'link' represents the first state of the following instruction.

'<' "rewind" (--ptr) can be implemented similarly by making leftward movements and rewriting the same symbol just read.

'+' "increment" (++*ptr) can be implemented by a ripple-carry from the Least Significant Bit to the Most Significant Bit, borrowing "rewind" states to back-up to normal position. If the LSB is on the left, it would look something like this:

inc8 _ link N 1
inc8 1 inc7 R _
inc7 _ rew1 N 1
inc7 1 inc6 R _
inc6 _ rew2 N 1
inc6 1 inc5 R _
inc5 _ rew3 N 1
inc5 1 inc4 R _
inc4 _ rew4 N 1
inc4 1 inc3 R _
inc3 _ rew5 N 1
inc3 1 inc2 R _
inc2 _ rew6 N 1
inc2 1 inc1 R _
inc1 _ rew7 N 1
inc1 1 overflow N 1

where overflow is a HALT state.

For I/O, the simplest way I can think is to place all input on the tape after the memory area, and expand the alphabet to include a symbol indicating the dividing line between the memory portion and the input portion of the tape. In fact, by expanding the cell size to nine squares, this symbol can serve as an input pointer, advancing as the input is consumed. (So "advance" and "rewind" now need 9 states each.) And another new symbol is written in front of the current memory cell to serve as the memory pointer. Inputting a byte therefore consists of schleping each bit over the entire space between the two tape positions with something like this:

input _ set-memptr L _
input 1 set-memptr L 1
set-memptr _ find-inptr R *
find-inptr _ find-inptr R _
find-inptr 1 find-inptr R 1
find-inptr $ schlep-bit R $
schlep-bit _ schlep-blank L _
schlep-bit 1 schlep-one L 1
schlep-blank $ schlep-blank L $
schlep-blank _ schlep-blank L _
schlep-blank 1 schlep-blank L 1
schlep-blank * deposit-blank R *
schlep-one $ schlep-one L $
schlep-one _ schlep-one L _
schlep-one 1 schlep-one L 1
schlep-one * deposit-one R *
deposit-blank _ etc R _
deposit-blank 1 etc R _
deposit-one _ etc R 1
deposit-one 1 etc R 1

where "etc" represents going to get the next bit in similar fashion.

To perform a loop (all BF loops are "while" loops, so the exit control is at the beginning and the end has a simple goto back to the beginning), we need first to check is the current cell is zero,

zero8 _ zero7 R _
zero8 1 body R 1
zero7 _ zero6 R _
zero7 1 left1 L 1
zero6 _ zero5 R _
zero6 1 left2 L 1
zero5 _ zero4 R _
zero5 1 left3 L 1
zero4 _ zero3 R _
zero4 1 left4 L 1
zero3 _ zero2 R _
zero3 1 left5 L 1
zero2 _ zero1 R _
zero2 1 left6 L 1
zero1 _ exit-loop R _
zero1 1 left7 L 1
left7 _ left6 L _
left7 1 left6 L 1
left6 _ left5 L _
left6 1 left5 L 1
left5 _ left4 L _
left5 1 left4 L 1
left4 _ left3 L _
left4 1 left3 L 1
left4 _ left3 L _
left4 1 left3 L 1
left3 _ left2 L _
left3 1 left2 L 1
left2 _ left1 L _
left2 1 left1 L 1
left2 _ loop-body L _
left2 1 loop-body L 1
...
loop-body-final _ zero8 N _
loop-body-final 1 zero8 N 1

So assuming the machine starts at tape-location 0, and the input is on the tape starting at 0 and going to the right, the "startup code" for this arrangement would be

startup _ place$ L _
startup 1 place$ L 1
place$ _ left270000 L $
left270000 _ left269999 L _
...

Jeez! The output is going to be HUGE! It might be better to treat the BF memory as negative-indexed and reverse all the _L_s and _R_s in 'advance', 'rewind', 'increment', and 'decrement'.


Questions:

Bonuses for optimizations? If I can implement this myself and provide a complete example output, The bonus could be "subtract the difference between your program's output for the example input with the example output". So eliminating states would be far more valuable than shrinking the code. One could possibly achieve a negative score!


Edit: Actually I think this is unreasonable unless the Turing Machine is augmented with non-reading (movement-only or epsilon) transitions. Duplicating every letter of the alphabet just to move over one square is just ridiculously painful. That means this challenge won't link-up nicely with the other one. :(

What about, instead of implementing the compiler, just devise a translation scheme (as above) that leads to a smaller output for a trivial sample program (based on calculating, rather than coding)? "Back of the envelope" compiler.

| |
\$\endgroup\$
  • \$\begingroup\$ "How much detail on BF do I need to supply? Can I simply reference the BF question?" A link to almost any site that describes the language will do. \$\endgroup\$ – dmckee --- ex-moderator kitten Nov 5 '12 at 16:52
  • \$\begingroup\$ Winning condition? \$\endgroup\$ – Peter Taylor Nov 6 '12 at 13:43
  • \$\begingroup\$ "Longest prefix containing syntactically-correct Malbolge!" :) ... I'd say have none at all. Perhaps the questioner should be required to accept their own example answer? \$\endgroup\$ – luser droog Nov 6 '12 at 18:08
  • \$\begingroup\$ @PeterTaylor Apologies for my last comment. I thought we were on my other answer about the [fun] tag. . . . This one would be a golf: shortest code by character count. But I think a clever system of bonuses could make it interesting. \$\endgroup\$ – luser droog Nov 7 '12 at 10:06
  • \$\begingroup\$ The "Equivalently, you may write a Brainfuck interpreter in TM" option doesn't play very well with being a code golf - how are you going to count the length of the TM? \$\endgroup\$ – Peter Taylor Nov 7 '12 at 11:15
  • \$\begingroup\$ @PeterTaylor Since the TM question specified 5-tuples, I think it's sufficient to count the tuples (== transitions). You can reduce states by increasing the alphabet (or vice versa), but the transitions would remain constant, I think. \$\endgroup\$ – luser droog Nov 8 '12 at 5:25
  • \$\begingroup\$ I'd like to adopt (work on and post) this challenge if you don't want to. Would I be able to? If you do not respond to this message within two weeks, by community guidelines, I am allowed to take it over. \$\endgroup\$ – MD XF Aug 18 '17 at 3:23
  • \$\begingroup\$ Yes, please. If you can do something with it, strike while the iron is hot. \$\endgroup\$ – luser droog Aug 18 '17 at 4:19
1
22 23
24
25 26
96

You must log in to answer this question.

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