515
\$\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 your first try can be difficult, and there is a much better chance of your challenge being well received if you post it in the Sandbox first.

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

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

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

\$\endgroup\$
0

3283 Answers 3283

1
26 27
28
29 30
110
2
\$\begingroup\$

Simulate simple Bloons Tower Defense!

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

The task

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

Bloon types

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

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

I/O

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

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

Examples

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

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

This is the 4/0/x Sniper Monkey:

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

This is codegolf, so lowest byte-count wins

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

Solve the Halting Problem for Oneplis

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

The three commands are:

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

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

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

Test cases

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

Sandbox

  • Test cases?

  • Shall I require the answers to deal with errors?

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

Noncommutative Quineoid Triple

This is the hard mode of Quineoid Triple

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

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

Where:

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

Rules and Scoring

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

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


Cops/Robbers: Create a weak block cipher

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

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

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

The Cops' Challenge

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

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

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

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

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

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

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

The Robbers' Challenge

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

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

You must not crack your own answer.

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

Example #1

Python 3, 133 bytes (cop)

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

Try it online!

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

Python 3, cracks xxx's answer

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

Try it online!

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

Example #2

Python 3, 147 bytes (cop)

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

Try it online!

My program uses a complicated thing.

Python 3, cracks yyy's answer

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

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

Try it online!

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


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


Questions to sandbox users:

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

Take 6!

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

The Game

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

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

Therefore, there is a total of

  • 1 card with 7 cows (number 55)

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

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

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

  • 76 cards with 1 cow (all other cards)

The game is played by up to 10 players.

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

A turn

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

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

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

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

Examples:

row tops: 10 20 30 40

played: 25

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

row tops: 10 20 30 40

played: 9

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

Counting

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

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

Bots

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

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

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

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

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

The default format will be

cards 0 1 2 3 4 5 6 7 8 9

No response is expected.

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

The default format will be

count 1 2 3 4

cows 5 6 7 8

top 11 20 22 35

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

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

The default format will be

used 0 1 2 3 4 5 6 7 8 9

No response is expected.

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

The default format will be

pickrow

count 1 2 3 4

cows 5 6 7 8

top 11 20 22 35

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

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

The default format will be

cardgain 1 2 3 4 5

cowgain 6

No response is expected.

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

The default format will be

score 30

others 0 1 2 3 4 5 6 7 8

No response is expected.

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

The default format will be

invalid

A timely shutdown is expected.

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

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

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

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

Controler

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

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

Notes:

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

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

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

Sandbox notes:

Any better idea for tournament?

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

Planned tags:

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

Output all of printable ASCII using all of printable ASCII

Posted

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

Count the Collatz survivors mod 2^n

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

Round a Matrix

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

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

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

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

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

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

Example:

 A = 1.2 3.4 2.4
     3.9 4.0 2.1
     7.9 1.6 0.6

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

 B = 1   3   3
     4   4   2
     8   2   0

This is code golf, so the shortest code wins.

Motivation

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

Questions

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

The Fibonacci Rectangular Prism Sequence (posted)

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

I only want some primes, not all of them

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

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

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

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

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

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

This is so the shortest code in bytes wins.


Meta

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

Question has been posted

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

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

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

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

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

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

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

Operational countdown

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

A Snake, A Camel And A Kebab.

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

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

Challenge

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

Inputs:

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

Outputs:

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

Test Cases:

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

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

Additional Info:

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

Meta

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

How Many Atoms?

Post

\$\endgroup\$
3
  • 1
    \$\begingroup\$ So we don't need to handle (Ne(St(Ed_2)_3)_4)_5 formulas? \$\endgroup\$ – Bubbler Dec 17 '20 at 7:26
  • \$\begingroup\$ @Bubbler adding that in as a test case \$\endgroup\$ – bigyihsuan Dec 17 '20 at 16:01
  • \$\begingroup\$ Looks like your test cases have some typos. H_20 should have an answer of 20, or the 0 should be an O. Also, the third to last has an _ after a number (C_21_H...), which doesn't seem right. In general, though, if the goal here is just to count the atoms, and not to check the validity of a formula, I find that the BNF and the list of elements is unnecessary and confusing to the task at hand. It seems like the challenge is going to be about validating a formula and then it becomes something completely different. \$\endgroup\$ – Xcali Dec 18 '20 at 18:44
