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

2962 Answers 2962

1
…
23 24
25
26 27
…
99
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\$
  • \$\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 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 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\$
  • \$\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 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\$
  • \$\begingroup\$ This may qualify for the quine tag but I'm not so sure about that \$\endgroup\$ – golf69 Aug 4 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 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 at 9:05
  • 3
    \$\begingroup\$ I do think so, yes (also it might be better received that way) \$\endgroup\$ – golf69 Aug 4 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 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 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 at 9:06
  • \$\begingroup\$ Posted here with some changes listed in this edited answer. \$\endgroup\$ – SomoKRoceS Aug 9 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\$
  • 3
    \$\begingroup\$ This is extremely complicated. I feel like this will be in unanswered for a while. \$\endgroup\$ – Razetime Aug 10 at 17:04
  • \$\begingroup\$ In the second example, how is ceramic destroyed without giving out any lower class bloons? \$\endgroup\$ – Bubbler Aug 11 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 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 at 23:35
  • \$\begingroup\$ actually RBE calculating is probably a bit too simple \$\endgroup\$ – thesilican Aug 19 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\$
  • \$\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 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 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 at 9:47
  • \$\begingroup\$ @Bubbler Oh, okay then. So if no one objects I'll post this to main. \$\endgroup\$ – null Aug 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 at 11:20
  • \$\begingroup\$ Or: errors terminate the program. \$\endgroup\$ – user253751 Aug 24 at 13:29
  • \$\begingroup\$ @user253751 Yes, that's also good. Although, I prefer it this way. \$\endgroup\$ – null Aug 24 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\$
  • \$\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 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 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 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 at 12:08
2
\$\begingroup\$

Brainfuck arbitrary precision multiplication

Goal

The goal is to multiply two numbers in the shortest amount of cycle.

The Input

The input is two numbers written decimally separated by a space. The number is NOT restricted by the size of the integer inside of the cells. The program must accept arbitrary sized integer

The Output

The output is a single integer written decimally.

Brainfuck variants used

Since the flavors of the Brainfuck is important in this challenge, you are required to use this flavor

Memory

The memory is an array of cells, unbounded to the left and the right, with 8-bit integer as the contents.

Input/Output

The input and the output uses ASCII symbol mapping. EOF is interpreted as \0 char.

Looping

The [ means that "check the current cell. If it's zero, jump to the instruction after the matching ]" The ] means that "jump to the matching [." no cycle is taken in this instruction.

Cycle

Every instruction takes a single cycle every time it's executed except for ]. ] is a free instruction.

Reference implementation

For the reference implementation, use copy.sh with this option:

  1. Cell size (Bits): 8
  2. Dynamic (infinite) Memory: yes
  3. End of input: char: \0
  4. Count instructions

Scoring

The program with lowest worst computational complexity (counted by using cycle metric as explained above, and in x where x is the length of the largest input in base 10) is the winner. In case of a tie, the winner is a program that takes the least cycle to execute 1234567890*987654321

| |
\$\endgroup\$
  • \$\begingroup\$ fastest-code is the winning criterion tag, so you don't need code-challenge. To lower the obstacle before starting to work on the challenge, I suggest to use the copy.sh online interpreter as the standard. (I think it satisfies the cycle count rule?) \$\endgroup\$ – Bubbler Sep 3 at 7:02
  • \$\begingroup\$ @Bubbler Actually, I designed my challenge with copy.sh as the reference. The only difference is that the memory tape is not unbounded to the left. \$\endgroup\$ – Xwtek Sep 3 at 7:25
  • \$\begingroup\$ You can set "memory overflow behavior" to "abort" for that. \$\endgroup\$ – Bubbler Sep 3 at 7:39
  • \$\begingroup\$ @Bubbler It's not possible to have both infinite memory and abort as memory overflow behavior. I changed the challenge so that the memory is also unbounded to the left. \$\endgroup\$ – Xwtek Sep 3 at 7:42
  • \$\begingroup\$ Can we make assumptions such as 'the number of digits in the numbers is less than X' or 'the number of digits in the number of digits in the numbers is less than X'? \$\endgroup\$ – the default. Sep 5 at 14:32
  • \$\begingroup\$ @thedefault. No. The program must handle arbitrary sized number. \$\endgroup\$ – Xwtek Sep 5 at 15:57
  • \$\begingroup\$ @Xwtek So it would be impossible to answer it in a flavor with 30000 cells of one byte each? I think the limit on the size of each number should be half of the number of cells (and thus infinite for flavors with infinite cells) \$\endgroup\$ – Redwolf Programs Sep 9 at 23:30
  • \$\begingroup\$ @RedwolfPrograms Yes, it's impossible. Maybe I'll make a challenge to minimize memory use, but for now, you have to use infinite flavors. "I think the limit on the size of each number should be half of the number of cells" Not necessarily, I bet you need much more memory than that. \$\endgroup\$ – Xwtek Sep 11 at 2:20
2
\$\begingroup\$

Posted lol ;P

