507
\$\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\$
0

3113 Answers 3113

1
24 25
26
27 28
104
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\$
2
  • \$\begingroup\$ Guess allowing removing arbitary least item is more interesting \$\endgroup\$ – l4m2 Jun 19 '20 at 2:38
  • \$\begingroup\$ What about a slight pivot - given a list and an allowance, return the list that maximise length of the list? \$\endgroup\$ – streetster Jul 29 '20 at 11:55
2
\$\begingroup\$

The smallest positive integer that cannot be printed in fewer than %NUMBER% bytes of %LANGUAGE%

All numbers mentioned below are positive integers. All programs mentioned below output exactly 1 number (including functions that return it).

For every number, there must be at least one program in your language that outputs it. Besides, the problem of determining what number the program outputs must be undecidable without making the assumption that the program halts.

The challenge itself is to choose a number \$N\$ and find the smallest number \$M\$ that cannot be output by a program shorter than \$N\$ ordinary units of measurement used for your language (usually bytes). You have to prove your solution correct. A strong mathematical proof is not necessary, but it should be reasonably convincing for somebody knowledgeable in your programming language.

The answer with the largest \$M\$ wins.

Sandbox stuff

  • In this challenge, non-golfing languages seem to have a serious advantage. I think scoring by \$M\$ instead of \$N\$ is better at reducing the advantage of Lenguage-like languages to manageable levels and preventing ties; is that correct?
  • Is the tag appropriate?
  • Title suggestions?
\$\endgroup\$
10
  • \$\begingroup\$ I feel like I misunderstand. Let's say print M (where M is a normal base 10 integer) is the only valid way to output integers in my language. I take \$N=7\$, then \$M=1\$. What's to stop me repeatedly increasing \$N\$ by 1 and adding a zero on to \$M\$ each time? \$\endgroup\$ – Dingus May 28 '20 at 2:23
  • \$\begingroup\$ @Dingus I used to have a complicated rule to prevent exactly this; I'll try to think of a simpler one. \$\endgroup\$ – the default. May 28 '20 at 2:35
  • \$\begingroup\$ I'm worried that the proof will just be an exhaustive search for most language, as \$M\$ has to be the smallest number. Alternatively, we could make \$M\$ a lower bound of the smallest value, and score a solution based on both \$M\$ and \$N\$. Another way is to flip this challenge to find the largest printable number in \$N\$ bytes, but that has already been done here and here. \$\endgroup\$ – Surculose Sputum May 29 '20 at 15:18
  • \$\begingroup\$ @Dingus I think you will have to stop when you can't prove whether whatever precedes print M halts or doesn't halt. I still think this is too cheap a way to get a high-scoring answer, but I am not sure how to formalize things better. \$\endgroup\$ – the default. Jun 2 '20 at 16:01
  • \$\begingroup\$ @mypronounismonicareinstate I think my question is probably not relevant. I overlooked a critical condition - 'the problem of determining what number the program outputs must be undecidable without making the assumption that the program halts'. \$\endgroup\$ – Dingus Jun 4 '20 at 0:18
  • \$\begingroup\$ I'm worried that some ridiculously large numbers will show up here. Also, as \$N\$ gets too large, maybe we will encounter problems like \$M\$ cannot be calculated assuming axioms of ZFC, what will happen then? \$\endgroup\$ – Trebor Jun 18 '20 at 7:29
  • \$\begingroup\$ @Trebor As far as I understand, each program either does output a number within finite time or doesn't output a number within finite time. If the program outputs a number, its result is known, and if it doesn't, the program is not valid because it doesn't output a number in finite time. Can you think of any particular way to obtain a ridiculously large number? \$\endgroup\$ – the default. Jun 18 '20 at 10:03
  • \$\begingroup\$ A simple example is a program that enumerates all the valid proofs in ZFC and outputs the Godel encoding of the first proof it encounters of \$A \wedge \neg A\$. Since ZFC cannot prove its own consistency, it is not decidable in ZFC whether this program terminates. Worse still, if the program do terminate, ZFC cannot compute the return value either, because it is now inconsistent, rendering its deductions unreliable. \$\endgroup\$ – Trebor Jun 18 '20 at 11:00
  • \$\begingroup\$ @Trebor Halting and printing a single number is completely binary. Are you sure you are reading the challenge correctly? I'm asking not for the largest number that can be printed, but for the smallest number that can't be printed. \$\endgroup\$ – the default. Jun 18 '20 at 11:27
  • \$\begingroup\$ @mypronounismonicareinstate Yes, that's why I'm "worried" instead of "sure". Also, these problems will not show up if we keep it small... \$\endgroup\$ – Trebor Jun 19 '20 at 0:42
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\$
1
  • 5
    \$\begingroup\$ Have you considered "Does this month start on Monday?" \$\endgroup\$ – Domenico Modica Jun 6 '20 at 14:06
2
\$\begingroup\$

Self-distances completion - Minimum k to get them all

Related minor code-golf challenge

Consider \$A = (a_1,\dots,a_k)\ k\ge2 \$ a sequence of positive integers, in which all elements are different.

The self-distances completion of a sequence like \$A\$ it's performed recursively as follow:

Starting from \$i=2\$, while \$a_i\in A:\$ (loop until the last element)

  • If \$d=|a_i-a_{i-1}|\$ is not already in \$A\$, append \$d\$ to \$A\$
  • Increase \$i\$

The resulting sequence \$A^\circ\$ is presumably longer than \$A\$, nevertheless can't contain more than \$n\$ terms.

Examples

$$ A = (2,\ 9,\ 13,\ 15) \mapsto A^\circ = (2,\ 9,\ 13,\ 15,\ 7,\ 4,\ 8,\ 3,\ 5)\\ A = (2,\ 9,\ 13) \mapsto A^\circ = (2,\ 9,\ 13,\ 7,\ 4,\ 6,\ 3)\\ A = (2,\ 9) \mapsto A^\circ = (2,\ 9) $$

Task

If we pick a number \$n\ge 2\$, we can ask what's the minimum length \$k_n\$ of \$A\$ such that \$A^\circ\$ contains all the numbers up to \$n\$.

(Note that \$\max A = \max A^\circ\$ so \$n\$ has to be in \$A\$)

  • Generate the sequence of \$k_n\$ starting from \$n=2\$.

This is .

I'll run your code on my machine (Windows 10, i7-7500U) for 30 minutes.
Obviously longer sequence is better. In case of a tie, who gets to the last term faster wins.
Your submission must not use more than 8GB of memory.
Please include instructions for how to compile/run your code.

First values and more info

 n. k_n - first A* example found (how many A of lenght k_n that satisfy the condition)

 2.  2  - 1 2 (2)
 3.  2  - 1 3 2 (4)
 4.  2  - 4 1 3 2 (2)
 5.  2  - 5 4 1 3 2 (1)
 6.  3  - 1 6 2 5 4 3 (19)
 7.  3  - 3 1 7 2 6 5 4 (10)
 8.  3  - 6 1 8 5 7 3 2 4 (3)
 9.  4  - 6 1 9 2 5 8 7 3 4 (80)
10.  4  - 10 1 8 3 9 7 5 6 2 4 (39)
11.  4  - 6 8 1 11 2 7 10 9 5 3 4 (18)
12.  4  - 8 12 1 10 4 11 9 6 7 2 3 5 (7)
13.  4  - 5 3 12 13 2 9 1 11 7 8 10 4 6 (2)
14.  5  - 6 14 3 1 13 8 11 2 12 5 9 10 7 4 (68)
15.  5  - 9 13 3 1 15 4 10 2 14 11 6 8 12 5 7 (17)
16.  5  - 11 16 2 15 12 5 14 13 3 7 9 1 10 4 8 6 (9)
17.  5  - 14 15 9 13 17 1 6 4 16 5 2 12 11 3 10 8 7 (1)
18.  5  - 15 18 6 16 17 3 12 10 1 14 9 2 13 5 7 11 8 4 (1)
19.  6  - 16 10 18 1 4 19 6 8 17 3 15 13 2 9 14 12 11 7 5 (38)
20.  6  - 14 5 20 17 1 19 9 15 3 16 18 10 6 12 13 2 8 4 11 7 (8)
21.  6  - 12 19 3 21 20 6 7 16 18 1 14 9 2 17 13 5 15 4 8 10 11 (1)
22.  6  - 20 12 19 3 21 22 8 7 16 18 1 14 9 2 17 13 5 15 4 10 11 6 (1)
23.  7  - 22 4 23 14 16 1 21 18 19 9 2 15 20 3 10 7 13 5 17 6 8 12 11 (46)
24.  7  - 15 21 1 23 13 10 24 6 20 22 3 14 18 2 19 11 4 16 17 8 7 12 9 5 (14)
25.  8  - 19 23 2 22 9 1 25 7 4 21 20 13 8 24 18 3 17 5 16 6 15 14 12 11 10 (942)
26.  8  - 18 25 8 2 24 1 21 26 7 17 6 22 23 20 5 19 10 11 16 3 15 14 9 13 12 4 (254)
27.  8  - 27 1 25 20 6 22 18 3 26 24 5 14 16 4 15 23 2 19 9 12 11 8 21 17 10 13 7 (74)