2
\$\begingroup\$

Based Palindromes

\$\endgroup\$
6
  • \$\begingroup\$ “All integer base 10 numbers below 1000” would include negative numbers. Based on your test cases, you should clarify that you mean non-negative or positive numbers. Also, wouldn’t 0 be a palindrome in any base? Why is it excluded from the base 2 test case? \$\endgroup\$ – water_ghosts Dec 24 '20 at 23:22
  • \$\begingroup\$ @water_ghosts alright, i've edited the problem to show that it's only from 0-1000 inclusive, as well as added 0 to the output for base 2. \$\endgroup\$ – Gio D Dec 25 '20 at 0:04
  • \$\begingroup\$ This title is a downgrade from "Based Palindromes" \$\endgroup\$ – Razetime Dec 25 '20 at 3:15
  • 1
    \$\begingroup\$ @Razetime haha, i didn't know whether "based palindromes" made it clear what the challenge was and so i changed it. I've changed it back, though. \$\endgroup\$ – Gio D Dec 25 '20 at 3:31
  • \$\begingroup\$ Related. This is a simpler challenge than most of the other challenges that ask for palindromes in multiple bases, so I think it's fine. \$\endgroup\$ – Razetime Dec 25 '20 at 3:47
  • \$\begingroup\$ Now that this has been posted, I've edited it down to save space \$\endgroup\$ – caird coinheringaahing Dec 27 '20 at 22:12
2
\$\begingroup\$

Partial sums of the kempner series

Posted

\$\endgroup\$
2
  • \$\begingroup\$ Can we output rational numbers (or numerator/denominator pairs) instead of floats? \$\endgroup\$ – Dingus Dec 31 '20 at 13:41
  • \$\begingroup\$ @Dingus , yes according to the Default I/O methods. Do you think I should specify this in the challenge? \$\endgroup\$ – Command Master Dec 31 '20 at 14:14
2
\$\begingroup\$

Eye test - How many squares are in this picture?

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

Run the lottery

Rules

Your job is to write a program to accept lottery tickets, adding all the money to a pool, and divvy out the winnings based on how many numbers each ticket has guessed correctly. The amount of money people spent on their tickets is used to determine how much each person should take home.

  1. You will receive a list of lottery tickets, which will be how much the person has paid, along with 5 numbers between 1 and 25. The numbers do not have to be unique, and order matters. [1, 2, 3, 4, 5] and [3, 2, 1, 4, 5] are considered different, and [1, 1, 1, 1, 1] is a valid ticket.
  2. You will also receive 5 numbers between 1 and 25, which are the winning numbers. This follows the same restrictions as a participant's ticket.
  3. Each participant will be given a "score" based on how many numbers they guessed correctly. They must guess the number, and guess it in the correct spot as well. [x, x, 1, x, x] is not a winning number for [1, 2, 3, 4, 5]. [1, 1, 1, 2, 3] counts as 2 correct guesses for [1, 2, 1, 1, 1].
  4. The score is \$4^n\$ where \$n\$ is the number of winning numbers. Yes, a participant with 0 correct numbers has a score of 1, and is eligible to take home some money.
  5. Each participant's final weight is their score times the amount they spent on the ticket. A person with a score of 4 (1 correct guess) and paid $4 for a ticket has the same weight as a person with a score of 16 (2 correct guesses) and paid $1 for their ticket.
  6. Finally, the prize pool is then divvied up. 10% goes to you, the lottery company. The remaining 90% gets divvied up proportionally by each participant's final weight, rounded to the cent.

The input and output of the program can be in any format. The only stipulation is that monetary values must be decimals. For instance, $15.68 cannot be represented as 1568.