| |
\$\endgroup\$
  • \$\begingroup\$ Heeeere we go again. \$\endgroup\$ – Razetime Sep 2 at 1:34
  • 1
    \$\begingroup\$ Something that I noticed last time around was the 'you can add or change' limit means that programs can only grow. I'm not sure that this is intended, and it also has the effect that newly-arriving programs (which will tend to be shorter since they haven't yet 'grown' by successive additions) can trivially outlaw already-running programs. \$\endgroup\$ – Dominic van Essen Sep 2 at 9:15
  • 2
    \$\begingroup\$ Aside from the initial program, why isn't this a duplicate of the first version? \$\endgroup\$ – caird coinheringaahing Sep 2 at 23:16
  • 1
    \$\begingroup\$ @cairdcoinheringaahing the starting rules, as well as the new permanent rules make gameplay different enough to last time. \$\endgroup\$ – Lyxal Sep 3 at 0:36
  • \$\begingroup\$ Here's another observation that I thought-of during the last time around. It would have been too easy for any of the players to effectively 'ban' another running program when it gets too close to winning. For instance, ppery's program at turn 8 was obviously only a trivial modification away from winning, and it would have been easy but boring to introduce a rule like 'str language is forbidden'... \$\endgroup\$ – Dominic van Essen Sep 7 at 12:25
  • \$\begingroup\$ ...so, it would be worth considering a limitation to new rules, along the lines of: "any new rule must allow all currently-valid running programs to be legally-modified to comply with the new rule, when run in the same language". Of course, this is still quite open to 'playing dirty', since a required 'legal modification' might entail changing every character in the program... \$\endgroup\$ – Dominic van Essen Sep 7 at 12:26
  • \$\begingroup\$ @DominicvanEssen I've added a new deadlock section. Does that sound like what you meant? \$\endgroup\$ – Lyxal Sep 8 at 1:28
  • \$\begingroup\$ Yes, that's what I had in mind. I think this would make the rules much more interesting. And I still hope that some of the other players (and commenters) from the first round will also give their views, too... \$\endgroup\$ – Dominic van Essen Sep 8 at 14:54
  • 2
    \$\begingroup\$ You should explicitly specify whether implicit farkles count toward "you cannot answer twice in a row". That is, if you answer, and then nobody else answers for a week and there is an implicit farkle, can you answer again? \$\endgroup\$ – pppery Sep 8 at 21:28
  • \$\begingroup\$ Also, the deadlock rule defeats the point of language restrictions (since every rule than restricts languages is either useless or deadlocks at least one answer) \$\endgroup\$ – pppery Sep 8 at 21:41
  • \$\begingroup\$ Another thing to specify is which other rules the deadlock rule takes into account. Only the new rule? The new rule and the permanent rule about irreducibility? All rules that apply to new answers. \$\endgroup\$ – pppery Sep 8 at 21:55
  • \$\begingroup\$ This isn't code-challenge since answer-chaining is a winning criterion tag by itself when the win condition is "last answer". Also, if nobody answers for two weeks, are their two implicit farkles in a row? I previously thought so, but if you interpret them as turns taken by the community user, then it would get stopped by the "you can't answer twice in a row" rule. \$\endgroup\$ – pppery Sep 10 at 1:13
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\$
  • \$\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 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 at 18:16
  • \$\begingroup\$ But when do you take 720?? /s \$\endgroup\$ – Jo King Sep 21 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\$
  • \$\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 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 at 22:03
  • \$\begingroup\$ Related \$\endgroup\$ – Beefster Sep 28 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\$
  • \$\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 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 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 at 1:14
  • \$\begingroup\$ @cairdcoinheringaahing Yes. I added a test case (last one) for that \$\endgroup\$ – HyperNeutrino Oct 2 at 1:15
2
\$\begingroup\$

Posted

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ To your questions: No, I think the simplified version you've outlined already makes a good challenge. It focuses on precedence, without having to bring associativity into it. And the mixed identifiers would just make solutions more complicated without adding interest to the challenge. If I were to suggest a change, it might be to allow all identifiers matching [A-Za-z0-9_]+ (that is, \w+)--if that is a valid subset of Scala identifiers. I could go either way on that one: it makes things easier for regex solutions but harder for non-regex solutions. \$\endgroup\$ – DLosc Sep 30 at 3:10
  • 1
    \$\begingroup\$ Some clarifications: 1) Will all the operators be binary (not unary)? 2) Can we assume there will always be a single space between operators and identifiers? 3) Is (expr op expr2) op2 expr3 (without the outside parens, like your earlier example) a valid output format? 4) Unless you have a specific reason not to, I would suggest allowing the default I/O methods. For example, your current rules technically exclude input by command-line argument, which is the most natural input method in some languages. \$\endgroup\$ – DLosc Sep 30 at 3:25
  • \$\begingroup\$ @DLosc You make some good points. I've edited the question a bit, but I believe \w+ will still match [A-Za-z], so I've left that in for now. I may change it later to let people choose if they want just uppercase or just lowercase. \$\endgroup\$ – user Sep 30 at 13:15
  • \$\begingroup\$ Ah, good point that [0-9_] aren't used anyway. And now that spaces are guaranteed, it's also less important, since \S+ will match both names and operators--and since all operators are binary, that won't result in any parsing ambiguities. \$\endgroup\$ – DLosc Oct 3 at 2:03
  • 1
    \$\begingroup\$ One final nitpick: I don't think requiring parentheses around the whole expression makes sense, since the same thing without the outer parentheses qualifies as "Some tree-like structure equivalent to the above 2 representations." I like the optional parens around atoms; I would suggest making the outer parens optional too. More flexible I/O formatting is (almost always) better. \$\endgroup\$ – DLosc Oct 3 at 2:04
  • 1
    \$\begingroup\$ @DLosc Good idea. I'm posting this to the main site now, and I'll change that question itself instead of this. Thanks for all the help! \$\endgroup\$ – user Oct 4 at 0:16
2
\$\begingroup\$

Output all of printable ASCII using all of printable ASCII

Posted

| |
\$\endgroup\$
  • \$\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 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 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 at 18:48
  • \$\begingroup\$ Can my program contain additional non-ASCII bytes? \$\endgroup\$ – Adám Oct 12 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 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 at 19:03
  • \$\begingroup\$ Perhaps subtract 95 from each score so that scores look more reasonable \$\endgroup\$ – Lyxal Oct 13 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 at 10:55
2
\$\begingroup\$