The veeery elementary program I used. There aren't any optimizations, it's just for reference.

For the purpose of the challenge you don't have to output examples nor the count. k_n is sufficient

(It doesn't appear in OEIS).

Conjectures

  • The sequence of \$k_n\$ is monotonically increasing
  • \$k_{n+1}=k_{n}\lor k_{n+1}=k_{n}+1\$

Sandbox

  • It's all clear and does it makes sense?
  • Any suggestion for a "lighter" name of the process other than "self-distance completion"?
\$\endgroup\$
12
  • \$\begingroup\$ The alignment of Examples is fine in the main post preview :) \$\endgroup\$ – Domenico Modica Jun 1 '20 at 8:46
  • \$\begingroup\$ A k-permutation of n seems to be a permutation of some k-element subset for {1, ..., n}, right? \$\endgroup\$ – retzler Jun 4 '20 at 20:13
  • \$\begingroup\$ @retzler Exactly, equivalently a non-repetitive sequence of integers. And then we consider its max element n. I prefer to keep the notation of k-permutation of n containing n since doesn't require the notion of max and also it's more linear for what comes next \$\endgroup\$ – Domenico Modica Jun 4 '20 at 20:36
  • \$\begingroup\$ If the growth of k_n is unknown, an algorithm's complexity might come in the form f(k_n). Edit Ah well, tagged fastest-code. Maybe there's another ambiguity: Maybe still require an example for each n - otherwise what's to prevent printf("2,2,2,2,3,3,3,4,4,4,4,4,5,5,5,5,5,6,6,6,6,7"); \$\endgroup\$ – retzler Jun 4 '20 at 21:39
  • \$\begingroup\$ @retzler I decided to go for fastest-code since looking around fastest-algorithm are not so popular. And as you spotted, the complexity of the algorithm wouldn't be straightforward (and I know almost nothing how it's calculated). About the output I think that to hardcode a sequence it's automatically seen as cheat. Look \$\endgroup\$ – Domenico Modica Jun 4 '20 at 22:09
  • \$\begingroup\$ Some comments: (1) The description is a little difficult to follow, but I think it's because the problem is that hard to define. You can't probably get the description much clearer than it is now. (2) In the "Task" section you ask for the minimum k such that its completion contains all numbers up to n. However, the math section right afterwards requires, if I'm interpreting it correctly (four quantifiers in a row is a little too much for me), that k and all numbers above it satisfy that property. (3) Maybe give a few more details about your computer: RAM, even cache memory \$\endgroup\$ – Luis Mendo Jun 5 '20 at 20:15
  • \$\begingroup\$ (4) Your submission must not use more than 8GB of memory: isn't that platform-dependent to some extent? (5) Typo: "lenght" \$\endgroup\$ – Luis Mendo Jun 5 '20 at 20:15
  • \$\begingroup\$ @LuisMendo (1) The question was very instinctive, but maybe I've convoluted it too much. Playing with the completion I asked myself how can I "generate" all the number up to a certain one. Of course is interesting to find the minimum requirements that is the minimum (starting) length. Now one particular thing to notice is that the new terms added are always smaller that the max element in the input string (that's because we are always adding distances). So if I hope to generate all the number up to 20, of course 20 has to be within the input string \$\endgroup\$ – Domenico Modica Jun 6 '20 at 13:05
  • \$\begingroup\$ @LuisMendo That's why I define \$\mathcal{A}_{n,k}\$ to be all the sequences of length \$k\$ having \$n\$ as their max element. All the completion of all the sequences in one of these sets always keep the same max element \$n\$, (the only thing that can change is the resulting length). It's in these sets that make sense to search if it exists one sequence that maps to the "full" \$n\$-sequence. It's a guideline not a rule (maybe it does more harm than good) \$\endgroup\$ – Domenico Modica Jun 6 '20 at 13:09
  • \$\begingroup\$ @LuisMendo (2) Yes, you've interpreted it correctly. It's nothing special, basically when you find the smaller k that works, all the numbers above it automatically work as well. Take the working sequence you found of length k, you can find a k+1 sequence if you incorporate the first \$d\$ appended, you can find a k+2 long sequence incorporating also the second \$d\$ appended in the original one. So, they will all work above a certain threshold. (3-4) I was borrowing from this post \$\endgroup\$ – Domenico Modica Jun 6 '20 at 13:23
  • \$\begingroup\$ @DomenicoModica (2) Ah, maybe clarify that in the text then. On the face of it, they seem different statements \$\endgroup\$ – Luis Mendo Jun 6 '20 at 13:33
  • 1
    \$\begingroup\$ @LuisMendo I've pared it down substantially. I don't know why I thought all that notation was fundamental ahahaha. Anyway I'll wait sometimes to post it because I want to experiment a bit with it to have a bigger picture and maybe find some useful reductions \$\endgroup\$ – Domenico Modica Jun 6 '20 at 14:00
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\$
2
  • \$\begingroup\$ This seems like mostly a challenge to compute digits of pi or phi, which feels like a chameleon challenge. \$\endgroup\$ – xnor Jun 8 '20 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 '20 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\$
6
  • \$\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\$ – the default. Jun 7 '20 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 '20 at 18:23
  • \$\begingroup\$ I'm sorry to say that somebody has beaten you to it. \$\endgroup\$ – Dingus Jun 10 '20 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 '20 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 '20 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 '20 at 1:55
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\$
3
  • \$\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 '20 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 '20 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 '20 at 2:32
2
\$\begingroup\$

Posted at Baba if you, flag is win

\$\endgroup\$
4
  • \$\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 '20 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 '20 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 '20 at 17:00
  • \$\begingroup\$ Now that this has been posted to main, could you delete this proposal to create more space for new answers? \$\endgroup\$ – caird coinheringaahing Sep 25 '20 at 1:05
2
\$\begingroup\$

Logo Pack LAPACK (Posted)

\$\endgroup\$
2
  • 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 '20 at 7:45
  • \$\begingroup\$ Now that this has been posted to main, could you delete this proposal to create more space for new answers? \$\endgroup\$ – caird coinheringaahing Sep 25 '20 at 1:04
2
\$\begingroup\$

Migrate Try it online! to CommonMark

Try it online! generates old-style MarkDown code blocks which indent all lines with 4 spaces and then optionally precedes the block with a language comment.

Furthermore if the code block can't be parsed by old-style MarkDown (e.g. it has a leading newline, common in Retina answers), then it instead uses a <pre><code> block, with HTML escapes for all nonprinting characters.

Your program or function must take a whole TIO post, and change its code block into CommonMark style.

Examples:

# [Python 2], 16 bytes

<!-- language-all: lang-python -->

    print "Python 2"

[Try it online!][TIO-kdaf9y51]

[Python 2]: https://docs.python.org/2/
[TIO-kdaf9y51]: https://tio.run/##K6gsycjPM/r/v6AoM69EQSkAzFcwUvr/HwA "Python 2 – Try It Online"

becomes

# [Python 2], 16 bytes

``` python
print "Python 2"
```

[Try it online!][TIO-kdaf9y51]

[Python 2]: https://docs.python.org/2/
[TIO-kdaf9y51]: https://tio.run/##K6gsycjPM/r/v6AoM69EQSkAzFcwUvr/HwA "Python 2 – Try It Online"

which displays as

Python 2, 16 bytes

print "Python 2"

Try it online!

while

# [Retina 0.8.2], 13 bytes

<pre><code>
Retina 0.8.2
</code></pre>

[Try it online!][TIO-kdafdbm1]

[Retina 0.8.2]: https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d
[TIO-kdafdbm1]: https://tio.run/##K0otycxL/P@fKwjMUDDQs9Az@v8fAA "Retina 0.8.2 – Try It Online"

becomes

# [Retina 0.8.2], 13 bytes

```

Retina 0.8.2
```

[Try it online!][TIO-kdafdbm1]

[Retina 0.8.2]: https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d
[TIO-kdafdbm1]: https://tio.run/##K0otycxL/P@fKwjMUDDQs9Az@v8fAA "Retina 0.8.2 – Try It Online"

which displays as

Retina 0.8.2, 13 bytes


Retina 0.8.2

Try it online!

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

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

Where are the traps?