Example game

The winning numbers are as follows

  • [2, 18, 1, 15, 7]

Four people bought tickets with the following prices and numbers

  • $6, [9, 5, 6, 15, 22], one match, score of 4, weight of 24
  • $2, [2, 25, 17, 7, 7], two matches, score of 16, weight of 32. Notice how only the second 7 counts, order matters
  • $67, [11, 16, 9, 20, 16], no matches, score of 1, weight of 67
  • $1, [12, 19, 6, 25, 2], no matches because the 2 is in the wrong spot, score of 1, weight of 1

The total pool is $76, $68.4 after we take our cut, which is then sent out based on the weights. The sum of all weights is 124.

  • First ticket gets 24/124, $13.24
  • Second ticket gets 32/124, $17.65
  • Third ticket gets 67/124, $36.96
  • Fourth ticket gets 1/124, a whole 55 cents
\$\endgroup\$
3
  • \$\begingroup\$ I think you should explain that the winning numbers are not necessarily distinct in rule 2, instead of leaving it until the examples. Likewise, you should state the 'order matters' rule earlier. \$\endgroup\$ – Dingus Jan 12 at 11:57
  • 1
    \$\begingroup\$ @Dingus I added those clarifications to rules 1-3. Thoughts? \$\endgroup\$ – Daffy Jan 15 at 23:46
  • \$\begingroup\$ Looks good to me. \$\endgroup\$ – Dingus Jan 16 at 5:02
2
\$\begingroup\$

Bot Factory KoTH (2.0)


Posted to main

\$\endgroup\$
8
  • \$\begingroup\$ in a way which produces side effects other than intended Can you define that more precisely? Are you allowed to use global variables to share information between a main bot and worker ones? Also can worker bots collide with their owner? \$\endgroup\$ – Command Master Jan 18 at 12:25
  • \$\begingroup\$ @CommandMaster Yes they can collide, and using global variables for any sort of communication is not allowed. I will probably add an "official" way of doing that at some point. \$\endgroup\$ – Redwolf Programs Jan 18 at 14:32
  • \$\begingroup\$ I think it could be more fun if the size of the original bot doesn't matter, but I'm not sure \$\endgroup\$ – Command Master Jan 18 at 16:00
  • \$\begingroup\$ @CommandMaster The problem with that is that you could make a bot that uses really long comments to manipulate the character pool so that the characters it needs for its worker bots appear more often \$\endgroup\$ – Redwolf Programs Jan 18 at 18:43
  • \$\begingroup\$ It might be a good idea to provide a map of the factory in the API. Also, the effect of program size on the initial score might even be too small: the difference between a program of length 100 and a program of length 5000 is less than 61 collected characters within 100000 turns. (a linear function might be better) \$\endgroup\$ – the default. Jan 22 at 15:54
  • \$\begingroup\$ @thedefault. Maybe the initial score penalty will be double the length of the program, given that there's 100k turns to make up for it. What would the output of the map be like? A 2d array? \$\endgroup\$ – Redwolf Programs Jan 22 at 16:47
  • \$\begingroup\$ @RedwolfPrograms yes (or perhaps a function .get(x,y) so that submissions can't modify the map?). I think double the length of the program would be too much. (what about half the length of the program? that'd also magically explain why creating a worker costs half its size in points) \$\endgroup\$ – the default. Jan 22 at 16:56
  • \$\begingroup\$ @thedefault. The problem with a 2d array is that it's an infinite map so if one bot is really far away from the rest you could end up with a really huge array a naive bot might be searching. I think a function like at(coords) would work well though, maybe returning an object listing all of the chars at that location, and any bots who are there. I do like the half length idea. \$\endgroup\$ – Redwolf Programs Jan 22 at 17:00
2
\$\begingroup\$

Is each bracket matched?

Given a string consisting only of the characters ()[]{}, determine if each type of bracket is matched--that is, every ( corresponds to one later ), every [ corresponds to one later ], and every { corresponds to one later } (and vice-versa).