Secret ">" Stacking Challenge: cheating

Sequel to Secret ">" Stacking Challenge: grading. You can skip the whole Background section if you already read the first one.

Background

Tetris Grand Master 3 has a hidden grading system based on the shape of the stack at the end of the game, which is called Secret ">" Stacking Challenge. It consists of entirely filling the lowest rows except for the zigzag pattern which starts at the left bottom cell and spans the entire width:

#
.#########
#.########
##.#######
###.######
####.#####
#####.####
######.###
#######.##
########.#
#########.
########.#
#######.##
######.###
#####.####
####.#####
###.######
##.#######
#.########
.#########

The board is graded by how many lines follow this exact pattern from the bottom line. Note that the topmost hole in the pattern must be blocked by an extra piece of block. If you consider the #s and .s as the mandatory pattern (blanks can be anything), you can get the score of 19 only if the exact pattern above is matched from the bottom line. Analogously, if the board matches this pattern

   #
###.######
##.#######
#.########
.#########

but not

    #
####.#####
###.######
##.#######
#.########
.#########

then the score is 4.

For this challenge, consider a board of arbitrary size (other than 20 cells high and 10 cells wide). We can grade the board for the same pattern: for example, if the board has width 4, this is the pattern for score 3:

  #
##.#
#.##
.###

and this is the pattern for score 10:

   #
###.
##.#
#.##
.###
#.##
##.#
###.
##.#
#.##
.###

Challenge

Given the board width and the desired score for Secret ">" Stacking Challenge, pick a sequence of tetrominoes and generate the sequence of moves that will achieve the score. The Tetris moves can be represented in any ways that clearly specify where each tetromino is placed in which orientation, optionally along with the board state after each placement.

For the Tetris movement rules, we use simple permissive rule as in this challenge: you can place a tetromino anywhere (even in closed rooms), as long as it doesn't float in the air or overlap with existing pieces. Therefore, if you plan to use coordinates, you need to specify both x and y coordinates (the y coordinate should be counted from the bottom, as the board can grow upwards without bound -- or count from the top by also outputting the field height).

You can assume the width is at least 5 and the score is nonzero. You should theoretically support arbitrarily high score. The generated sequence doesn't need to be minimal.

Standard rules apply. The shortest code in bytes wins.

Output example