Related: Trapped Knight Sequence The Path Of The Wildebeest

Background Partially copied from my related challenge

The trapped knight sequence is a finite integer sequence of length 2016, starting from 1, and has the following construction rules:

  1. Write a number spiral in the following manner:
17 16 15 14 13 ...
18  5  4  3 12 ...
19  6  1  2 11 ...
20  7  8  9 10 ...
21 22 23 24 25 ...
  1. Place a knight on 1.
  2. Move the knight to the grid with the smallest number it can go that has not been visited before, according to the rules of chess (i.e. 2 units vertically and 1 unit horizontally, or vice versa).
  3. Repeat until the knight gets stuck.

It is known that the sequence ends at 2084 where the knight is trapped. But here is a twist. Suppose a knight can step back to the previous grid whenever it is stuck, and choose the grid with the next smallest number possible. By doing so, the sequence can be further extended until it is stuck again at 2720. Then, the knight steps back and choose another path, which further extends the sequence until it is stuck again at 3325...

Then, we call these numbers at which the knight is being trapped "traps". So we now know that the first few traps are at 2084, 2720, 3325, ... and it continues to infinity.

Challenge

Write a shortest program or function, receiving an integer \$N\$ as input, output the first \$N\$ traps in the extended trapped knight sequence.

Values

The first 100 terms of the sequence are as follows.

  2084,   2720,   3325,   3753,   7776,   5632,   7411,   8562,  14076,   8469, 
  9231,  22702,  14661,  21710,  21078,  25809,  27112,  24708,  19844,  26943,
 26737,  32449,  31366,  45036,  37853,  37188,  43318,  62095,  67401,  68736,
 70848,  62789,  63223,  69245,  85385,  52467,  71072,  68435,  76611,  84206,
 81869,  70277,  81475,  83776,  70767,  84763,  99029,  82609, 103815,  86102,
 93729, 100614, 108039,  82111,  99935,  85283, 109993, 119856, 119518, 116066, 
109686,  92741, 124770,  92378, 104657, 125102, 107267, 107246, 117089, 117766,
 99295, 121575,  98930, 117390, 123583, 112565, 122080, 111612, 111597,  97349,
105002, 130602, 133509, 153410, 127138, 143952, 153326, 157774, 122534, 136542,
163038, 134778, 140186, 162865, 171044, 159637, 171041, 174368, 184225, 152988

Winning Criteria

The shortest code of each language wins. Restrictions on standard loopholes apply.

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

Convert LifeOnTheEdge to LifeOnTheSlope

Your task here is to take a LifeOnTheEdge pattern and convert it to LifeOnTheSlope.

A LifeOnTheEdge pattern is composed of these four characters: |_L . A pattern corresponds to a certain arrangement of "on" edges in a square grid. The pattern is placed in the grid first with the characters in the cells, and each of the four letters specifies the state of the edges on the left and the bottom of that cell. | means the edge on the left is on, _ means the bottom edge is on, L means both of them are on and means neither of them are on.

For example the following LifeOnTheEdge:

|_L
 |

translates to:

. . . . .
|   |
. ._._. .
  |
. . . . .

Your task is however convert it to LifeOnTheSlope. LifeOnTheSlope is a LifeOnTheEdge equivalent but only uses three symbols: /\ . You should rotate the pattern 45-degree clockwise, for example the above example translates to:

/

/\/
  \

Sandbox

I'm not sure if I described the problem clearly. Improvements on the wording and other things?

\$\endgroup\$
2
  • \$\begingroup\$ Nice challenge! The task is clear, I just think you may specify if and how leading/trailing newlines/spaces are allowed, for example in the example there may be a trailing space. And also.. Are the set of characters strictly fixed? People usually ask for free sets, for example some values [1,2,3,0] instead of |_L but since this is ascii-art I think it's fine to have a fixed set. Let's see if anyone else has any opinion. \$\endgroup\$ – AZTECCO Aug 2 '20 at 12:35
  • \$\begingroup\$ @AZTECCO For the second question I'm fine with both options. This convertion is a thing that annoys me in my CA exploration. \$\endgroup\$ – null Aug 2 '20 at 12:38
2
\$\begingroup\$

Identify the tonic from a key signature

Objective

Given a key signature in major, output its tonic.

Input

An integer from -14 to +14, inclusive. Its absolute value is the numbers of flats/sharps. Negative number represents flats, and positive number represents sharps. Note that theoretical keys are also considered.

Mapping

Note the use of Unicode characters ♭(U+266D; music flat sign), ♯(U+266F; music sharp sign), 𝄪(U+1D12A; musical symbol double sharp), and 𝄫(U+1D12B; musical symbol double flat).

-14 → C𝄫
-13 → G𝄫
-12 → D𝄫
-11 → A𝄫
-10 → E𝄫
-9 → B𝄫
-8 → F♭
-7 → C♭
-6 → G♭
-5 → D♭
-4 → A♭
-3 → E♭
-2 → B♭
-1 → F
0 → C
1 → G
2 → D
3 → A
4 → E
5 → B
6 → F♯
7 → C♯
8 → G♯
9 → D♯
10 → A♯
11 → E♯
12 → B♯
13 → F𝄪
14 → C𝄪

Output must be a string. Whitespaces are permitted everywhere.

Rule

  • Invalid inputs fall in don't care situation.