Pairs are allowed to overlap: ([)] is just as valid as ([]).

Output one consistent value for one classification and anything else for the other, or following your language's truthiness semantics (inverted if you want).

Test cases:

Matched:

()
[]
{}
()[]{}
()()([])
{[][}]
{{{}}}
([{}]){([]})
[(()())(((())))(]()(()))

Not matched:

(
]
{{}
[)
(()())((((()))))(()()(())(())))
{}{}{)
[())[])]
)(

Meta

  • Does this admit a variety of interesting solutions?
  • Would it be better to add <> as a bracket type? Have fewer bracket types? Arbitrarily many?
  • I'm writing this up entirely because I'm surprised it hasn't been asked yet, so although I have looked, this might still be a duplicate.
  • Although I don't think it's necessarily unclear, I feel like the specification could be worded better.
\$\endgroup\$
2
2
\$\begingroup\$

Is this a valid Irish word?

In Irish, most consonants are divided into broad (velarized) and slender (palatalized) variants, and the orthography marks them with neighboring vowels, which are similarly divided. This gives rise to the caol le caol agus leathan le leathan (slender with slender and broad with broad) rule – a medial sequence of consonants must have the same class of vowel on either side: in leabhar, bh is surrounded by two broad vowels, so it is broad as well, and in cailín, l is surrounded by two slender vowels, so it is slender. a, o and u are broad and e and i are slender (similar with the vowels with the fada: á ó ú é í); ae is also considered broad.

Given a word, output whether it follows this rule.

Input

You may assume that the input has only the following characters with their uppercase variants:

aábcdeéfghiílmnoóprstuú
AÁBCDEÉFGHIÍLMNOÓPRSTUÚ

Tests

Valid:

deartháireacha
madra
nuachtán
gaolta
ceannasaithe
snámhann
fómhair
laethanta
béar
Bealtaine
hAoine
ball
tree
ggg

Invalid:

codegolf
delta
alishanoi
ABI
anseo
breithlá

(Note that anseo and breithlá are Irish words, but they happen not to follow this rule. You should still output a falsy answer for them for the sake of simplicity.)

\$\endgroup\$
10
  • 1
    \$\begingroup\$ Jebus, I haven't heard "slender with slender and broad with broad" in a couple of decades, that gave me a flashback! You note that "anseo" ("here", for the benefit of the non-Gaeilgeoirí) doesn't follow the rule but you should probably specify the expected output for it - I'd suggest against special-casing it and having it be invalid. \$\endgroup\$ – Shaggy Jun 2 '19 at 19:51
  • 2
    \$\begingroup\$ This needs a much better definition of what is a broad consonant versus what is a slender consonant, unless I'm not understanding the challenge. \$\endgroup\$ – AdmBorkBork Jun 3 '19 at 12:56
  • \$\begingroup\$ @AdmBorkBork as I understood it, broad and slender consonants are indistinguishable in writing, the point is to detect consonants that would have to be both at the same time. \$\endgroup\$ – FrownyFrog Jun 13 '19 at 4:49
  • \$\begingroup\$ I'd suggest listing their uppercase variants \$\endgroup\$ – l4m2 Jun 25 '19 at 15:52
  • \$\begingroup\$ 'in leabhar, bh is surrounded by two broad consonants, so it is broad as well, and in cailín, l is surrounded by two slender consonants'. Did you mean 'vowels' instead of 'consonants' here? \$\endgroup\$ – Dingus Feb 8 at 5:06
  • \$\begingroup\$ Yes, that should have been 'vowels'. \$\endgroup\$ – bb94 Feb 8 at 19:14
  • 1
    \$\begingroup\$ I still have no idea what the types of consonants and vowels are. \$\endgroup\$ – user202729 Feb 9 at 2:12
  • 1
    \$\begingroup\$ This looks like a good challenge to me, to make it more understandable I would just explicitly list the sets of broad vowels, slender vowels, and consonants. (Rather than "here are all the characters: aábc..." have "here are all the broad vowels:aAáÁ...", "here are all the slender vowels:...", "here are all the consonants:...") \$\endgroup\$ – Leo Feb 10 at 5:42
  • \$\begingroup\$ Also, you should clarify what should happen if the word does not contain a sequence of consonants surrounded by vowels (e.g. "ball", "thx", "tree") \$\endgroup\$ – Leo Feb 10 at 5:44
  • \$\begingroup\$ "thx" is assumed to never be passed in as input. "ball" and "tree" would return true, because there's no contradiction between broad and slender vowels around consonants that can occur here. \$\endgroup\$ – bb94 Feb 12 at 6:09
2
\$\begingroup\$

Count strictly overlapping substrings

Posted

\$\endgroup\$
4
  • 1
    \$\begingroup\$ Is it correct that 1 is never a valid result? \$\endgroup\$ – Adám Jan 28 at 17:04
  • \$\begingroup\$ @Adám yes; do you think I should add that? \$\endgroup\$ – pxeger Jan 28 at 17:04
  • \$\begingroup\$ Probably a good idea. \$\endgroup\$ – Adám Jan 28 at 17:05
  • \$\begingroup\$ You need test cases with longer bs that can overlap themselves in multiple ways. \$\endgroup\$ – Adám Jan 28 at 17:27
2
\$\begingroup\$

Pad a jagged array to be square

Posted

\$\endgroup\$
11
  • \$\begingroup\$ Add a test case for pad value -1 or something like that. \$\endgroup\$ – user202729 Feb 12 at 14:55
  • \$\begingroup\$ Can any dimension of the input array be 0? [please review other sandbox posts] \$\endgroup\$ – user202729 Feb 12 at 14:56
  • \$\begingroup\$ Also add a test case with an array consisting of only fill values. \$\endgroup\$ – user202729 Feb 12 at 14:58
  • \$\begingroup\$ @user202729 what do you mean by "[please review other sandbox posts]"? I don't see the need for a test case with pad value -1, because the type of the elements in the array is answer-defined. I'll clarify the other two though \$\endgroup\$ – pxeger Feb 12 at 16:22
  • \$\begingroup\$ I suggest that you specify more clearly what input formats are allowed, that is, what counts as an "array". For example, is it acceptable to take lines of text with space as separator within each line? Or use two types of brackets, such as {[1, 5, 3], [4, 5], [1, 2, 2, 5]}? \$\endgroup\$ – Luis Mendo Feb 12 at 18:31
  • \$\begingroup\$ @LuisMendo input should be taken in your language's natural representation of nested arrays. If it doesn't have a builtin array representation, then take it in some kind of text representation like I mentioned in the rules section \$\endgroup\$ – pxeger Feb 12 at 18:49
  • \$\begingroup\$ The problem with saying "natural representation" is that a language may have more than one way of representing nested tuples. That said, I think what you have in the question is alright - perhaps to clarify what Luis is talking about you could add: "input can be any unambiguous representation of a jagged array"? I think what Luis may be getting at is that there could be a problem with e.g. a Python array contains meta-information (the length) while a C array wouldn't, but usually I think that is left out. \$\endgroup\$ – FryAmTheEggman Feb 12 at 19:26
  • \$\begingroup\$ To explain my point better: MATLAB (or MATL) can use curly braces for arbitrary arrays, and square brackets for rectangular arrays. So either {{1, 5, 3}, {4, 5}, {1, 2, 2, 5}} or {[1, 5, 3], [4, 5], [1, 2, 2, 5]} could be used as input. The latter is probably better to reduce code length. Can we just choose the most convenient one? What is the limit where choosing a convenient format counts as "pre-processing" the input and is not allowed? All this is language-dependent, but some general specification would be needed \$\endgroup\$ – Luis Mendo Feb 12 at 19:33
  • \$\begingroup\$ @pxeger Something that I tend to add to my sandbox review comments recently, hoping to reduce the problem of the sandbox posts not being reviewed enough. \$\endgroup\$ – user202729 Feb 13 at 2:37
  • 1
    \$\begingroup\$ @LuisMendo You can probably choose any convenient one (I think that's the common consensus?) \$\endgroup\$ – user202729 Feb 13 at 2:38
  • \$\begingroup\$ The "-1" thing is just to make people notice that the value to be padded is an input rather than hard coded by the code. \$\endgroup\$ – user202729 Feb 13 at 2:46
2
\$\begingroup\$

Snail word

Very similar to other challenges

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

Reconstruct an integer from its prime exponents

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

Draw four colorful quarter circles

The challenge is to reproduce this image in your favorite language:

enter image description here

  • Your image must be at least 400 by 400 pixels.
  • The fill colors don't need to be the same as in the image but they must be different from each other.
  • You must include the outlines but they can be any visible thickness you choose.
  • The quarters should be at the same orientation as in the image.
  • Your image must have four quarter circles aligned as in the image which each touch the edge of the circle at a point.
  • Your code must take input which specifies the location, in pixels, of the point where the quarter-circles meet; you can take this input in any reasonable format, but the units must be pixels (no relative units, such as a fraction of the width/height of the image). You can assume these inputs are always within the bounds of the outer circle. You can also assume that the inputs are such that all four quarter circles can be drawn within the circle.

Here is some LaTeX code as an example:

\documentclass[tikz,margin=3mm]{standalone}
\usetikzlibrary{calc,through}

\usetikzlibrary{intersections}


\begin{document}
\begin{tikzpicture}[inner sep=0pt, outer sep=0pt]

  \coordinate (point) at (-0.1,0.4);

  \draw [name path=mycirc] (0,0) circle [radius=1];
  \path [name path=di-1] (point) -- ++(-2,2);
  \path [name path=di-2] (point) -- ++(-2,-2);
  \path [name path=di-3] (point) -- ++(2,-2);
  \path [name path=di-4] (point) -- ++(2,2);
  
  \foreach \col [count=\i] in {yellow,red,blue,brown}{
  
      \fill [red, name intersections={of=mycirc and di-\i}] (intersection-1) circle [radius=0.05] node (inter-\i) {};
      
      \fill[\col,draw=black,rotate around={(\i+3)*90:(point)}] (point)
        let \p1 = ($(point) - (inter-\i)$) in 
        arc [start angle=0, end angle=90, radius={0.707*veclen(\x1,\y1)}]
        -- +(270:{0.707*veclen(\x1,\y1)}) -- cycle ; 
  }
  
  \fill[red] (point) circle [radius=0.05];
   
\end{tikzpicture}
\end{document} 

[I would love help on how to improve this challenge.]

\$\endgroup\$
7
  • 4
    \$\begingroup\$ Describing the exact ratios of the shapes would be helpful in drawing them \$\endgroup\$ – user Mar 5 at 15:34
  • 2
    \$\begingroup\$ Those are quarter-circles, not semicircles \$\endgroup\$ – pxeger Mar 5 at 15:46
  • \$\begingroup\$ Might be more interesting if the center of the shape (where the petals meet) was an input \$\endgroup\$ – Zaelin Goodman Mar 5 at 15:54
  • \$\begingroup\$ @pxeger ahem.. thanks :) \$\endgroup\$ – Anush Mar 5 at 15:57
  • \$\begingroup\$ @ZaelinGoodman Could you say exactly how that could be specified? \$\endgroup\$ – Anush Mar 5 at 15:59
  • 2
    \$\begingroup\$ @Anush Since the image is 300 x 300 pixels, you could say something like you must take input which specifies the location, in pixels, of the point where the quarter-circles meet; you can take this input in any reasonable format, but the units must be pixels (no relative units, such as a fraction of the width/height of the image). You can assume these inputs are always within the bounds of the outer circle. \$\endgroup\$ – Zaelin Goodman Mar 5 at 16:03
  • 1
    \$\begingroup\$ "Your image must be at least 400 by 400 pixels" what about vector graphics? If some one choice to output the image with vector graphics format. How to define its width and height? \$\endgroup\$ – tsh Mar 9 at 5:51
2
\$\begingroup\$

Gray code... Gray code?

Your Task

Your task is to print (in an easily readable and consistent format) the binary representations of the numbers 0-255 in some order such that only one bit is altered between two consecutive numbers.

Your Restrictions

Each successive byte of the source code after the first can only change one bit from the previous byte.

Other Information

Example valid code (in utf-8): q1!#c. Here, q (01110001) and 1 (00110001) are different in only one bit, and so on

Example invalid codes (in utf-8): Q1!, "!"

Example valid outputs (seperated by an empty line):

10101010 10101011 11101011 ... 01010101

[10, 11, 1011, 1111, 1110, ...]

10
0
1
11
111
...

Example invalid outputs (seperated by an empty line):

0000000100000011000000100000000000000100...

0
01
10
11
100
...

0 1 ... 100000000 110000000 ... 11111111

00 01 11 10 0100 0101 ...

0 1 3 2 5 6 ...

Notes:

  • A character can be stored as two bytes, but the bytes must differ by only one bit
  • If your interpreter ignores a character (like Whitespace ignores almost all characters) it cannot be used
\$\endgroup\$
10
  • \$\begingroup\$ Is printing 1 3 2 6 7 5 4 and onwards ok? \$\endgroup\$ – PkmnQ Feb 28 at 4:36
  • 1
    \$\begingroup\$ What does "some form of gray code" mean exactly? / Clarify that the restriction part applies to the source code of the program. \$\endgroup\$ – user202729 Feb 28 at 6:49
  • 1
    \$\begingroup\$ I'll change it to binary gray code to avoid confusion. \$\endgroup\$ – Hyperbole Feb 28 at 15:55
  • \$\begingroup\$ You should describe what the gray code is to avoid ambiguities. \$\endgroup\$ – FryAmTheEggman Feb 28 at 21:49
  • \$\begingroup\$ Do you think this challenge is too hard? \$\endgroup\$ – Hyperbole Mar 2 at 15:01
  • \$\begingroup\$ Is it okay if the output is printed in decimal instead of binary? \$\endgroup\$ – user202729 Mar 3 at 13:20
  • \$\begingroup\$ Perhaps add "addition of leading zeroes doesn't count as a change" and some examples to illustrate/example valid output (just for challenge accessibility, this is implied from the definition (and the Wikipedia page)) \$\endgroup\$ – user202729 Mar 3 at 13:21
  • 1
    \$\begingroup\$ Would be hard for practical languages, but for everything-are-valid languages it should not be a problem. Good challenge idea. \$\endgroup\$ – user202729 Mar 3 at 13:22
  • \$\begingroup\$ Does the last statement means "Your program should not work by removing any single bytes", or "Any subsequence of your program should not work."? \$\endgroup\$ – tsh Mar 16 at 11:43
  • \$\begingroup\$ @tsh neither. It means that you can't use a character if it is completely skipped over by the interpreter. For example, in the python code "if len('abc') < 4: print('Hello, World')" the "c" can still be used because it is not skipped over by the interpreter. \$\endgroup\$ – Hyperbole Mar 18 at 17:29
2
\$\begingroup\$

Subarrays With At Least N Distinct Integers

\$\endgroup\$
5
  • \$\begingroup\$ I don't get it. From 1,2,2,3 you can make 3 subsequences of 2 integers: 12; 22; 23. And the middle one is not made of different integers. So how it comes that "the number of contiguous subsequences that contain at least N distinct integers" is 5 in this case? \$\endgroup\$ – Sheik Yerbouti Mar 7 at 11:55
  • 2
    \$\begingroup\$ @Sheik 1,2, 1,2,2, 2,2,3, 2,3, 1,2,2,3 are the subsequences that contain at least 2 distinct integers. In my opinion, there should be a column in the table of test-cases that contains these sub-sequences for clarity. \$\endgroup\$ – Hyperbole Mar 7 at 17:40
  • \$\begingroup\$ @Hyperbole thank you very much. It wasn't that hard to get but, I don't know, English is not my language. Anyway if not on the test cases, they should be at least in an example before the tests. \$\endgroup\$ – Sheik Yerbouti Mar 7 at 18:24
  • 1
    \$\begingroup\$ @Hyperbole I appreciate the feedback. I updated the post with the example. \$\endgroup\$ – user101295 Mar 7 at 18:57
  • 1
    \$\begingroup\$ @SheikYerbouti I have updated the post with the example. \$\endgroup\$ – user101295 Mar 7 at 18:57
2
\$\begingroup\$

Tri tri tribonacci

Tribonacci from Wikipedia:

The tribonacci numbers are like the Fibonacci numbers, but instead of starting with two predetermined terms, the sequence starts with three predetermined terms and each term afterwards is the sum of the preceding three terms.

The challenge

Given three arrays of three integers, for each array:

  1. Find the generator G (the first non-negative integer) of the sequence to which the three numbers belong
  2. Then find the G-th element of the sequence (zero-indexed*)

The three integers found are indeed part of a tribonacci sequence, output the G-th element of that sequence.

*The sequences are zero-indexed because G may be 0 and in that case you have to find the 0th element of the sequence.

Example

Given the input

[[5, 11, 20], [1, 2, 3], [23, 39, 67]]

5 11 20 are part of the sequnce 2 4 5 11 20, which starts with 2, so we take the 2nd element of the sequence: 5

1 2 3 are part of 0 1 0 1 2 3, so we take 0

23 39 67 are part of the sequence 7 11 5 23 39 67 129 235 so we take 235

Now 5 0 235 are part of the sequence 230 5 0 235 so the output is the 230th element of that sequence:

174892031986606286607812889236621806383715371411020300455075910

Input / output

You can take the input as you prefer: an array of three arrays, three arrays, an object, a string, etc.

You are not required to handle integers larger than those implemented by your chosen language, I will post plenty of test cases with smaller output after I make a program for the challenge.

This is , everyone wins.

Meta

Please say something.

\$\endgroup\$
7
  • 2
    \$\begingroup\$ Are you sure you meant to put This is [tag:code-golf], everyone wins.? That's not code golf :p \$\endgroup\$ – Redwolf Programs Mar 8 at 23:55
  • \$\begingroup\$ Looks fine to me, except for the "zero-indexed" part. 0-indexing and 1-indexing are usually equally allowed. (Also, people might complain about "why not just make it two challenges, one for finding the generator and one for n-th tribonacci") \$\endgroup\$ – Bubbler Mar 9 at 0:00
  • \$\begingroup\$ @RedwolfPrograms we keep the truth in the sandbox, I will put "the shortest wins" in the challenge \$\endgroup\$ – Sheik Yerbouti Mar 9 at 0:00
  • \$\begingroup\$ @Bubbler the zero-indexing is because the sequence may start with 0, and in that case you have to find the 0th element of the sequence. About splitting the challenge, I didn't check but it's possible that one or both of the parts already exist. \$\endgroup\$ – Sheik Yerbouti Mar 9 at 0:03
  • 1
    \$\begingroup\$ @SheikYerbouti That makes sense. Then it would be better to include the justification of why it should be 0-indexed in the post. \$\endgroup\$ – Bubbler Mar 9 at 0:07
  • \$\begingroup\$ @Bubbler I added a note to justify the restriction, thank you for the feedback! \$\endgroup\$ – Sheik Yerbouti Mar 9 at 0:15
  • \$\begingroup\$ Maybe "This is code golf, so shortest code wins, but who's counting?" instead of "everyone wins"? \$\endgroup\$ – Beefster Mar 15 at 15:47
1
26 27
28
29 30
110

You must log in to answer this question.

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