For board with 6 and score 2, one possible way is as follows: (As are the tetromino placed at each turn, # are existing pieces on the board, and . are empty cells)

......  ......  ......  ......  ......
A.....  #.....  #.....  .AA...  .##AA.
AA....  ##AA..  ####AA  #.AA..  #.##AA
.A....  .#AA..  .###AA  .#####  .#####

The above is a valid output format (you can choose any distinct chars/values in place of .A#). The following is also valid (although it is less obvious, it is indeed an unambiguous description of tetromino placements):

......  ......  ......  ......  ......
A.....  ......  ......  .AA...  ...AA.
AA....  ..AA..  ....AA  ..AA..  ....AA
.A....  ..AA..  ....AA  ......  ......

And this: (tetromino code, rotation, x and y coordinates from bottom left, 0 indexed)

S 1 0 0
O 0 2 0
O 0 4 0
Z 0 1 1
Z 0 3 1

And anything in between (e.g. showing tetrominos as a canonicalized matrix instead of a code). If in doubt, ask in comments.

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

Political Simulator

(Taken over from HyperNeutrino)

It's election time, and your job is to beat your competitor in a head-on rivalry! You are both trying to win over a city of 256 people in a 16x16 grid. Right now, the city hasn't been divided into voting regions yet, but that's where your gerrymandering skills come in! You can also campaign in arbitrary areas of the city to gain support.

General

All bots will be run against all other bots once per game. In each game, the city will start out with all voters being neutral. The game will keep track of a number for each voter, determining who they support. From a particular bot's perspective, a positive number means that voter will vote for them, while a negative number is a vote for the opponent. Zero is neutral.

Both bots start with $100, and can move once per turn. These moves are run effectively simultaneously, so there is no first turn advantage. Moves fall into four categories:

  • Campaigning: This will cause every person in a specific area to increase their support for the candidate who is campaigning. The amount it changes depends on their neighbors.
  • Polling: This will get the average support for the candidate in a specific area.
  • Bribing: This will cause a particular person to increase their support for the candidate.
  • Region Merging/Unmerging: This will reshape voting regions.

At the end of each turn, after both candidates have moved, both will recieve $25.

Details

The following moves are allowed. If an invalid move is given (insufficient money or invalid coordinates), the bot's turn will be skipped.

All coordinates should be within 0 <= n < 16, and for the second pair in rectangular bounding areas 0 <= n <= 16 (as these are exclusive).

  • campaign([x, y], [x, y]): Campaign within the boundary determined by the two coordinate pairs
    • Costs $1 per person affected
    • Each person within the area will change their support according to the following rules:
      • For all neighbors orthogonally (including diagonals) adjacent and within the boundary, add 0.05 support for whichever candidate they support, or 0.15 if their support is at least 1.5 for that candidate
      • Add 0.25 for the candidate who is campaigning
  • poll([x, y], [x, y]): Poll within the boundary determined by the two coordinate pairs
    • Costs $0.25 per person polled, rounded up
    • On the next turn, the following information is given about each person in the area (after the opponent's move):
      • Their support for the polling candidate, where positive numbers indicate a vote for them, and negative numbers being a vote for the opponent
  • bribe([x, y]): Bribe the person at the location determined by the coordinate pair
    • Costs at least $5
      • For every time a person within the voting block (not the voting region) has been bribed, add $0.25 (and round down)
    • Add up to 3.5 support for the bribing candidate
      • For every time a person within the voting block has been bribed, the support added is decreased by 0.15
      • Eventually, this can cause bribing someone in a voting block to reduce their support for the candidate
  • merge([x, y], [x, y]): Merge the voting regions determined by the two coordinate pairs
    • Costs $25 for every block in the larger region
    • Requires the regions which contain the two people specified to be touching
      • Note that the coordinates correspond to people, not blocks. To reference a block, just multiply its coordinates by 4
  • unmerge([x, y]): Unmerge the voting region determined by the two coordinate pairs
    • Costs $15 for every block in the region
    • Every block in the region becomes its own region

Winning

At the end of each turn, after both candidates have moved, all regions will have their votes added. Each person will either vote for one candidate or be neutral, regardless of by how much (i.e., a score of +0.05 or +30 would be identical here). If the following conditons are met, an election will be held and the winner chosen:

  • All regions are made up of less than half neutral voters
  • The number of regions voting for each candidate are not tied

I/O

All bots should be submitted in the form of Javascript functions. The following information will be provided as arguments to the function:

  • An array of voting regions, represented as objects with the following properties:
    • blocks: An array of voting blocks, represented as the coordinates [x, y] of the top-left person (such as [4, 0] or [12, 12])
    • number_neutral: The number of people in the region who are neutral
    • number_you: The number of people in the region voting for the bot
    • number_opponent: The number of people in the region voting for the bot's opponent
    • absolute_average: The average absolute value of people's support for a candidate
      • Higher numbers indicate campaigning or bribing will typically be less effective
      • Exactly 0 would mean every person in the region is neutral
  • The amount of money the bot has
  • An object containing the results of the last move (empty unless it was a poll)
    • An array people will contain objects representing each person polled:
      • position: The person's coordinates, formatted as [x, y]
      • region: The numbered ID of the region the person is in (the region's index in the first argument)
      • support: A number indicating whether the person is neutral (0), voting for the bot (positive), or voting for the bot's opponent (negative)
    • An object amounts containing the following properties:
      • number_neutral: The number of people in the region who are neutral
      • number_you: The number of people in the region voting for the bot
      • number_opponent: The number of people in the region voting for the bot's opponent
      • absolute_average: The average absolute value of people's support for a candidate
  • An object that can be used for storage between turns (but not between rounds/games)

To move, the result one of the functions above should be returned. For example:

{
    "Example": (regions, money, result, storage) => {
        storage.block = ((storage.block || 0) + 1) % 16;
    
        return campaign(
            [(storage.block / 4 | 0) * 4, (storage.block % 4) * 4],
            [(storage.block / 4 | 0) * 4 + 4, (storage.block % 4) * 4 + 4]
        );
    }
}

Rules

  • Bots should take a reasonable amount of time to run
  • Bots should play fairly, no manipulating the controller or other submissions in ways not allowed here
  • Every bot will be run against every other bot once, with the winner being the bot which wins most often
    • In the event of a tie, the earlier bot wins
  • Invalid return values or bots that error will assume no move for the turn
  • Bots must be deterministic

Sandbox

  • Is this game balanced? Is there room for strategy?
  • Is there anything unclear? Is it difficult to read ("wall of text" or similar)?
  • Is there anything repetitive or unnecesary? Underspecified?
| |
\$\endgroup\$
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
\$\begingroup\$

Polygon prefixes

Polygons are named after the number of sides that they have. A pentagon has 5 sides, an octagon has 8 sides. But how are they named? What's the name for a 248-sided polygon?

All polygons are suffixed with -gon. There are specific prefixes for each polygon depending on the number of sides. Here are the prefixes for the lower numbers:

3 - tri
4 - tetra
5 - penta
6 - hexa
7 - hepta
8 - octa
9 - nona
10 - deca
11 - undeca
12 - dodeca
13 - triskaideca
14 - tetradeca
15 - pentadeca
16 - hexadeca
17 - heptadeca
18 - octadeca
19 - nonadeca
20 - icosa

Polygons with 21 to 99 sides have a different system. Take the prefix for the tens digit (found on the left column), the ones digit (right column below), and then stick a "kai" between them to get (tens)(ones)gon.

20 - icosi       | 1 - hena
30 - triaconta   | 2 - di
40 - tetraconta  | 3 - tri
50 - pentaconta  | 4 - tetra
60 - hexaconta   | 5 - penta
70 - heptaconta  | 6 - hexa
80 - octaconta   | 7 - hepta
90 - nonaconta   | 8 - octa
                 | 9 - nona

The 3-digit sided polygons are named in a similar fashion. A 100-sided polygon is called a hectogon. Take the hundreds digit, find it on the column for ones digits, then stick a "hecta" to its right. Now number off the tens and ones like above: (hundreds)hecta(tens)(ones)gon. If the hundreds place digit is a 1, don't put the prefix behind "hecta".

So, given an integer (3 <= n <= 999), return the name of an n-sided polygon. n-gon is not a valid answer :P

As with all code golf, shortest code wins.


Is the description good? Would it be harder if I instead asked for the number of sides, given a name?

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ What is a 101-sided figure called? "hectahenagon"? Is "hena" from the column for ones digits you mention? If so, then what is a 111-sided figure called? I'd say "hectaundecagon", but then that comes from a column where "hena" is not present. \$\endgroup\$ – Gaffi Feb 11 '13 at 11:15
  • \$\begingroup\$ @Gaffi: Yep, it's hectahenagon, from what Google says. \$\endgroup\$ – beary605 Feb 11 '13 at 16:03
  • \$\begingroup\$ I am going to take this if you allow me or if you don't respond \$\endgroup\$ – Christopher May 30 '17 at 1:13
1
\$\begingroup\$

Self-Golfing Code?

I don't know if I just didn't search hard enough, but I couldn't find any challenge regarding self-golfing code, or rather, any code that can deterministically reduce another set of text code to a much smaller program, yet still compile/run.

For example, take this:

int main() {
std::cout<<"Hello world 1!"<<std::endl;
std::cout<<"Hello world 2!"<<std::endl;
std::cout<<"Hello world 3!"<<std::endl;
std::cout<<"Hello world 4!"<<std::endl;
std::cout<<"Hello world 5!"<<std::endl;
}

And output this (as one possible solution):

#define A std::cout<<"Hello world 
#define B !"<<std::endl;
#define C B A
int main() {
A 1 C 2 C 3 C 4 C 5 B
}

Alternative:

Sub MySub()
Dim aNumber As Integer
Dim someString As String
aNumber = 123
someString = "abc"
MsgBox aNumber
MsgBox someString
End Sub

into (again, as one possible solution)

Sub m()
Dim a As Integer
Dim s As String
a = 123
s = "abc"
MsgBox a
MsgBox s
End Sub

Do we have a challenge for this?

If not, here are some rules I envision:

  • Golfing code need not be in the same language as code to be golfed.
  • Since compilers/running of code varies, newly golfed code must still run under same environment.
  • Possible challenge scoring (multiple options -- thinking code golf):
    • 1: Shortest golfing code wins (not my favorite, since you can minimally shorten the base code, yet still write the shortest program).
    • 2: Shortest output of a set of pre-defined code (potentially limiting if participants are unfamiliar with the options available)
    • 3: Combination of length of golfing code and the output result of the same as input. (Ratio, summation, etc.) -- This I think is my preferred option.
    • 4: Multi-player Ratio of golfed size of other participants' own code versus their original submission. (Similar limitations to that of point #2.)
| |
\$\endgroup\$
  • 1
    \$\begingroup\$ Sounds more like an auto-golfer than obfuscation. Seems like it would be very hard to make it a fair contest unless you pick a language to golf, and even then it had better be a simple language (no platform dependency issues or compiler options). \$\endgroup\$ – Peter Taylor Feb 13 '13 at 15:15
  • \$\begingroup\$ @PeterTaylor My examples are golfing, but either would work. Perhaps golfing would be simpler, then? I agree that the options for usable languages makes this a bit messy... Would one challenge per language be acceptable? (i.e. aligned with most challenges that are language-agnostic) \$\endgroup\$ – Gaffi Feb 13 '13 at 17:36
  • 2
    \$\begingroup\$ Language-agnostic to mean means that you can write a program to do it in any language. Since the language to be golfed can be different from the submitted program, I don't see any incompatibility between making the problem "Write a program to golf Piet" and being language-agnostic. \$\endgroup\$ – Peter Taylor Feb 15 '13 at 0:18
  • \$\begingroup\$ @PeterTaylor So then you see no problem with one question per language on which to operate? Are there any proposed scoring algorithms you particularly like/dislike? \$\endgroup\$ – Gaffi Feb 15 '13 at 12:02
  • \$\begingroup\$ That depends on what you mean. If you're planning to post 10 questions at once, yes, that would be a problem. But I don't see a problem with posting a well-defined "Auto-golf Piet" and following it up two months later with "Auto-golf Perl 5". \$\endgroup\$ – Peter Taylor Feb 16 '13 at 10:19
  • \$\begingroup\$ Scoring is an issue. The halting problem means that it's impossible to write an optimal solution, so the scoring must take into account how good the solution is. I think option 3 is the best, and you'll want a big test set (maybe a few kB taken from a real-world open source project) with coverage of the language features. \$\endgroup\$ – Peter Taylor Feb 16 '13 at 10:22
  • \$\begingroup\$ Btw, your first example doesn't work. You can't have unmatched quotes in preprocessor directives. Don't know why. \$\endgroup\$ – MD XF Jan 13 '18 at 18:03
  • \$\begingroup\$ I honestly think this would be fine if you did something like solely maco-golfing, making it somewhat language agnostic because of gcc -E. \$\endgroup\$ – Zacharý Nov 10 '18 at 14:36
1
\$\begingroup\$

Missile Command

I'm making this CW, because it needs lots of help. I've been toying with this idea for a while. Think "battleship" to get in the right mind-frame. But, instead of ships, what you lay down are tiles which represent a Befunge-style program. This program controls the behavior of guided missiles ejected from the spawn tile. The goal is to program a missile which will obliterate an opponent's program block, as well as guard its own control block.

Haven't nailed-down the board size. 20x20 seems a little cramped.

         1         2
12345678901234567890
____________________1  4x20 program block
____________________2
____________________3
_______@____________4
....................5  12x20 arena
....................6
....................7
....................8
....................9
....................01
....................1
....................2
....................3
....................4
....................5
....................6
___________@________7  4x20 program block
____________________8
____________________9
____________________02

Tiles

@ spawn

Program control.

I'm imagining these to change direction of the code for "boustrophedon" writing.

this,then\
 txen,siht

haven't thought it all though, yet.

/

\

Movement.

F forward move forward one square

B back move back one square

L left turn left 90°

R right turn right 90°

So the submissions would be 4x20 code blocks which compete in a king-of-the-hill style.

| |
\$\endgroup\$
  • \$\begingroup\$ If this is deterministic, won't it be "Last person to submit their program wins"? \$\endgroup\$ – Peter Taylor Jun 7 '13 at 8:39
  • \$\begingroup\$ That is a danger, yes. I'm hoping ways around it can be found. There could be a random operator. And proximity detection, or something. \$\endgroup\$ – luser droog Jun 7 '13 at 8:46
1
\$\begingroup\$

Find all of the Scrabble numbers:

A scrabble number is a number n whose scrabble representation can score n points. As an example consider 12: its English spelling twelve has value 12 when it is placed on a stretch of six blank tiles. Since the highest ever reported 1 word scrabble score barely exceeds 2000 points, that will be the upperbound for this challenge.

Score and quantities for English:

2 blanks |  x1  |  x2  |  x3  |  x4  |  x6  |  x8  |  x9  |  x12 |
    1    |      |      |      | LSU  | NRT  | O    | AI   | E    |
    2    |      |      | G    | D    |      |      |      |      |
    3    |      | BCMP |      |      |      |      |      |      |
    4    |      | FHVWY|      |      |      |      |      |      |
    5    | K    |      |      |      |      |      |      |      |
    8    | JX   |      |      |      |      |      |      |      |
   10    | QZ   |      |      |      |      |      |      |      |

Considerations for either bonus points to scoring or extra requirements:

  • Respect the board, only using gaps between double/triple letter and double/triple word scores that occur on a standard scrabble board.
  • Respect the tile count for each letter.
  • There are non-English versions of scrabble, maybe it should be 'language-agnostic' (lol, but seriously is there a reason to accept only English submissions?).
  • Should the 2 blanks be allowed?
| |
\$\endgroup\$
  • \$\begingroup\$ What about tiles which were already on the board and so wouldn't score anything? As for language: one approach would be to make it take the names of the tiles (and perhaps the values and counts of the letters) as input; this would also prevent the problem from being effectively one of Kolmogorov complexity. \$\endgroup\$ – Peter Taylor Jun 19 '13 at 22:50
  • \$\begingroup\$ I don't believe that tiles on the board already would pose an issue. If you assume that the board may be prepared with any subset of the tiles beforehand (some may be impossible, but checking that is out of scope) all that is relevant to the problem is which are placed to complete the word. All the tiles points are counted, even the earlier placed, but only the new 7 (or less) tiles may qualify for triple/double-word/letter scores. w.r.t. kolmogorov, If I wanted to make it programming challenge instead of codegolf (so that isn't an issue) then there needs to be a scoring system right? \$\endgroup\$ – Kaya Jun 19 '13 at 23:33
  • \$\begingroup\$ Yes, if it isn't codegolf then it needs a scoring system. I'm not sure what you could use as an alternative scoring criterion, though: it's simple enough logic that pretty much any implementation would be IO-bound, so speed doesn't work; and big-O based tends to be less straightforward than you might think. \$\endgroup\$ – Peter Taylor Jun 21 '13 at 11:05
1
\$\begingroup\$

Sort all lines according to their corresponding Levenshtein Distance to the first line.

Shamelessly borrowed from: http://golf.shinh.org/p.rb?Levenshtein+Distance+Sort+FIXED

For a definition of the Levenshtein Distance, look here: http://en.wikipedia.org/wiki/Levenshtein_algorithm

Rules:

Takes input from stdin. Must work for all possible input. Get points for:

Smallest character count. Using Languages that are difficult to golf in. I think character count / the average values from here (http://golf.shinh.org/lranking.rb) might suffice?

| |
\$\endgroup\$
  • \$\begingroup\$ There are a number of ambiguities in the problem description. What is the correct behaviour if the input is empty? In the general case, should the first line be included in the lines which are sorted and output? Should the sort be by ascending or descending edit distance? How should ties be broken? \$\endgroup\$ – Peter Taylor Jun 25 '13 at 20:23
  • \$\begingroup\$ As for handicapping: are you going to prohibit built-in or library-provided edit distance functions? If not then the averages you link are not especially relevant: PHP handily wins the existing edit distance question by virtue of its built-in function. \$\endgroup\$ – Peter Taylor Jun 25 '13 at 20:27
  • \$\begingroup\$ (That existing question does also raise the possibility of yours being closed for not being sufficiently different). \$\endgroup\$ – Peter Taylor Jun 25 '13 at 20:28
1
\$\begingroup\$

Fastest Code: checking if interval pairs overlap

Given an unsorted input of many interval pairs (50+), write the fastest algorithm to determine if they do not overlap.

An interval pair is said to overlap if interval x and interval y are overlapping.

Example input 1:
interval x , interval y

10-25, 50-60
10-15, 25-60

Output:
Can be in any true false format.

false (They overlap)

reasoning:

a.x overlaps b.x
a.y overlaps b.y

Example input 2:

10-25, 50-60
20-30, 25-30

Output:

true (they do not overlap)

reasoning:

a.x overlaps b.x
a.y does not overlap b.y

Scoring:

[not sure...]
brute force gives a worst case n^2 runtime
| |
\$\endgroup\$
  • 1
    \$\begingroup\$ It's hard to understand what the program is supposed to do. It's better to give three separate self-contained test cases than to mix them together with extra identifiers which won't be in the actual input. But if I understand correctly, there's nothing difficult here at all. It's just interval overlap testing (two ifs) done twice for no obvious reason. \$\endgroup\$ – Peter Taylor Jul 5 '13 at 19:45
  • \$\begingroup\$ The problem is that there will be a very large input. I'm thinking > 50 lines. \$\endgroup\$ – EAKAE Jul 5 '13 at 20:50
  • \$\begingroup\$ I'm not sure whether or not to score it based on time, or worst case runtime. \$\endgroup\$ – EAKAE Jul 5 '13 at 20:59
  • 1
    \$\begingroup\$ Instead of asking for overlap, ask for disjoint: "Check if a family of intervals is disjoint". I also think it would be more interesting if you give intervals in interval notation but I you should at least specify whether or not the endpoints are included. \$\endgroup\$ – Justin Dec 21 '13 at 7:41
1
\$\begingroup\$

Countdown: Federal Holidays in the United States

Inspired by this question:

Christmas Countdown

Write a program or script that will countdown to the nearest U.S. federal holiday, at any given time, and will switch the display to an appropriate greeting during each holiday.

The following holidays must be tracked, and announced:

Holiday                         Date                    Greeting
==========================================================================================
New Year's Day                  Jan. 1                  Happy New Year!
Martin Luther King, Jr. Day     3rd Mon. in Jan.        Happy Martin Luther King, Jr. Day!
President's Day                 3rd Mon. in Feb.        Happy President's Day!
Memorial Day                    Last Mon. in May        Happy Memorial Day!
Independence Day                Jul. 4                  Happy Independence Day!
Labor Day                       First Mon. in Sept.     Happy Labor Day!
Columbus Day                    2nd Mon. in Oct.        Happy Columbus Day!
Veterans Day                    Nov. 11                 Happy Veterans Day!
Thanksgiving                    4th Thu. in Nov.        Happy Thanksgiving!
Christmas                       Dec. 25                 Merry Christmas!

The strings listed under "Holiday" and "Greeting" are all free. Shortcuts like "Merry X-mas!" or "Happy 4th of July" will count against you - the full and proper holiday names are free, so there's no good reason not to use them.

The following strings are also free, only when used as a label for time units or in advertising the next upcoming holiday:

days
hours
minutes
seconds
milliseconds
until
time

On any given non-holiday, the program must show a count-down timer which displays time remaining at least down to the second, and updates the display with an accurate value (according to the system clock) at least once per second. Time remaining until a holiday must be counted as the time until midnight (00:00:00) on that day.

How the days, hours, minutes, and seconds (and milliseconds, if you choose) are displayed is up to you, so long as all mandatory items are present and it is clear which numbers represent which value. Again, the strings defining units of time are free so there's no really good reason not to use them. (Though you won't be penalized for not using these strings, so long as it is still unambiguous which time units are which.) The program should also make apparent which holiday is being counted down towards.

On any given holiday, the program must cease displaying the countdown timer and instead display the appropriate greeting for that holiday from 00:00:00 until 23:59:59.

After a holiday is over, at 00:00:00 the next day, the holiday greeting must go away and be replaced with the countdown timer for the next holiday.

Answers must include:

  • Name of language
  • Score (length of golfed code, minus free characters)
  • Golfed code
  • Total length of golfed code
  • Total number of free characters used
  • Un-golfed code, with descriptive comments

The program must be capable of running accurately (according to the system clock) at any time, and must be able to run indefinitely. The only limitations to this should be those imposed by the host computer or the nature of the programming language.


Are there any additions/deletions/modifications that should be made to these rules?

I'm considering changing some of the greetings, but I'm not quite sure what to.

  • "Happy Martin Luther King, Jr. Day!" is just a mouthful and feels awkward, but shortening it to "Happy MLK Day" feels weird too - any other suggestions?
  • I'm not quite sure "Memorial Day" should really be preceded by "Happy" - thoughts?
  • Any others?
| |
\$\endgroup\$
  • \$\begingroup\$ I think it would be more interesting if the strings were not free, but you still required exact match. I would like to see the compression scheme used by contestants. \$\endgroup\$ – John Dvorak Dec 7 '13 at 12:04
  • \$\begingroup\$ @JanDvorak This is meant to be code-golf, not kolmogorov-complexity. \$\endgroup\$ – Iszi Dec 7 '13 at 22:11
  • \$\begingroup\$ This challenge proposal has been inactive for over a month. I would like to take ownership of the challenge and make it ready for posting. Please let me know within the next 14 days if you have any objections and would still like to finish and post this challenge yourself. \$\endgroup\$ – user10766 Nov 3 '14 at 2:01
1
\$\begingroup\$

Quine with syntax highlighting


I don't really have much of an idea how to properly pose a quine challenge, or what the common syntax highlighting rules are (or aren't) for various languages. So, I figured I'd just toss this concept up here for consideration and let the community flesh it out if they think it's a good idea.

| |
\$\endgroup\$
  • \$\begingroup\$ I'm pretty sure some languages don't even have syntax to highlight \$\endgroup\$ – John Dvorak Dec 13 '13 at 20:12
  • \$\begingroup\$ @JanDvorak Perhaps this would not quite be an "all languages" challenge, then - only languages which naturally lend themselves to syntax highlighting would be eligible. \$\endgroup\$ – Iszi Dec 13 '13 at 20:19
  • \$\begingroup\$ You also can't use a language that cannot render any decent GUI. Also, specifying the amount of syntax highlighting the program needs to generate will be hell. \$\endgroup\$ – John Dvorak Dec 13 '13 at 20:36
  • \$\begingroup\$ I don't think this question is feasible, due to the output restrictions and due to the difficulty in defining the minimum required syntax highlighting. \$\endgroup\$ – John Dvorak Dec 13 '13 at 21:09
  • \$\begingroup\$ I like this idea. I think you could specify an adequate level of highlighting with just keywords, strings or characters and numeric literals each having their own color. \$\endgroup\$ – Οurous Feb 28 '18 at 21:13
1
\$\begingroup\$

McDonald's Drive-Thru

Changes from original:

  • Provided some clarification of requirements with regards to impossible ordering quantities.
  • Added specification to include total cost of order.
  • Added specification to prefer lowest cost in case of a tie for number of packages.

TODO:

  • Verify package sizes and pricing to be used for this challenge.
  • Add pricing to output samples.
  • Edit or remove "not have any limitations" rule. As currently written, it may force otherwise unnecessary bloating of code in some languages. (e.g.: PowerShell can handle numbers as uint64 to work with extremely large quantities, but it defaults to int32.)

We want to write a program to help McDonald's Drive-Thru employees assist their customers in ordering Chicken McNuggets. Chicken McNuggets only come in packs of 4, 6, 9, or 20. However, customers may not always be considering this when they pull up to the speaker.

For example, a customer might want to order 50 McNuggets but they really don't care what sort of packaging they come in - they just want to make sure they get 50 McNuggets one way or another. We want to help the customers get the best value out of their order - that is, to compose an order large enough to accommodate their needs in as few packages as possible with little to no excess.

Users will provide a request for n Chicken McNuggets. Your program's task is to provide the user with the sizes and numbers of McNugget packages needed to fulfill the order exactly. If the exact order cannot be fulfilled, the system must output an order which would meet the customer's needs with as little excess as possible. The system must also provide the total cost of the order.

Rules

  • For values of n which can be ordered exactly, output how many of each pack must be ordered to achieve the requested quantity.
  • For impossible orders (1,2,3,5,7,11), print "[requested quantity] is impossible. Have [nearest valid quantity >n]:" followed by the normal output for the nearest possible quantity >n.
  • Impossible orders cannot be hard-coded. The program must be able to determine whether fulfilling an order exactly is possible without being explicitly told that 1,2,3,5,7, and 11 are impossible.
  • Output must exclude any package sizes which do not need to be ordered.
  • Output must be in descending order of package size.
  • Output must include the sum total cost of all the packages. (Tax not included.)
  • Further layout and formatting of the output is up to you, so long as it is unambiguous.
  • Program must not have any limitations beyond those inherent to the system or programming language.
  • If there are multiple ways to assemble the order in the least number of packages, output the method which has the lowest total price.

Examples:

Input: 8
Output:

2x4

Input: 43
Output:

1x20 1x9 1x6 2x4

Input: 11
Output:

11 is impossible. Have 12: 2x6

Relevant Numberphile Link


My main concern is that this problem may be too similar to this thread:

Work out change

Otherwise, are there any changes that should be made to this?

| |
\$\endgroup\$
  • 2
    \$\begingroup\$ My recommendation is to minimize the total cost of the order, rather than the number of packages. Based on these prices: fastfoodmenuprices.com/mcdonalds-prices, the costs are $2.99, $3.89, $4.29, and $5.00. This website lists the "9 piece" as "10 piece", I think that might be an error. \$\endgroup\$ – PhiNotPi Dec 14 '13 at 0:01
  • \$\begingroup\$ Why the restriction #3? \$\endgroup\$ – John Dvorak Dec 14 '13 at 6:12
  • \$\begingroup\$ I agree that it's too similar to the existing question. In addition, "nearest valid quantity" isn't unique, and you don't give any hint as to how to break ties. \$\endgroup\$ – Peter Taylor Dec 14 '13 at 10:17
  • 1
    \$\begingroup\$ @PeterTaylor Tiebreaker is specified as ">n", where "n" is the quantity requested by the user - that is, we want to give the user an option that will have at least as many nuggets as they want to order. \$\endgroup\$ – Iszi Dec 14 '13 at 23:37
  • \$\begingroup\$ @JanDvorak Essentially, to up the difficulty a notch. I figure it's a little trickier to catch the invalid quantities in the process of figuring out the answer if you can't write a simple if statement to match against the known quantities. \$\endgroup\$ – Iszi Dec 14 '13 at 23:42
  • \$\begingroup\$ @PhiNotPi Not sure if that's an error on the site, or a regional difference. The information I posted was based on the linked Numberphile video, which was made in the U.K.. It's also possible they may have changed the menu since then. Presuming that larger packages hold better value in terms of cost-per-nugget than smaller ones, the problem as stated should work itself out to the same goal as you've suggested. However, it might help to differentiate the challenge from the suggested duplicate if we add the total price into the expected output. \$\endgroup\$ – Iszi Dec 14 '13 at 23:45
  • \$\begingroup\$ My question is: how are you going to measure that? How large part of this knowledge are we disallowed from encoding? Can we memorize all but one? Can we special-case 1,2,3? Or, is it that anything goes as long as it either can be generalised to other Frobenius problems, or is inclusive, not exclusive? \$\endgroup\$ – John Dvorak Dec 14 '13 at 23:47
  • \$\begingroup\$ @JanDvorak The program should be able to work out for itself whether or not a given quantity is invalid - that's all there is to it. By its nature, I suppose that means solutions would be able to also handle other Frobenius problems. In fact, I was actually considering a separate "return the largest impossible quantity" problem, where users input several integers and the program outputs the largest quantity that cannot be achieved by adding multiples of those integers. \$\endgroup\$ – Iszi Dec 14 '13 at 23:53
  • \$\begingroup\$ Provided some updates to address comments. \$\endgroup\$ – Iszi Dec 15 '13 at 2:34
  • \$\begingroup\$ @Iszi Minimizing cost should serve as a tiebreaker for when there are multiple solutions with the minimum packaging. For example, look at N=36. The solution {0*4,0*6,4*9,0*20} works, but {1*4,2*6,0*9,1*20} is cheaper. (I used the costs {{4,2.99},{6,3.89},{9,4.29},{20,5.00}}) \$\endgroup\$ – PhiNotPi Dec 15 '13 at 3:07
  • \$\begingroup\$ @PhiNotPi Ah, I think I misunderstood when Peter said there wasn't a specifier for the tiebreaker. For some reason, I was thinking it was not possible for there to be a tie of that sort. Adding the price aspect definitely helps sort that out, then. Thanks. \$\endgroup\$ – Iszi Dec 15 '13 at 3:15
  • \$\begingroup\$ FWIW, it was my misreading. I failed to see the ">n". \$\endgroup\$ – Peter Taylor Dec 21 '13 at 12:01
1
…
23 24
25
26 27
…
99

You must log in to answer this question.

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