\$\endgroup\$
1
  • \$\begingroup\$ "Or a sequence of bytes representing a string in some existing encoding"? (I think this should be the default, but I don't remember seeing any meta post about it) \$\endgroup\$ – user202729 Aug 4 '20 at 6:06
2
\$\begingroup\$

Source Code Byte Frequency - Posted here

Changes from the original idea:

  • Without the requirement of fixed representation of the result (percentage and trimming).
  • With constraint: source code must be at least 1 byte long
  • Changed from character to byte, plus removing the constraint of SBCS languages only.
\$\endgroup\$
8
  • \$\begingroup\$ This may qualify for the quine tag but I'm not so sure about that \$\endgroup\$ – golf69 Aug 4 '20 at 6:40
  • 1
    \$\begingroup\$ Trimming the output may be difficult for some languages, maybe you could also allow fractions, or require that the output is only accurate to x decimal places? Something to consider when writing a challenge is if a rule actually contributes to the problem or is just an accessory of sorts (here I think the main problem is finding the proportions, and rounding is an accessory) \$\endgroup\$ – golf69 Aug 4 '20 at 6:47
  • \$\begingroup\$ @golf69 I'm also not sure about quine... About the trimming, my intention on the trimming and percentage format was to add a little bit of "work" that the program should do and make the frequencies a bit more different/challenging. Do you think I should drop the trimming part from the challenge? \$\endgroup\$ – SomoKRoceS Aug 4 '20 at 9:05
  • 3
    \$\begingroup\$ I do think so, yes (also it might be better received that way) \$\endgroup\$ – golf69 Aug 4 '20 at 17:21
  • 1
    \$\begingroup\$ I do not think the average person who does not use this site will know what a SBCS is, so it is probably still worth explaining. Alternatively, I think it would be cleaner to just require that the input be a byte and the output reflects the frequency of that byte. That way you don't eliminate multibyte languages from using it to their benefit, and I don't think it allows any "cheating." \$\endgroup\$ – FryAmTheEggman Aug 4 '20 at 21:52
  • \$\begingroup\$ Sounds okay to me. I agree that it is better to avoid elimination of multi-byte languages. \$\endgroup\$ – SomoKRoceS Aug 4 '20 at 22:03
  • \$\begingroup\$ The thing I try to avoid is to get a lot of 0 bytes answers (for languages that print 0 as default). So I want to add a task that the program should do, like printing in percentage format. So the question is, before I reduced the trimming task, if this is enough to achieve that. \$\endgroup\$ – SomoKRoceS Aug 5 '20 at 9:06
  • \$\begingroup\$ Posted here with some changes listed in this edited answer. \$\endgroup\$ – SomoKRoceS Aug 9 '20 at 16:50
2
\$\begingroup\$

Simulate simple Bloons Tower Defense!

For those who are unaware of this legendary series of video games, here is a link.

The task

You are going to be given an integer number and type of bloon wave and two integers describing the damage and pierce (max amount of bloons you can damage in one attack) of each attack. Your task is to output in how many attacks can you destroy the bloon wave.

Bloon types

For simplicity, there will be no special properties like fortified, regrow, camo e.t.c. White bloons will also not be present as, without special properties, they are the same as black bloons

Name - health - what it pops into
BAD   - 20000 - 3x DDT and 2x ZOMG
ZOMG - 4000  - 4x BFB
BFB   - 700   - 4x MOAB
MOAB - 200   - 4x Ceramic
DDT   - 350   - 6x Ceramic
Ceramic - 60    - 1x Rainbow
Rainbow - 1     - 2x Zebra
Zebra   - 1     - 2x Black
Black   - 1     - 2x Pink
Pink    - 1     - 1x Yellow
Yellow  - 1     - 1x Green
Green   - 1     - 1x Blue
Blue    - 1     - 1x Red
Red     - 1     - Nothing!

I/O

Input: A string describing the type of bloon, and three integers: the amount of bloons in the wave, attack damage and attack pierce

Output: An integer describing how many attacks are needed for destroying the whole wave.

Examples

Note: If there is not enough pierce n to attack the whole wave, then only the first n bloons are attacked

Input: Rainbow 3 2 10
Starting: 3x Rainbow
Attack 1: 12x Black
2: 20x Yellow 2x Black
3: 10x Blue 10x Yellow 2x Black
4: 10x Yellow 2x Black
5: 10x Blue 2x Black
6: 2x Black
7: 4x Yellow
8: 4x Blue
9: Done!
Output: 9

This is the 4/0/x Sniper Monkey:

Input: BFB 1 30 1
1: BFB(670)
2: BFB(640)
...
13: BFB(10)
14: 4x MOAB(180)
15: 1x MOAB(150) 3x MOAB(180)
...
19: 1x MOAB(30) 3x MOAB(180)
20: 4x Ceramic(60) 3x MOAB(180)
21: 1x Ceramic(30) 3x Ceramic(60) 3x MOAB(180)
22: 3x Ceramic(60) 3x MOAB(180)
...
27: 1x Ceramic(30) 3x MOAB(180)
28: 3x MOAB(180)
...
69: 1x Ceramic(30)
70: Done!

This is codegolf, so lowest byte-count wins

\$\endgroup\$
5
  • 3
    \$\begingroup\$ This is extremely complicated. I feel like this will be in unanswered for a while. \$\endgroup\$ – Razetime Aug 10 '20 at 17:04
  • \$\begingroup\$ In the second example, how is ceramic destroyed without giving out any lower class bloons? \$\endgroup\$ – Bubbler Aug 11 '20 at 0:31
  • \$\begingroup\$ +1 because btd is awesome lol. However this is a very complicated challenge, even for people who know how the mechanics work. It might be better if you limit the problem to 1 pierce only \$\endgroup\$ – thesilican Aug 18 '20 at 23:34
  • \$\begingroup\$ or you could even do a challenge that simply requires calculating the RBE for a bloon wave, that could still be an interesting challenge \$\endgroup\$ – thesilican Aug 18 '20 at 23:35
  • \$\begingroup\$ actually RBE calculating is probably a bit too simple \$\endgroup\$ – thesilican Aug 19 '20 at 0:02
2
\$\begingroup\$

Solve the Halting Problem for Oneplis

Oneplis is a "very simple esolang" (I don't want to count this one toward my esolangs) made by me which only have three commands. As you can probably see from the name, it is a subset of 1+, along the lines of Befinge.

The three commands are:

  • 1, which pushes 1. (Obviously!)
  • +, which pops the top two numbers and pushes their sum. (Obviously!)
  • #, pops a number n and jumps to the instruction after the nth (0-based) #.

Oneplis is almost certainly a (very limited) push-down automaton, since it's impossible to decrement a number and impossible to retrieve elements arbitrary deep in the stack! Oh, and the only way to read a number is with #, which cannot handle arbitrarily large numbers!

This is , so shortest code wins! Your output should be truthy for halting, and falsy for non-halting. You can use any set of five characters for the instructions. Don't care if it jumps to a non-existence # or trying to execute + when there are <2 numbers on the stack.

Test cases

11+ -> True
1##1# -> False
1## -> True
11+1+###11+# -> True
11+##1#1 -> False

Sandbox

  • Test cases?

  • Shall I require the answers to deal with errors?

\$\endgroup\$
7
  • \$\begingroup\$ For "nth #", is it 1- or 0-based? (I guess it's 0-based, but you need to be explicit on it anyway.) \$\endgroup\$ – Bubbler Aug 20 '20 at 9:39
  • \$\begingroup\$ @Bubbler Uh, ok. It's 0-based in 1+, but 0-based indexing does not make any sense in this challenge anyway, it's impossible to push 0... Should I change it to 1-based? \$\endgroup\$ – null Aug 20 '20 at 9:42
  • \$\begingroup\$ I don't think it's that nonsense, as the only effect is that all instructions between first and second #s are unreachable. \$\endgroup\$ – Bubbler Aug 20 '20 at 9:47
  • \$\begingroup\$ @Bubbler Oh, okay then. So if no one objects I'll post this to main. \$\endgroup\$ – null Aug 20 '20 at 10:15
  • \$\begingroup\$ if you don't plan to require answers to deal with errors then also mention that they don't need to worry about popping from an empty stack \$\endgroup\$ – Mukundan314 Aug 20 '20 at 11:20
  • \$\begingroup\$ Or: errors terminate the program. \$\endgroup\$ – user253751 Aug 24 '20 at 13:29
  • \$\begingroup\$ @user253751 Yes, that's also good. Although, I prefer it this way. \$\endgroup\$ – null Aug 24 '20 at 13:43
2
\$\begingroup\$

Noncommutative Quineoid Triple

This is the hard mode of Quineoid Triple

Write three different programs such that all of the following properties hold:

  • \$ A(B) = C \$
  • \$ B(C) = A \$
  • \$ C(A) = B \$
  • \$ A(C) = -B \$
  • \$ B(A) = -C \$
  • \$ C(B) = -A \$
  • \$ A(A) = \epsilon \$
  • \$ B(B) = \epsilon \$
  • \$ C(C) = \epsilon \$

Where:

  • \$ f(g) \$ is the output obtained from feeding the program text of \$g\$ into program \$f\$
  • \$ -x \$ is the program text of \$x\$ in reverse (reversed in terms of either raw bytes or unicode codepoints)
  • \$ \epsilon \$ is the empty string / an empty output

Rules and Scoring

  • This is , so the shortest program length total, in bytes wins.
  • Standard quine rules apply.
  • Each program can be in any language. Any number of them may share languages or each may use a different language.
  • Use any convenient IO format as long as each program uses a consistent convention.
    • Functions are allowed, as this counts as "any convenient IO".
  • The result of feeding anything other than program text of one of the three programs is undefined.
\$\endgroup\$
2
\$\begingroup\$

Sandbox note: This is partially inspired by There's a fault in my vault!, which I thought had some interesting ideas in it. This is my effort to frame those ideas in a clearer fashion.


Cops/Robbers: Create a weak block cipher

In cryptography, we often use block ciphers, which are a form of keyed encryption. More specifically, for a plain text string \$s\$ and a secret key \$k\$, we design an encryption function \$E(s, k)\$ and a decryption function \$D(\hat{s}, k)\$ such that if we encrypt and then decrypt the text with the same key, we get back our original text. That is, we have \$D(E(s,k),k) = s\$ for all possible strings \$s\$ and \$k\$.

One security property a good block cipher has is that it is resistant against key-recovery attacks. This means that if we have the ability to run \$E(s, k)\$ and \$D(\hat{s}, k)\$ for various choices of \$s\$ and \$\hat{s}\$ and collect pairs of encrypted and decrypted text we cannot tell what the key is.

In this challenge, you will design a simple block cipher that is intentionally vulnerable to a key recovery attack, and challenge others to try and exploit it.

The Cops' Challenge

  1. Design a block cipher. Design an encryption function \$E(s,K)\$ and decryption function \$D(\hat{s},k)\$ that take strings (or your language's closest equivalent) of a fixed length \$16\$ bytes and a key of fixed length \$16\$ bytes and outputs a string of length \$16\$ bytes. Your \$E\$ and \$D\$ functions must have the property that \$D(E(s,k),k) = s\$ for all 16-byte strings \$s\$ and \$k\$.1 The functions must be deterministic (not use any randomness) and pure (not rely on any outside state). Your \$E\$ and \$D\$ must work within the integer/float precision of your language. Specifically, you may not treat floating point as if it's arbitrary precision, nor may you assume integers of arbitrary size if your language utilizes fixed-size integers.
  2. Implement a secret key-recovery attack on your block cipher. Write a program that makes calls to \$E\$ and \$D\$ for a secret, unknown key \$k\$ and fully recovers the key by observing properties of the input/output pairs. The key must be recovered with probability \$1\$ - you may not rely on probabilistic approaches.2 You must treat \$E\$ and \$D\$ as black boxes, from which you can only observe their input and output. This means you must not utilize runtime introspection, timing information, or other side effects of the implementation. You must only pass full \$16\$ byte strings to \$E\$ and \$D\$, and not any other type. This means you may not rely on special objects with overloaded operators or similar to glean information about how the input is processed by \$E\$ and \$D\$. Your attack may be adaptive, in that it decides which strings to pass in based on outputs to previous strings. To enforce a practicality limit, your attack must work for a combined total of strictly less than \$2^{16}\ = 65536\$ calls to \$E\$ and \$D\$ for any key \$k\$. If the block cipher you design has the property that for keys \$k_1\$ and \$k_2\$ that \$E(s,k_1)=E(s,k_2)\$ and \$D(s,k_1)=D(s,k_2)\$ for all \$s\$, then we call these keys functionally identical, and your attack may recover any functionally identical key to the original.

That's it! You will reveal both the encryption and decryption functions \$E\$ and \$D\$, and challenge the robbers to find your key recovery attack (or possibly a different one).

Clearly, the challenge is to design your \$E\$ and \$D\$ to look secure, but they have some catastrophic weakness that allow you to recover the key with very few calls. Another approach is to 'trapdoor' the function in some way only known to you. In the spirit of Kerckhoffs's principle, you are encouraged to post a short explanation of what your \$E\$ and \$D\$ do, especially if they are written in an esoteric language.

You may use cryptographic functions if you wish, but using them presents several practical problems. Hashing functions are designed to be one way and your are unlikely to be able to design both an encryption and decryption function that utilizes them. Symmetric ciphers have both encryption and decryption, but is unlikely to allow the key recovery attack outlined here.

If no-one mounts a successful attack in 7 days, you may post your key recovery attack and mark your answer as safe, which prevents it from being cracked. Note your submission can still be cracked until your reveal your attack.

Your answer is invalid if you do not follow the rules set above. Your answer can be declared invalid even after it is marked safe, if it turns out your revealed attack does not obey the rules.

The shortest safe submission, calculated as the sum of the bytes of the two functions \$E\$ and \$D\$, wins. Your functions must be named.

The Robbers' Challenge

  1. Find a vulnerable answer. That is an answer, which hasn't been cracked yet and which isn't safe.
  2. Crack it by designing a key recovery attack. Your attack must follow the rules outlined in the cops section. To recap, this means:
    • The total number of calls to \$E\$ and \$D\$ with the key \$k\$ must be strictly less than \$2^{16}\$
    • You must only pass \$16\$ byte strings to \$E\$ and \$D\$, and must have the key \$k\$ initially be unknown
    • The attack may be adaptive but must work to recover any 16 byte key \$k\$ (or a functionally identical key)
    • You must treat \$E\$ and \$D\$ as black box, and may not use runtime introspection, timing information, etc.

If you've found such a attack, post an attack on the robber's thread linking back to the answer. If possible, you should post a link to an online interpreter which allows others to run your attack for various keys \$k\$. You are encouraged to post how your answer works, and the maximum number of calls your approach makes to \$E\$ and \$D\$. If your attack does not recover the key, but instead a functionally identical one, explain (briefly) why they are functionally identical.

You must not crack your own answer.

The user who cracked the largest number of answers wins the robbers' challenge. Ties are broken by the sum of bytes of cracked answers (more is better).

Example #1

Python 3, 133 bytes (cop)

E=lambda s,k:''.join(chr((ord(c)+ord(d))%256) for c,d in zip(s,k))
D=lambda s,k:''.join(chr((ord(c)-ord(d))%256) for c,d in zip(s,k))

Try it online!

My program computes the sum of \$s_i\$ and \$k_i\$ for each \$i\$.

Python 3, cracks xxx's answer

leaked_key = E('\0'*16,k)
print('key = %s' % leaked_key)

Try it online!

My crack completes in \$1\$ call and uses that fact that \$0 + k = k\$.

Example #2

Python 3, 147 bytes (cop)

def E(s,k):
 o=''
 V=[*range(256)]
 j=0
 for i in range(16):
  j+=V[i]+ord(k[0])
  j%=256
  V[i],V[j]=V[j],V[i]
  o+=chr(ord(s[i])^j)
 return o
D=E

Try it online!

My program uses a complicated thing.

Python 3, cracks yyy's answer

leaked_key = ''
for c in range(256):
 if E('f'*16,chr(c))==E('f'*16,k):
  leaked_key = chr(c)+'x'*15
  break

print('key = %s' % leaked_key)
assert E('abcdabcdabcdabcd', leaked_key) == E('abcdabcdabcdabcd', k)
assert D('abcdabcdabcdabcd', leaked_key) == D('abcdabcdabcdabcd', k)

Try it online!

They only ever use the first byte of the key, so we can just bruteforce the first byte and pad with anything to get a functionally identical key. This involves a maximum of \$256\$ calls to \$E\$ with the secret key.


1. This means that if your language uses null-terminated strings, such as C, then you should be using memcpy-type operations instead of string operations. Since the input length is fixed as 16 bytes, this should be no issue.
2. This requirement forbids most kinds of Birthday attack.


Questions to sandbox users:

  • I know this is a lot to take in. Is it clear?
  • Can anyone think of a trivial way to trapdoor \$E\$ and \$D\$ with eg. a hashing function? I don't think it's possible, but I could be wrong.
\$\endgroup\$
4
  • \$\begingroup\$ I love this idea! I think it's written in a pretty clear way, I think you could trivially trapdoor E and D, by doing something like if (s == hash("sixteen_byte_str")) return k, but disallowing cryptography functions should fix that \$\endgroup\$ – Redwolf Programs Sep 7 '20 at 14:06
  • \$\begingroup\$ @RedwolfPrograms Glad you think it's clear! Out of curiosity, if you wrote that as your encryption function, how would you write the corresponding decryption function? \$\endgroup\$ – Sisyphus Sep 7 '20 at 22:58
  • \$\begingroup\$ Something like if (ŝ == k) return hash("sixteen_byte_str"), you'd just need to ensure there's no way it could be confused with a value that legitimately encrypts to k (which would be easily doable by replacing it with whatever hash("sixteen_byte_str") would typically encrypt to). Using crypto functions to trivially win a CnR challenge is practically a loophole, and is likely to be downvoted anyway. (Btw, when I write x == hash("sixteen_byte_str"), I mean hash(x) == "sixteen_byte_str") \$\endgroup\$ – Redwolf Programs Sep 8 '20 at 1:51
  • \$\begingroup\$ Actually, wait, I'm being stupid. I think there's no way to not have it return hash(x) == "sixteen_byte_str" in one of the two functions, so there doesn't appear to be a trivial way to trapdoor it. I'd still disallow crypto in case someone uses some sort of fancy asymmetric thing, but I can't figure it out if there is. \$\endgroup\$ – Redwolf Programs Sep 8 '20 at 12:08
2
\$\begingroup\$

Take 6!

A good card game is a wonderful thing. I got me a nice fresh set of Take 6! Too bad though, I have no-one to play with. And so I turn to you!

The Game

The game is played with a set of 104 cards, numbered 1 to 104 inclusively. Each card has a number of 'cows' attached. Here's a quick Python function to calculate the number of cows:

def cows(card):
    out = 1
    if(card % 5) == 0:
        out += 1
    if(card % 10) == 0:
        out += 1
    if(card % 11) == 0:
        out += 4
        if(card % 5) == 0:  # C-c-c-combo
            out += 1
    return out

Therefore, there is a total of

  • 1 card with 7 cows (number 55)

  • 8 cards with 5 cows (the other multiples of 11: 11, 22, 33, 44, 66, 77, 88, 99)

  • 10 cards with 3 cows (multiples of ten: 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)

  • 9 cards with 2 cows (other multiples of five: 5, 15, 25, 35, 45, 65, 75, 85, 95)

  • 76 cards with 1 cow (all other cards)

The game is played by up to 10 players.

Each player is given 10 cards. 4 cards are placed on the table as the starts of 'rows'. Then 10 turns of play take place. Then, results are calculated.

A turn

Each player selects one of their remaining cards. At the same time, they reveal their selected cards.

Going in the order of lowest card number, the player whose card it is must place it into a row according to rules:

  1. If there is a row with the top card of a lower number than the player's and no such row with a lower number exists, their card must be placed at the end of the row. If their card is the sixth in a row, they take the first 5 cards and put them on their result pile, leaving theirs as the new start.

  2. If no such row exists, they must pick one of the rows, take all the cards there to their result pile, and leave their card as the new start.

Examples:

row tops: 10 20 30 40

played: 25

must be placed on the row with a 20, creating the configuration 10 25 30 40 with a possible cow gain

row tops: 10 20 30 40

played: 9

pick any row, creating for example 10 20 9 40, but guaranteed to gain cows

Counting

The sum of cow values of the cards in a player's result pile is their score. The lower the score the better.

Scores may be added up over several games, creating an overall score for a match.

Bots

Bots will be standalone programs. Everything belonging to a bot will be placed in a single directory, the name of the directory will be used as the name of the bot. A launch script named launch (may be the entire bot) must be provided. If necessary, a compilation script named build may be provided. Both scripts shall be placed directly in the bot's directory and should use shebangs to specify how they are to be run.

Bots shall not interfere with other bots, the controller, or the git repositories used.

The bots will have the option of storing extra information in files in their own directory. It will be wiped when a fresh series is being run (such as after adding a new bot).

An override input format may be provided. I intend to use StringTemplate for this, I'll write up some details when working on the controller. The default format will have all messages newline-terminated.

Once launched, the bot will be first given their cards, as a list of card numbers, where the numbers may or may not be ordered.

The default format will be

cards 0 1 2 3 4 5 6 7 8 9

No response is expected.

For each round, the bot will be prompted with the current state of the grid, that is the number of cards in each row, the sum of cows in each row and the top number card in the row.

The default format will be

count 1 2 3 4

cows 5 6 7 8

top 11 20 22 35

The bot shall answer with the number of one of its remaining cards.

The list of all the cards used by all bots in the round will be given to each bot. Not that this includes the bot's own card. The order of bots in this message will be consistent within a game.

The default format will be

used 0 1 2 3 4 5 6 7 8 9

No response is expected.

If the placement rule 2. has to be invoked, the bot will receive a message containing the board state at the time when it needs to pick a row

The default format will be

pickrow

count 1 2 3 4

cows 5 6 7 8

top 11 20 22 35

The bot shall respond with the number of the row it wishes to take. The rows will be 0-indexed for this.

If the bot's move results in a gain of result cows, it will be informed of which cards and how many cows it has gained (note that the lower the number the better).

The default format will be

cardgain 1 2 3 4 5

cowgain 6

No response is expected.

At the end, all bots will be shown their score as well as all the scores of others, in the order consistent with the used cards message.

The default format will be

score 30

others 0 1 2 3 4 5 6 7 8

No response is expected.

If the bot makes an invalid move, it will be delivered a special message informing it of such. From that point the bot's current game is over. It gets 100 points of penalty.

The default format will be

invalid

A timely shutdown is expected.

The bot may of course try to save information to its private file at any time, including at the end.

After the final message, the bot shall terminate in a timely manner.

Scoring will be added up over many games, number depends on how fast the games end up running, but at least 100 sounds reasonable to me.

Bots will be placed in a separate github repository TODO for easy setup and reseting. Bots that need a compilation script but don't have one will be given one.

Controler

Work has started at https://github.com/MrRedstoner/Take6KOTH

The controller will be designed to run in Java 1.8+, using the Process API to launch bots.

Notes:

While the number of bots is too low, it will be padded to 10 by using multiples of primitive bots. The tournament style once 11+ submissions exist is for now playing all subsets of size 10.

I intend to write up at least a few primitive bots, to get the games going. Something like using cards in the order they were given, or randomly. These will also demonstrate the custom input functionality. Maybe even one that uses external input, to let me play for fun!

Limits for execution time, storage of data etc. are not given at this time. If bots start to behave excessively limits may be added.

Sandbox notes:

Any better idea for tournament?

Should bots be given the names of their competitors as well? Currently leaning towards yes.

Planned tags:

\$\endgroup\$
3
  • \$\begingroup\$ Even though most people can read python, you should still include a written description of how the cows are counted. As it is, your program counts twice for it being divisible by 5 in the case of 55, is that intentional? \$\endgroup\$ – FryAmTheEggman Sep 18 '20 at 18:13
  • \$\begingroup\$ @FryAmTheEggman it is indeed intentional, it's a combo for a reason :D. The result also matches what wikipedia describes about the game. Should have some more to edit soon so I'll make the change then. \$\endgroup\$ – Mr Redstoner Sep 18 '20 at 18:16
  • \$\begingroup\$ But when do you take 720?? /s \$\endgroup\$ – Jo King Sep 21 '20 at 9:39
2
\$\begingroup\$

Complete the landscape

Carcassonne is a tile-based game, where the objective is to construct Roads, Cities and Monasteries, in order to score points. The game works by players taking turns to draw and place tiles to construct a landscape, then claiming roads, cities and monasteries. An example landscape is:

Example Landscape

There are \$19\$ distinct tiles (ignoring rotations), each of which contains at least one feature (Road, City or Monastery):

All tiles

Also, notice that the landscape must be consistent. This means that roads must connect to other roads, city edges must connect to other city edges and fields must connect to fields. Therefore, these tiles are inconsistent:

Inconsistent tiles

To avoid this challenge being about image processing, we can translate each tile into a list containing \$5\$ values, according to this legend:

[North edge, East edge, South edge, West Edge, # of cities]

0: Field
1: Road
2: City

For instance, this tile can be described as [2, 0, 1, 1, 1]. Using this legend, we can describe each tile uniquely, and it's rotations are rotations of the first four elements. The entire grid can be described as a rectangular matrix, with a \$20^\text{th}\$ distinct value for an empty square. Translating the first landscape into this format, we get:

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

using [] to represent an empty square. The complete list of tiles (ignoring rotations) in the same grid as the second image is

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

Your task is to take in a rectangular matrix where every element save one is one of the 19 tiles given above or one of their rotations. Tiles can appear more than once, and not every tile will appear in every input. This landscape will be consistent, as defined above. You should take in this input and output the tile that could fill the empty space in the array, keeping the landscape consistent, as defined above.

If there are multiple tiles that would work, you may output either all of them or just one. If no such tile exists, you may produce any output/result that could not be construed as a tile (i.e. it's not in the 19 tiles specified above, nor in any of their rotations). The "empty space" in the input may be your choice, so long as its consistent, and (although I'm not sure why you would) it isn't one of the 19 tiles above or their rotations, and there will only ever be a single empty space.

This is , so the shortest code in bytes wins.

Test cases

test cases to be added


Meta

  • Is this clear enough?
    • More specifically, is the definition of a "consistent landscape" objective and understandable?
  • This is a somewhat related question, but I believe there are enough differences between the two for them to not be duplicates. Thoughts?
  • Tags are , , , . Any suggestions?
  • Any further feedback?
\$\endgroup\$
3
  • \$\begingroup\$ @Beefster Aside from involving tiling, I'm not quire sure how that challenge is related, let alone a possible duplicate \$\endgroup\$ – caird coinheringaahing Sep 28 '20 at 22:00
  • \$\begingroup\$ Filling Carcassonne tiles in a grid can be thought of as a specific case of wang tiles with a different set of tiles, but upon closer inspection, seeing as your challenge is to complete the landscape, rather than fill a grid from nothing, this is actually a pretty different challenge. \$\endgroup\$ – Beefster Sep 28 '20 at 22:03
  • \$\begingroup\$ Related \$\endgroup\$ – Beefster Sep 28 '20 at 22:04
2
\$\begingroup\$

AOG Day 1: The Advent Begins

What good is Advent... without the actual Advent Calendar? Fortunately, we already have an advent calendar, so we don't need to worry about getting one of those! But since it's not a physical calendar, we can't open the doors with our hands; rather, it's a block of characters. How do we open a door on that calendar?

Challenge

You will be given an advent calendar in a state from day 0 to 24 and you are to open the next door. Essentially you will be given a calendar (a 5x5) containing all numbers for (X+1) to 25 (inclusive) and blanks to fill the rest except for one square which is the current door. Your task is to take the treat and open the next door for this day.

Input

Input will be a 5x5 of values. You can choose to take this in any reasonable format, but you must leave it as a grid, you cannot I/O as a flat list. Three types of values are needed: the days must be represented as integers from 1 to 25, and opened windows / the treat window need to be two consistent distinct values; for example, 0 and -1, [] and "", or anything else reasonable enough.

Output

Output should be a 5x5 of values in the same format as the input. The next day (the smallest remaining integer) should be replaced with a treat window, and the treat window from the prior day should become empty (take the treat every day).

Sample Test Cases

These use _ for empty windows and * for the treat. This is mostly to make it look visually nice for this question.

     Input     ->     Output
     
 3  7 25 10 14     3  7 25 10 14
24 12  * 15  9    24 12  _ 15  9
 2 22 18 23 17 ->  * 22 18 23 17
 4  8  5 13 19     4  8  5 13 19
 6 21 20 11 16     6 21 20 11 16
 
 8 23 16 12 14     * 23 16 12 14
 9  _ 24  _  _     9  _ 24  _  _
17  _ 13 25 10 -> 17  _ 13 25 10
15 19 21 18 11    15 19 21 18 11
_  *  _ 20 22     _  _  _ 20 22

 8 18 16 21  _     * 18 16 21  _
10 17  _  _ 19    10 17  _  _ 19
24 22 14 20 25 -> 24 22 14 20 25
15 12  _ 23 13    15 12  _ 23 13
11  _  _  *  9    11  _  _  _  9

11  3  6 14  7    11  3  6 14  7
23 15 10  1 21    23 15 10  * 21
 5 13  2 16 25 ->  5 13  2 16 25
19  4 12  9  8    19  4 12  9  8
24 18 20 22 17    24 18 20 22 17

You can generate more test cases here.

Rules and Specifications

  • The calendar will always contain 25. However, it may not always contain * or _.
  • Standard loopholes apply, as always.
  • this is a challenge so your score is determined by your code length in bytes with a lower score being better; however, a solution will not be accepted.

Sandbox

  • This challenge will be posted on December 1st, 2020.
  • Is this too easy/trivial, or a duplicate?
  • tags will be
\$\endgroup\$
4
  • \$\begingroup\$ Why would the input not include a *? Furthermore, I'd include a test case with no _ (or * if that's possible). Just to clarify, input can be taken as a 5x5 2D array (but not as a flat list of 25 elements)? \$\endgroup\$ – caird coinheringaahing Oct 2 '20 at 1:12
  • \$\begingroup\$ @cairdcoinheringaahing If it's day 0 (so if the calendar is unmodified) then nothing has been opened. I will include a case to reflect that; the first test case doesn't contain a _. Also yes, though I could be convinced to change that. \$\endgroup\$ – HyperNeutrino Oct 2 '20 at 1:13
  • \$\begingroup\$ So on day 0 the advent calendar is just a grid of 25 numbers, and the program must "open" door 1? \$\endgroup\$ – caird coinheringaahing Oct 2 '20 at 1:14
  • \$\begingroup\$ @cairdcoinheringaahing Yes. I added a test case (last one) for that \$\endgroup\$ – HyperNeutrino Oct 2 '20 at 1:15
2
\$\begingroup\$

Output all of printable ASCII using all of printable ASCII

Posted

\$\endgroup\$
8
  • \$\begingroup\$ "Irreducible" isn't really an observable requirement; I'd recommend looking into using pristine-programming to make it an objective criterion. \$\endgroup\$ – HyperNeutrino Oct 12 '20 at 18:31
  • 1
    \$\begingroup\$ What do you mean by "observable"? "irreducible" simply means you can't purely remove characters (not purely substrings) from the program and have it still work (not merely not error). That's pretty objective, is it not? \$\endgroup\$ – pxeger Oct 12 '20 at 18:39
  • \$\begingroup\$ Actually, yes it seems you're right, I was probably thinking of some other common criteria that isn't valid. Otherwise challenge looks good, doesn't seem to be a duplicate. I would say this isn't kolmogorov complexity since it's not constant but it is restricted source albeit not in the common usage. \$\endgroup\$ – HyperNeutrino Oct 12 '20 at 18:48
  • \$\begingroup\$ Can my program contain additional non-ASCII bytes? \$\endgroup\$ – Adám Oct 12 '20 at 19:00
  • \$\begingroup\$ @Adám yes, in the post it says "Your program, and its output, can contain any additional non-printable-ASCII bytes (bytes, not characters) if you like, such as newlines". "non-printable-ASCII" includes "non-ASCII" \$\endgroup\$ – pxeger Oct 12 '20 at 19:01
  • 2
    \$\begingroup\$ Ah, I see. Maybe clarify that you mean both non-[printable-ASCII] and [non-printable]-ASCII. \$\endgroup\$ – Adám Oct 12 '20 at 19:03
  • \$\begingroup\$ Perhaps subtract 95 from each score so that scores look more reasonable \$\endgroup\$ – Lyxal Oct 13 '20 at 10:51
  • \$\begingroup\$ @Lyxal my reasoning for not doing that was because I suspect most answers will be quite a lot longer in order to make sure they're irreducible, it would complicate things, and IMO it doesn't really matter if they're that length \$\endgroup\$ – pxeger Oct 13 '20 at 10:55
2
\$\begingroup\$

Count the Collatz survivors mod 2^n

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

Round a Matrix

Your input is a 2d array of nonnegative floats A. It can be supplied in whatever format is most acceptable for your language. It can have any dimensions.

Let r and c be the 1d arrays of row and column sums of A respectively, rounded to the nearest integer, with the rule that 0.5 is rounded up to 1.

Your task is to output a 2d array of nonnegative integers B such that |b_{ij} - a_{ij}| < 1 for all i and j, and also the row and column sums of B are equal to r and c respectively.

In other words, B is obtained by rounding each element of A up or down, in such a way that the row and column sums are preserved.

There may be many possible solutions. In this case, you only need to output one of them.

If there is no solution, your program's behaviour can be undefined.

Example:

 A = 1.2 3.4 2.4
     3.9 4.0 2.1
     7.9 1.6 0.6

in this case, the row sums are [7.0, 10.0, 10.1] and the column sums are [13.0, 9.0, 5.1] so after rounding these, you get r = [7 10 10] and c = [13 9 5]. One acceptable solution is

 B = 1   3   3
     4   4   2
     8   2   0

This is code golf, so the shortest code wins.

Motivation

I am also interested in what clever algorithms people can come up with. I guess the most obvious is just to do a random search, but that can take a very long time, even if the array is only 10x10 or so.

Questions

  • Is it clear? Please can you edit it if it's not in the right format?
  • Has it appeared here before? (I don't think so, because I was searching Stackoverflow for a while in order to come up with a solution to this.)
  • Is there always a solution under the conditions given here?
  • Would it be better in some other format than code golf?
  • Should the condition |b_{ij} - a_{ij}| < 1 be |b_{ij} - a_{ij}| <= 1?
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Since you want optimal, interesting solutions, rank by time complexity. You'll get fewer answers, but they will be more optimal than a direct brute force approach. \$\endgroup\$ – Razetime Oct 22 '20 at 6:53
  • 1
    \$\begingroup\$ The suggestion of using complexity isn't often a good one - most challenges here that try to do that wind up closed or unanswered. It would be much simpler to go by execution time for some number of test cases that you pick. For the actual question, I think you should explicitly say that r and c are computed by summing and then rounding (assuming that is the correct order) as it isn't precisely clear from what you have right now. \$\endgroup\$ – FryAmTheEggman Oct 22 '20 at 20:34
2
\$\begingroup\$

The Fibonacci Rectangular Prism Sequence (posted)

\$\endgroup\$
12
  • 2
    \$\begingroup\$ There are the square roots of A127546. It looks like there are ways to generate this sequence shorter than just generating Fibonacci numbers and adding their squares. So, this doesn't strike me as a duplicate but an interesting challenge in its own right. I'd recommend removing the square-root step from the challenge and just asking for the sum of the three squares, which is a whole number. This might also allow for more interesting recursive solutions. You should include test cases, perhaps something like the first 15 elements of the sequence and maybe one big one. \$\endgroup\$ – xnor Oct 27 '20 at 0:39
  • 1
    \$\begingroup\$ For clarity, I also recommend explicitly giving the formula for the k-th term in terms of the respective Fibonacci numbers, so that solvers don't need to know the Pythagorean formula for the diagonal of a prism. And, just in case, give the recursive formula for the i'th Fibonacci numbers. Mathjax is enabled here, but you have to use \$ delimiters in place of $. \$\endgroup\$ – xnor Oct 27 '20 at 0:45
  • \$\begingroup\$ @xnor Just throwing in an equation seems odd for a code golf challenge. Do you have any ideas for context? Or is that okay here? (I guess I could always just write that you have to square it after...) \$\endgroup\$ – nthnchu Oct 27 '20 at 1:18
  • \$\begingroup\$ Not quite sure what you mean here. I do think it would be good to keep the Fibonacci prism context as some motivation and flavor. I'm not suggesting removing that, but adding a formula like \$g(n)=F_n^2 + F_{n+1}^2 + F_{n+2}^2\$ (or with a square root if you want to keep that) and the definition of Fibonacci numbers \$F_n\$. I can say there's a preference here for challenges to have the task easy to read by skimming. And, to give a formula if possible and save solvers a bit of a time from doing math problem, although clever golfers may find shorter alternative ways to express or compute it. \$\endgroup\$ – xnor Oct 27 '20 at 2:32
  • \$\begingroup\$ I've edited the question. Is that what you wanted @xnor? \$\endgroup\$ – nthnchu Oct 27 '20 at 13:08
  • 2
    \$\begingroup\$ Yes, this looks good. You should still add test cases. I'd suggest also linking oeis.org/A127546. \$\endgroup\$ – xnor Oct 28 '20 at 4:12
  • 1
    \$\begingroup\$ I think the first test case ought to be 1 ==> 6 \$\endgroup\$ – Giuseppe Oct 28 '20 at 21:15
  • \$\begingroup\$ @Giuseppe Yeah, you're right. Thanks for the correction! \$\endgroup\$ – nthnchu Oct 28 '20 at 22:12
  • \$\begingroup\$ I made some clean-up edits, in part to avoid references to programs and functions, since either is allowed by allowed. \$\endgroup\$ – xnor Oct 29 '20 at 0:38
  • \$\begingroup\$ @xnor Thank you! When should I post this (out of the sandbox)? (I'm new :D) \$\endgroup\$ – nthnchu Oct 29 '20 at 22:18
  • \$\begingroup\$ @nthnchu The usual recommendation is 3 days minimum, but it's really up to you. I just read through it again, and I think it all looks good. One minor thing is that we allow zero-indexing for sequence challenges by default, which would allow doing the mapping as 0 ==> 6, 1 ==> 14, .... So I think it would be good to say that input may be taken zero-indexed to remind solvers of this. \$\endgroup\$ – xnor Oct 29 '20 at 22:43
  • \$\begingroup\$ @xnor I choose the 1 index off of \${F_1}^2+{F_{1+1}}^2+{F_{1+2}}^2 = 6\$. 0 would therefore be \${F_0}^2+{F_{0+1}}^2+{F_{0+2}}^2 = 2\$. The index is based off of \$F_0=0\$ and \$F_1=1\$ \$\endgroup\$ – nthnchu Oct 29 '20 at 23:08
2
\$\begingroup\$

I only want some primes, not all of them

It is well known that there are various formulae for calculating primes that span from calculating a subset of primes, to all possible primes. However, for this challenge, I only want a specific subset.

You are to write a program which takes a single natural integer \$n>0\$ as input. This program will then output a function, \$f(p)\$, which will take a integer \$p\ge0\$ and do the following:

  • If \$p < n\$, return the \$p\$th value of a contiguous subset length \$n\$ of primes
  • If \$p \ge n\$, returns a non-prime integer (including \$0\$, \$1\$ and negative integers).

For example, Euler's quadratic \$p^2+p+41\$ returns the \$p\$th value of the subset of primes \$\{41, 43, 47, ..., 1601\}\$ for \$0 \le p \le 39\$. However, for \$p=43\$, this returns \$1933\$, which is prime, so this would not be a valid function to return for \$n = 40\$.

You may choose the subset (and it may differ for different \$n\$), so long as it is finite and contiguous. You may also choose to use 1-indexing for \$p\$, meaning that \$f(p)\$ returns primes for \$1 \le p \le n\$.

You may output in the most natural form of a function in your language. For example, Jelly would return a string representing a link, Python would return a named function or lambda etc.

This is so the shortest code in bytes wins.


Meta

\$\endgroup\$
4
  • 1
    \$\begingroup\$ 1. Why output a function and not just have a program with two inputs? 2. Maybe you should note that 0, 1, and negative numbers are not prime. 3. I also think you should clarify that "length n" refers to the subset, not its elements. That intially confused me for a while. 4. What if \$p\$ or \$n\$ is negative? Or zero? - is the "\$p\$th value" using a 0-based index? \$\endgroup\$ – pxeger Nov 3 '20 at 20:20
  • 1
    \$\begingroup\$ @pxeger 1. the idea of the challenge is based on prime calculating formulae, so I want submissions to return "a formula" for a given \$n\$, rather than just a single value for two values \$n\$ and \$p\$. Whether the "formula" is a mathematical one or just "if \$p<n\$ then ... else ..." is irrelevant. 2, 3, 4. All clarified \$\endgroup\$ – caird coinheringaahing Nov 3 '20 at 20:26
  • \$\begingroup\$ "a natural integer \$p \ge 0\$" - zero isn't technically a natural number. Personally I think you should just drop the "natural" because an inequality is clearer. \$\endgroup\$ – pxeger Nov 3 '20 at 20:29
  • \$\begingroup\$ @pxeger There's some disagreement about whether \$0\$ is natural or not (something I've had to deal with in past challenges), but I agree, the inequality + just "integer" is much clearer \$\endgroup\$ – caird coinheringaahing Nov 3 '20 at 20:30
2
\$\begingroup\$

Question has been posted

\$\endgroup\$
1
  • \$\begingroup\$ Seems to be a heavy dictionary-ing challenge that might not make it suitable, but otherwise cool idea. \$\endgroup\$ – Beefster Nov 9 '20 at 20:16
2
\$\begingroup\$

Middle-Square RNG: What Number Came Before? (WIP)

A well-known, but statistically poor, way of generating random numbers is to square the number and take the middle digits (when expressed in base 10)

Your task is to take a 4-digit number as input and output any 4-digit number that produces the input number (there may be more than one, which is one of the statistical flaws of this method) when applying middle-square. If the square has an odd number of digits, take an extra digit off the left side.

If there is no such number (some numbers with this method have no predecessor- yet another statistical flaw), indicate that clearly in a way that cannot be mistaken as a valid answer. Some possible ways of indicating this:

  • Output nothing
  • Output null/None/nil/false
  • Output an empty list
  • Output a negative number
  • Output an error message that is clearly not a 4-digit number
  • Throw an exception
  • Crash
  • Exit with a nonzero status

\$\endgroup\$
2
  • \$\begingroup\$ Is there a theoretical guarantee that any number if attainable? (i.e. is there always a solution?) \$\endgroup\$ – Robin Ryder Nov 23 '20 at 8:21
  • \$\begingroup\$ @RobinRyder no. Some numbers have no predecessor. \$\endgroup\$ – Beefster Nov 30 '20 at 21:11
2
\$\begingroup\$

Operational countdown

  • Posted.
\$\endgroup\$
2
  • \$\begingroup\$ How to handle floating point imprecision in this given that your doing floating point division and roots then checking to see if those are integers? I cooked up a solution in Perl that is off by 1 on several of your examples because as it gets near 1, the subtraction ends in .999999...... \$\endgroup\$ – Xcali Dec 3 '20 at 4:15
  • \$\begingroup\$ @Xcali it's a trivial part of the challenge, this kind of problem is common to many languages, anyway I think that Perl, like most of languages, can handle integer numbers properly. \$\endgroup\$ – AZTECCO Dec 3 '20 at 5:11
2
\$\begingroup\$

A Snake, A Camel And A Kebab.

As many of you will know, almost every programming language has a standard casing system; unfortunately, we have not been able to agree on a singular system to use and now must frequently switch between camelCase, snake_case and kebab-case.

Now I know what you're thinking... wouldn't it be nice if we had a program that could convert from one casing to another?
Well - soon we're going to have plenty!!! (This is where you come in)

Challenge

You're job is to write a program/function that will take an input string, and a casing system. It will then print/return the converted string.

Inputs:

You're program will receive two inputs, an alphabetic string that is to be converted and a string that will always be one of kebab camel or snake.

Outputs:

You're program should output a string that conforms to the new casing if it is possible. If the input string was invalid, and had mixed casing, you're program should print/do nothing.

Test Cases:

Valid Examples:
"aJavaVariable", "snake" = "a_java_variable"
"a_python_variable", "kebab" = "a-python-variable"
"golf", "camel" = "golf"
"", "snake" = ""
"doHTMLRequest", "kebab" = "do-h-t-m-l-request"

Invalid Examples (no output):
"an_InvalidName", "kebab"
"invalid-inPut_bad", "camel"

Additional Info:

  • As most programming languages prefer lowercase variable names, you should convert all letters to lowercase unless it is needed to be upper case for camel casing.

Meta

  • Is this a duplicate? I couldn't find any quite like it.
  • Are the rules clear?
  • Would it lead to more creative answers if I remove the possibility of being given invalid input, and assume all input will be valid?
\$\endgroup\$
4
  • 3
    \$\begingroup\$ I think you should remove the invalid input handling, as it might only increase the code length.. \$\endgroup\$ – vrintle Dec 14 '20 at 3:41
  • \$\begingroup\$ Very very similar to this,, except there's an extra casing requirement. \$\endgroup\$ – Razetime Dec 14 '20 at 3:45
  • 1
    \$\begingroup\$ @Razetime Good find. I think that although the premise of the question is very similar, the difference in triggering which case to convert to, will lead to very different code logic. \$\endgroup\$ – Scott Dec 14 '20 at 20:23
  • \$\begingroup\$ Suggested expansion: PascalCase \$\endgroup\$ – Beefster Dec 14 '20 at 23:47
1
24 25
26
27 28
104

You must log in to answer this question.

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