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

2972 Answers 2972

1
49 50
51
52 53
100
1
\$\begingroup\$

Posted: Poker for Two

Posted on main here.

| |
\$\endgroup\$
  • \$\begingroup\$ or would it be better for my controller to follow poker etiquette by not revealing any card that isn't in a showdown?: When I've played poker (albeit digitally) the winner has the choice whether they show or hide their cards. That way, people can show if they were serious about their hand or hide the fact they bluffed. Allowing this system would also potentially add another interesting aspect to the challenge: do I reveal my "hand" or not. \$\endgroup\$ – Lyxal Aug 3 at 7:17
  • \$\begingroup\$ Also, I recommend you deal with replacement - that's how usual poker works: the deck is shuffled after each round. \$\endgroup\$ – Lyxal Aug 3 at 7:19
  • \$\begingroup\$ This game has no draws, so why shuffle after each round? That practically nullifies the effect of "no replacement" and has the bad effect of quantising the game to c possibilities for each bot's card. If you want each round's cards returned to the pack to be shuffled for the next round, you might as well deal floats in the range 0.0 to 1.0. (Or ints 0...c-1 with a very large c.) \$\endgroup\$ – Rosie F Aug 4 at 6:19
  • \$\begingroup\$ @Lyxal It seems to me that, if a player were allowed to reveal or not reveal their card, "not revealing" dominates "revealing", so nobody would choose to reveal, so I might as well just not reveal, and save everyone the bother of indicating their choice. Any objections? \$\endgroup\$ – Rosie F Aug 4 at 6:22
1
\$\begingroup\$

Posted: Combinatorial Decomposition

| |
\$\endgroup\$
  • \$\begingroup\$ s/provided/and/? \$\endgroup\$ – user202729 Aug 18 at 3:42
  • \$\begingroup\$ @user202729 I don't think so; I did add the word "both" though, to indicate that the conditions are linked to the uniqueness. \$\endgroup\$ – golf69 Aug 18 at 6:52
1
\$\begingroup\$

How Many Notches Are On Texas Red's Pistol?

The song, Big Iron, by Marty Robbins, is about an Arizona Ranger who rode into the town of Agua Fria to take the outlaw Texas Red alive (or maybe dead), armed with only the Big Iron (a .45 revolver) on his hip. Texas Red, despite being only 24 years old, is extremely dangerous, having already taken out 20 men who have tried to go after him. As a point of pride, he's carved out a notch on his pistol for each one. The song counts the notches on Texas Red's pistol as "one and nineteen more". After listening to the song a couple times, two questions crossed my mind:

  1. What about the other numbers that add up to twenty?
  2. What if the Ranger wasn't the 21st person to try?

The Challenge

Given a positive integer, N, the total notches on Texas Red's pistol, and another number A (also an positive integer), output a number B such that B + A = N. In the context of the song, it should read "A and B more".

The Catch

The song still has to be intact without sub-dividing any beats. That is, the number of syllables in the phrase "A and B more" must add up to 5. If it doesn't, output the string "oops". You may assume

  • 0 < A < N < 20
  • 1 < N

Examples

N   A   B (output)

20  1   19   ("One and nineteen more.")
19  2   oops ("Two and seventeen more" has 6 syllables)
11  7   4    ("Seven and four more.")

Syllable Counts

The numbers, from one to nineteen, have syllable counts as follows: one (1), two (1), three (1), four (1), five (1), six (1), seven (2), eight (1), nine (1), ten (1), eleven (3), twelve (1), thirteen (2), fourteen (2), fifteen (2), sixteen (2), seventeen (3), eighteen (2), and nineteen (2). No synonyms are accepted, such as "aught more" for "zero more".

Scoring

: Shortest code in bytes wins. Standard loopholes apply.


Meta Stuff:

I hope this is interesting enough. I thought just a normal subtraction problem would be too boring.

Is "oops" a good distinguishing output?

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

Show an integer, in digits of your choice

Input

A string representing digit characters, and a nonnegative integer.

How?

We shall show the integer in positional notation, where the string has the digit characters. Assuming the string is zero-indexed, the \$n\$th character shall represent \$n\$. The length of the string is the base.

For example, "0123456789" will show the integer in the standard decimal representation.

Rules

  • The string is assumed to have at least 2 characters.

  • Invalid inputs fall in don't care situation.

Examples

Beware of the zero!

Binary representation

Given "01" as the string:

$$ \begin{array}{c|c} 0 & “0” \\ 4 & “100” \\ 8 & “1000” \\ 15 & “1111” \\ 16 & “10000” \\ 23 & “10111” \\ 42 & “101010” \end{array} $$

Devanagari representation

Given "०१२३४५६७८९" (U+0966 – U+096F) as the string:

$$ \begin{array}{c|c} 0 & “०” \\ 4 & “४” \\ 8 & “८” \\ 15 & “१५” \\ 16 & “१६” \\ 23 & “२३” \\ 42 & “४२” \end{array} $$

Duodecimal representation

Given "0123456789↊↋" (The last two characters are U+218A and U+218B) as the string:

$$ \begin{array}{c|c} 0 & “0” \\ 4 & “4” \\ 8 & “8” \\ 15 & “13” \\ 16 & “14” \\ 23 & “1↋” \\ 42 & “36” \end{array} $$

Ungolfed solution

Haskell

showIntArb :: String -> Int -> ShowS
showIntArb "" _ = error "showIntArb: No given digit"
showIntArb (d:_) 0 = showChar d
showIntArb ds n = let
    appendDigit ints = if length ints <= n
        then appendDigit $ do
            d <- ds
            int <- ints
            return (d : int)
        else ints
    in showString (appendDigit (fmap return ds) !! n)
| |
\$\endgroup\$
  • \$\begingroup\$ so this is a base encoding question, with symbol replacement, right? \$\endgroup\$ – Razetime Sep 14 at 17:43
  • \$\begingroup\$ @Razetime Yes, exactly. \$\endgroup\$ – Dannyu NDos Sep 14 at 22:51
1
\$\begingroup\$

Haiku Quine

A haiku is a type of poetry originating from Japan following a simple pattern: 5 syllables on the first line, 7 syllables on the second, and 5 syllables on the third. Traditionally, haikus also include some reference to nature or seasons, but we'll ignore tradition for the sake of this challenge.

Your task is to create a quine which has some reasonable pronunciation in the form of a haiku.

For example, consider this loophole-abusing (and thus non-competing) Python quine:

0+0
with open(__file__) as fp:
    print(fp.read())

To be read as:

ze-ro plus ze-ro
with o-pen file as F P
print F P dot read

Rules and Scoring

This is , so the shortest code wins.

  • Standard rules and banned loopholes apply
  • Include a reasonable haiku pronunciation alongside your code (yes, this is inherently subjective and open-ended)

NOTE: may be better as a

| |
\$\endgroup\$
  • \$\begingroup\$ what's the standard for xxd output here? \$\endgroup\$ – Razetime Sep 15 at 3:34
1
\$\begingroup\$

Convert A String To Shorthand

Shorthand has been used for hundreds of years to compress and speed up the speed at which someone can write down what is said.
It does this using several abbreviating methods; three of which will be used here to compress a sentence.

Challenge

When given a sentence, alongside a set of 'briefs', 'prefixes' and 'suffixes' (defined below), print or return the sentence in its compressed form.

Definitions

  • Brief: A word that can be entirely substituted by another string of characters.
    I.E. Would: D, Be: B, Able: Ab. "I would be able...": "I D B Ab
  • Prefix: The beginning of a word that can be substituted by another string of characters; the prefix will either be joined or dis-joined.
    After(Joined): Af. Afternoon = Afnoon.
    Enter/Inter/Intra(Dis-joined): N. Internet = N-net
  • Suffix: The ending of a word that can be substituted by another string of characters; the suffix will either be joined or dis-joined.
    ful/ify(Joined): F. Clarify = Clarf
    ification(Dis-joined): F. Clarification = Clar-f

Input Structure

  1. The first input will be the sentence to be converted
  2. The second input is a collection of the briefs. Each brief is a collection itself, in which the first element represents the shortened form of that brief, while the rest of the elements are all strings that map to the brief. Example: [ [d, would], [m, much, more], [a, at, an] ]
  3. The third and fourth inputs are collections of prefixes and suffixes. The first element of each prefix/suffix is the shortened form, the second element is a flag (of your choosing) that represents whether it is joined or dis-joined. Everything else are the strings that match the prefix/suffix.
    Prefix: [ [af, true, after], [n, false, enter, inter, intra] ]
    Suffix: [ [f, true, ful, ify], [f, false, ification] ]

Sample Input:

"a shipment of letters was delivered to the postshop", [["of", "o"], ["t", "to"], ["was", "os"], ["the", "th"]], [["sh", false, "ship"], ["d", true, "de"], ["po", false, "post"]], [["rs", true, "ers"], ["m", true, "ment"], ["d", true, "ed"]]

Rules, Assumptions and Freedoms

  • You may assume all input is lowercase letters.
  • A brief will always take priority over prefixes and suffixes.
  • you can indicate a dis-joined suffix/prefix however you wish, as long as you mention how you are indicating it.
  • The input may be rearranged however you like, as long as you specify how your input is structured
  • Output may be returned, printed or the nearest equivalent.

Test Cases

"a shipment of letters was delivered to the postshop", [["of", "o"], ["t", "to"], ["was", "os"], ["the", "th"]], [["sh", false, "ship"], ["d", true, "de"], ["po", false, "post"]], [["rs", true, "ers"], ["m", true, "ment"], ["d", true, "ed"]]

a sh-m o lettrs os dliverd t th po-shop

"shorthand was once a common skill among woman", [["was", "os"]], [["sh", false, "ship", "short"], ["cm", true, "com"]], [["mn", true, "mon", "man"]]

sh-hand os once a cmmn skill among womn"

"the electrician will be able to fix it", [["th", "the"], ["l", "will"], ["b", "be"], ["ab", "able"], "t", "to", "it"]], [["el", false, "electr"]], [["sh", true, "cian", "sion"]]

th el-ish l b ab t fix t

| |
\$\endgroup\$
  • \$\begingroup\$ Looks like a nice challenge, I don't think there's much that needs to B clar-f-ed \$\endgroup\$ – Redwolf Programs Sep 7 at 14:12
1
\$\begingroup\$

Is it almost-prime?

Definition: A positive integer n is almost prime, if it can be written in the form n=p^k where p is a prime and k is also positive integers. In other words, the prime factorization of n contains only the same number.

Input: A positive integer 2<=n<=2^31-1

Output: a distinct truthy value, if n is almost-prime, and a distinct falsy value, if not.

Truthy Test Cases:

2
3
4
8
9
16
25
27
32
49
64
81
1331
2401
4913
6859
279841
531441
1173481
7890481
40353607
7528289

Falsy Test Cases

6
12
36
54
1938
5814
175560
9999999
17294403
| |
\$\endgroup\$
  • \$\begingroup\$ 36 has two distinct primes in the prime factorization 2×2×3×3. Is it really "almost prime"? \$\endgroup\$ – Bubbler Aug 25 at 23:19
  • \$\begingroup\$ Thanks, moved it to the falsy section. \$\endgroup\$ – infinitezero Aug 25 at 23:20
  • \$\begingroup\$ Then I think the a in n=a^k must be prime. Also you have a typo in the input range. \$\endgroup\$ – Bubbler Aug 25 at 23:33
  • \$\begingroup\$ Suggested tags: code-golf (it's not "codegolf"), decision-problem, primes. There's a discussion for decision problem output formats. Also, the $input in the title might be misleading to some people, making them assume the challenge is for a specific language. \$\endgroup\$ – Bubbler Aug 26 at 0:04
  • 1
    \$\begingroup\$ I would call this "Is it a prime power?", since that is the typical term. Also, I found related, related, and related but it doesn't seem to be a dupe. I think it will be an interesting challenge for languages without factoring builtins! \$\endgroup\$ – Sisyphus Aug 26 at 0:54
1
\$\begingroup\$

Keep the symmetry

SANDBOX: I am aware that the language in this challenge, as it stands, is quite... fluffy. If anyone could help me firm it up, I would be grateful. Also, would this be better as a cops-and-robbers style challenge, where the cops are trying to make the output more symmetrical, and the robbers make it less symmetrical?

Given a 2D array of 1s and 0s, flip a 1 to a 0 and output the resulting array.

The output array must be "closer to being symmetrical" than the input.

In the case where the array is already symmetrical, it must still flip a 1 to a 0, breaking as little symmetry as possible - e.g for

1,0,1
1,0,1
1,0,1

In the above case, changing the top-left 1 to a 0 will break symmetry in both directions, whereas changing the middle-left 1 will only break symmetry one way.

The output must be in the same form as the input (so that your program or function could take it in again).

What is symmetry?

I am talking about reflectional symmetry along both the horizontal and vertical axes.

Where the array has an even number of entries in a row/column, the axis is between the two central rows/columns:

1,0,|,0,1
1,0,|,0,1
-,-,-,-,-
1,0,|,0,1
1,0,|,0,1

otherwise it's down the middle of the middle row/column (and the numbers in that row/column count on both sides).

   |  
 1,0,1
-1,0,1-
 1,0,1
   |

Some Examples

Each pair of grids below is input .. output, which then becomes the next input, etc. iteratively:

1,0,0,1      1,0,0,1      1,0,0,1      1,0,0,1      1,0,0,0      0,0,0,0      0,0,0,0
0,0,1,0  ..  0,0,0,0  ..  0,0,0,0  ..  0,0,0,0  ..  0,0,0,0  ..  0,0,0,0  ..  0,0,0,0
1,0,0,1      1,0,0,1      0,0,0,1      0,0,0,0      0,0,0,0      0,0,0,0      0,0,0,0
1,1,1      1,0,1      1,0,1      1,0,1      1,0,1
1,1,1  ..  1,1,1  ..  1,0,1  ..  0,0,1  ..  0,0,0
1,0,1      1,0,1      1,0,1      1,0,1      1,0,1

| |
\$\endgroup\$
  • \$\begingroup\$ Is the program supposed to find the shortest path, or any path? Are we supposed to display each step? Should the choice of flipping a 1 to a 0 be random, or can it be calculated? A reference implementation would be very useful in this question. \$\endgroup\$ – Razetime Aug 26 at 13:03
  • \$\begingroup\$ The program is only supposed to flip one, calculated, bit from 1 to 0 and return the new grid. so iterative calls to the program would ultimately lead to all 0s. I guess I'm unclear exactly how I want the concept to be translated into a challenge, which is why I put the sandbox text at the top \$\endgroup\$ – simonalexander2005 Aug 26 at 13:38
  • \$\begingroup\$ The program must be trying to make the array symmetrical This needs to be defined precisely. What does it mean that the program "tries" to make it symmetrical? That repeated application of the program eventaully gives a symmetrical array? That it does it in a "small" (to be defined) number of steps? Same with as easy as possible: this needs to be defined precisely. I'm afraid I don't get the main idea of the challenge, actually \$\endgroup\$ – Luis Mendo Aug 26 at 17:21
1
\$\begingroup\$

Balanced Beams

Here are some examples of beams that balance:

X Y A   | X Y B Y
--+-----+---+---+
  |         |   |
X X   Y Y   Y X X
--+---- ----+-- +

A X X Y | A B Y Y
+---+---+-+-----+
|   |     |     |
B A | A AAB B   A
+ --+-- --+--   +

X Y X X | Y B   X
+-+-+---+---+----
| | |       |
Y A X Y Y X X X X
+ + + ------+----

The diagram will always be 17 characters wide and the top beam always balances in its centre. The other +s on the top beam indicate the point from which a lower beam hangs and the + on the lower beam indicates the point at which it balances. Your input does not need to include the |s if you don't need them. Lower beams with a width of 1 balance by default of course. The balancing of the top beam has to take the total weight of each lower beam into account.

As you can see, for each example, there are two positions marked A and B where I have forgotten whether they should be an X or a Y.

Please write a program a function which will accept the above diagram as input and output which of X and Y belong in each of the two positions A and B.

Your output should be something along the lines of A=X, B=X although any unambiguous output suffices e.g. you could output the diagram with the A and B substituted accordingly or you could modify the input in-place. You do not have to output values for X or Y, although for each diagram they always have a fixed ratio which will allow all beams to balance.

Other input formats could be acceptable but they need to get suggested as comments to the sandbox post.

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

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

Posted: Prime Power Switch

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

Sandbox Question

Do people think this is worth posting, given it only really requires a prime check along with getting digit prefixes? There are multiple implementations (possibly including hard-coding in some languages) to consider which might be enough. Please vote!


Produce all 83 base-ten right-truncatable primes in as few bytes as possible in the language of your choice.

  • Order is irrelevant, but the production must terminate.
  • You may produce a list, a set, or an equivalent object.
  • You may print them (e.g. space-separated, each on a line, or formatted as a list or set (e.g. {2; 3; 293; 5; ...})
  • You may give the numbers themselves as strings.
  • You may produce an iterator (but evaluating it must terminate).

Right truncatable primes

A right truncatable prime is a prime for which removing any number of trailing decimal digits is also prime.
For example, \$7193\$ is a right truncatable prime since \$719\$, \$71\$, and \$7\$ are all prime.

There are only 83 such numbers in base-ten, when sorted they are:

[2, 3, 5, 7, 23, 29, 31, 37, 53, 59, 71, 73, 79, 233, 239, 293, 311, 313, 317, 373, 379, 593, 599, 719, 733, 739, 797, 2333, 2339, 2393, 2399, 2939, 3119, 3137, 3733, 3739, 3793, 3797, 5939, 7193, 7331, 7333, 7393, 23333, 23339, 23399, 23993, 29399, 31193, 31379, 37337, 37339, 37397, 59393, 59399, 71933, 73331, 73939, 233993, 239933, 293999, 373379, 373393, 593933, 593993, 719333, 739391, 739393, 739397, 739399, 2339933, 2399333, 2939999, 3733799, 5939333, 7393913, 7393931, 7393933, 23399339, 29399999, 37337999, 59393339, 73939133]

This is A024770 in the Online Encyclopedia of Integer Sequences.


For some mathematician-written* Python see https://youtu.be/f2lEB4nMmyI.
* Fair warning, it might well make you cringe.

| |
\$\endgroup\$
  • \$\begingroup\$ I don't really mind prime challenges, just that most people who have been here a while have a stigma against it. Related. \$\endgroup\$ – Razetime Sep 5 at 14:26
  • \$\begingroup\$ The code in the link contains what appears to be a partially censored racial slur, so I think you should probably drop the youtube reference. \$\endgroup\$ – FryAmTheEggman Sep 9 at 21:32
  • \$\begingroup\$ Otherwise I think this is probably interesting enough, as these primes have several other non-prime features. It might be problematic if too many answers are just primality checks wrapped in terminating loops, though? \$\endgroup\$ – FryAmTheEggman Sep 9 at 21:35
  • \$\begingroup\$ @FryAmTheEggman Oh wow, I didn't notice; that's pretty sad. \$\endgroup\$ – Jonathan Allan Sep 9 at 22:15
1
\$\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
1
\$\begingroup\$

Move the Knight!

Your knight is on (0, 0) on an infinite (to all of the four edges, not just two) chessboard, and you need to move it to (a, b). You can use arbitrary (but finite) number of moves to do that. Since the chessboard is infinite, you can use squares with negative coordinates.

Since you only have 2 knights (if no promotion occured) to type the program, your program needs to be as short as possible.

Input

The input is two integers, a and b.

Output

You output a sequence of characters, each represents a move. There are eight directions to move, so your output should contain eight distinct characters, each represents one direction. They can be any eight characters, as long as they are all unique.

Test Cases

The characters used here is:

 A B
C   D
  N
E   F
 G H
0 0 -> ""
1 1 -> "GD" or "DEGD" or "DG" etc.
3 3 -> "DDDGGG" (one possible version)
2 3 -> "FGD"

Rules

  • Standard Loopholes are forbidden.
  • This is , so shortest code wins.
| |
\$\endgroup\$
  • \$\begingroup\$ @Razetime I did... "They can be any eight characters, as long as they are all unique." \$\endgroup\$ – null Sep 15 at 12:30
  • \$\begingroup\$ oh, sorry about that. \$\endgroup\$ – Razetime Sep 15 at 12:31
  • \$\begingroup\$ @Razetime I intend to make this challenge have many different, unique, interesting approach, and which one is shorter highly depends on the language. \$\endgroup\$ – null Sep 15 at 12:33
1
\$\begingroup\$

Do my data follow Benford's law or a uniform distibution?

Background

Benford's law, also known as the law of anomalous numbers, describes the distribution of the leading digit in many numerical data sets. Let \$X\$ be the leading digit of an observation (in base 10). According to Benford's law, \$P[X=i]=\log_{10}(1+\frac1i)\$ for \$i=1\ldots 9\$.

For instance take the yearly reputation change of the top 1000 users on CGCC. For a user with reputation change 3522, keep only the leading digit, 3. Repeat this for all users, and you get this distribution, which is far from uniform:

enter image description here

This has been shown to apply to vary different data sets, from town populations to stock prices, and is used to detect tax and election fraud.

On the other hand, for some other data sets, the distribution of the leading digit is a uniform distribution: \$P[X=i] = \frac19\$ for \$i=1\ldots 9\$.

Given some observed frequencies \$(f_i)_{i=1\ldots 9}\$, we shall measure the distance to these two distributions using the sum of the errors in absolute value: \$\sum_i \left|f_i-\log_{10}(1+\frac1i)\right|\$ and \$\sum_i\left|f_i-\frac19\right|\$, respectively.

Task

Take as input a list of non-zero numbers. For each number, keep only the leading digit, which is defined as the first non-zero digit. Compute the observed frequencies of leading digits, and output one of two values, depending on whether the observed frequencies are closer to Benford's law or to a uniform distribution.

Input

Input format is flexible. Note that input may include negative values, as well as non-integers.

Output

Either two consistent values, one for Benford's law and one for the uniform, or a truthy/falsey value.

Test cases

To be added

This is , so shortest answer in bytes wins.

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

Finding the densest crossword puzzles

I love crosswords, and nothing beats a super densely packed puzzle. But how dense can the puzzles get?

Here's a sample puzzle I made a few years ago:

enter image description here

Certainly not great, but can we do better?

Given any list of characters, a crosswordification of that list is a crossword puzzle consisting of characters from that list. For example, given the list ['b','a','d','a','d'], the following is a valid crosswordification:

enter image description here

but this isn't

enter image description here

Clearly, the order of the list is irrelevant.

Given a valid crossword, the area of the crossword is the area of the smallest rectangle containing the crossword. In the above examples, the smallest rectangle containing the crosswords are 3x3 squares, which have area 9.

Challenge

In this challenge, you must write a function which takes two arguments

  • A list-like structure containing english characters

  • A list-like of valid words consisting of english characters

and outputs an integer, representing the minimal area of a crosswordification of the list of english characters, where the second input defines the set of valid words.

I will be using this english dictionary for my test cases. Any code that is used to import/parse the dictionary into a list-like structure won't be counted in the byte-count, just the function.

Test Cases

More to be added:

['d','a','a','a','t','n','m'] -> 7 (adamant is a word)

['k','a','s','a'] -> 6
| |
\$\endgroup\$
  • \$\begingroup\$ Here's what I understand: Our programs need to calculate the smallest possible corssword from the given characters, display the size alone. correct? \$\endgroup\$ – Razetime Sep 17 at 5:04
  • \$\begingroup\$ @Razetime correct \$\endgroup\$ – Don Thousand Sep 17 at 13:51
  • \$\begingroup\$ Do you suspect there is any other way to do this apart from brute forcing all possible arrangements and picking the minimal area one that meets the requirements? \$\endgroup\$ – Sisyphus Sep 18 at 4:40
  • \$\begingroup\$ @Sisyphus yes, but not revealing, as thats part of the challenge \$\endgroup\$ – Don Thousand Sep 18 at 11:17
1
\$\begingroup\$

Posted.

| |
\$\endgroup\$
  • \$\begingroup\$ "one or more of the options for the longest palindromic run of digits in its binary representation can be removed" Does this mean I can remove several runs? For example, 945770 = 11100110111001101010_2 has 110011 as the longest palindromic run, it occurs twice and if I remove both occurrences, the result is 10101010. On the other hand, 944522 = 11100110100110001010_2 has 110011 and 001100 as longest palindromic runs, and removing both gives 10101010. \$\endgroup\$ – Zgarb Sep 12 at 10:25
  • \$\begingroup\$ Don't forget Dennis, Dennis 2.0 or Calvin numbers :P \$\endgroup\$ – caird coinheringaahing Sep 12 at 15:37
  • \$\begingroup\$ @Zgarb No; you should only remove a single run before splitting the remaining digits. I've clarified this in the challenge text. \$\endgroup\$ – sporeball Sep 13 at 0:50
1
\$\begingroup\$

Posted

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ I think the notation is fine, you could let people use any 4 distinct characters instead. You should mention that gravity is tward the center of the pattern. \$\endgroup\$ – Razetime Sep 18 at 2:33
  • 1
    \$\begingroup\$ left/right/up/down is more suitable for dominoes, I think. I don't know how walls and splits would change this, but go for it if you're fine with lesser answers. finding if a target domino falls is a different question altogether. \$\endgroup\$ – Razetime Sep 18 at 2:35
  • \$\begingroup\$ @Razetime There's no gravity, the example just happened to go towards the center. The direction relies solely on the pieces (I'll clarify that) \$\endgroup\$ – user 2 days ago
  • \$\begingroup\$ You mix a lot of terminology about the directions, i.e. using "north" and "below" in the same description. I think you would be better off editing the descriptions to all use the same convention. Separately, truthy and falsy aren't really good terms to use, since some languages don't have a concept of truth. I'd recommend saying something like "one consistent value for true and anything else for false or the reverse", or something similar. \$\endgroup\$ – FryAmTheEggman 2 days ago
  • 1
    \$\begingroup\$ Related, outputting the result after dominoes fall in 1D. \$\endgroup\$ – xnor 2 days ago
  • \$\begingroup\$ @FryAmTheEggman I started out with just north/south/east/west, and then changed it after Razetime's comment. I guess I left out some parts. I will change the falsy/truthy part too \$\endgroup\$ – user 2 days ago
0
\$\begingroup\$

Write a compiler/interpreter for ...

Inspired by the lisp challenge here.
It is a series of puzzles.

I don't like to see a simple eval solution, so:

  • interpreting the language is fine
  • translating the language to a different language is fine.

I think this is specific for each language.

Only the syntax and the basic commands.
Also specific.

Winning criteria should not be code golf.
The goal should be that you can "learn" an other language by looking at the code.

Languages that might be good candidates:

  • Lisp
  • APL
  • J
  • Brainfuck (already posted)
  • Whitespace
  • Forth
| |
\$\endgroup\$
  • 1
    \$\begingroup\$ This only works for languages which are small and well defined. BF fits those criteria. Whitespace does too. The others may not. Lisp and Forth have so many dialects that you would have to specify exactly which dialect to support; Lisp, Forth, APL and J might have too many built-ins to fit in an answer: there are character limits. \$\endgroup\$ – Peter Taylor May 12 '13 at 15:16
  • \$\begingroup\$ You don't have to provide all the built-ins, but that is why it is here. \$\endgroup\$ – Johannes Kuhn May 12 '13 at 15:38
  • \$\begingroup\$ What defines the "basic commands"? \$\endgroup\$ – ASCIIThenANSI Aug 31 '15 at 17:54
  • \$\begingroup\$ I don't know? Maybe that you can do the basic stuff with it like +,-,print,... \$\endgroup\$ – Johannes Kuhn Aug 31 '15 at 18:22
  • 1
    \$\begingroup\$ I suggest a programmer can implement the tiniest subset of those languages in order to be Turing-complete, as these are non-trivial subsets that can theoretically simulate the rest of the language... \$\endgroup\$ – user85052 Jun 28 '19 at 4:17
  • \$\begingroup\$ Which human is learning the programming language by looking at the code? \$\endgroup\$ – MilkyWay90 Aug 26 '19 at 3:23
0
\$\begingroup\$

Find Maximum number of 4+ letter words from Scabble Tiles

The challenge is to find the most words with 4 or more letters you can make with one set of scrabble tiles.

The tile distribution is as follows:

2 Blank Tiles
A 9  N 6    +====+===========+
B 2  O 8    | 01 | K J X Q Z |
C 2  P 2    | 02 | B C M P F |
D 4  Q 1    | 02 | H V W Y * |
E 12 R 6    | 03 | G         |
F 2  S 4    | 04 | L S U D   |
G 3  T 6    | 06 | N R T     |
H 2  U 4    | 08 | O         |
I 9  V 2    | 09 | A I       |
J 1  W 2    | 12 | E         |
K 1  X 1    +====+===========+
L 4  Y 2
M 2  Z 1

Valid words are any words that are 4+ that are available in this file, the official scrabble dictionary.

Tiles cannot be used twice. This means you can only have 1 word with a K, J, X, Q, and/or Z unless you use a blank tile to represent one of these letters.

I'm not sure how I'd do scoring on this. I want shorter code to score better, but I don't want a short piece of code that finds a lot less words to score better than a longer piece that finds many more words.

| |
\$\endgroup\$
  • \$\begingroup\$ Meh. I don't like dependency on external files; are we allowed to load it, or even embed it into the source code? \$\endgroup\$ – John Dvorak Dec 17 '13 at 20:00
  • \$\begingroup\$ as for finding more vs. shorter code, you could demand all words be found \$\endgroup\$ – John Dvorak Dec 17 '13 at 20:19
  • \$\begingroup\$ @JanDvorak Any way to use it. It's a text version of the official scrabble dictionary, it seemed to be the most fitting word list for the task. "All words being found" might be hard, considering there are probably many combinations of words that would deplete all the tiles. It's a maximum of 25 words, (25 words, 4 letters each, 100 tiles), but I don't know if it's possible to use all tiles with just 4 letter words. After so many words, you might not have enough tiles to make an actual word, which means you'd either have to go back or accept that you're not using all the tiles. \$\endgroup\$ – Rob Dec 17 '13 at 20:23
  • 5
    \$\begingroup\$ As currently described, this is a no-input task, which means that the answer can be precomputed and then the program only needs to decompress it. Consider rewriting it to take input (either of the word list or of the tiles available). \$\endgroup\$ – Peter Taylor Dec 18 '13 at 8:01
  • \$\begingroup\$ I suggest taking a list of tiles as input, loading the list of words from a predefined file and requiring all combinations / best combination to be found. Of course, if the input is the full list of tiles, the computation is going to take ages. I might allow preprocessing the word list outside the program itself (up to a certain point; a linearithmic growth?) \$\endgroup\$ – John Dvorak Dec 18 '13 at 8:32
  • 1
    \$\begingroup\$ I suggest modifying this so that input is a list of tiles, limited to a full rack or less (therefore 4-7 tiles, since our minimum word length is 4). Input should be assumed to be valid based on the standard set of tiles (e.g.: it wont' have something like 3 J's or 4 G's). This would have some practical use for a player in a scrabble game to figure out their next move (though it does not take into account tiles available to them which are already on the board). \$\endgroup\$ – Iszi Dec 18 '13 at 21:14
  • \$\begingroup\$ Alternative mode: Input is a list of tiles, maximum 96 (so that at least 4 are remaining in the set). Output only includes words (minimum 4 letters) which can be created without those tiles. This would be interesting as it provides words that may yet be created (though, again, not taking into account usable tiles on the board) at a given point in the game. \$\endgroup\$ – Iszi Dec 18 '13 at 21:15
  • \$\begingroup\$ Output needs to be decided as either a list of all possible words, or only the highest-scoring word(s). Another enhancement may be to require that the list be sorted descending in order of score (if output is all words), then ascending alphabetically. There's no reason to take each program's output into account for scoring. Since everyone is expected to use the same dictionary, all programs' outputs should be identical (except perhaps in sorting, if that's left out of the spec). So, this should be Code Golf. \$\endgroup\$ – Iszi Dec 18 '13 at 21:15
  • \$\begingroup\$ It's also worth noting that, as currently written, the task could just be to filter the given dictionary down to words which have 4 or more letters. By its very nature, the Scrabble dictionary should already exclude any words that cannot be made with a Scrabble set. \$\endgroup\$ – Iszi Dec 18 '13 at 21:18
  • \$\begingroup\$ @Iszi it's not "what are all the words you can make", it's "what are all the words you can make, where every letter used depletes a tile". There's a max of 25 words if you can use all 100 tiles. \$\endgroup\$ – Rob Dec 19 '13 at 16:40
  • \$\begingroup\$ I think I misunderstood the problem, then. I thought it was "all the words possible using a set of tiles" not "all the words possible, using only one set of tiles". Still, my point about code golf remains. There is an absolute maximum to the number of words (each with 4 or more letters) you can make with a single Scrabble set, and a finite number of permutations which can be used to hit that maximum. Every program written with this goal should end up with the same (or nominally similar) output. \$\endgroup\$ – Iszi Dec 19 '13 at 16:56
0
\$\begingroup\$

Test for Irreducible Complexity (Check for Redundant Characters)

I may need some additional help coming up with the full spec for this competition. As of right now, this is just a concept.

Many interesting questions, such as the "42" question in this sandbox, involve finding the longest program which is not reducible. This means that no set of characters can be removed and still allow the program to function as desired.

The basic idea is that your program will test a Base Program to make sure that it contains no redundant characters. The input will consist of:

  • Base Program (in the same language as your answer)
  • Expected Output

Your program will simply evaluate all possible subsequences of the Base Program and verify that none of them give the Expected Output.

This challenge actually has a utility value to several other challenges. For example, it verifies the results of a "longest non-reducible"-type challenge. In addition, it could make sure that a golfed solution cannot be golfed further.

I assume that the winning criteria will be fastest program, as cycling through all the possibilities takes a long time.

Problems

A sequence of length N has 2^N subsequences. Even if each evaluation is done very quickly, it might be unfeasible to test any program with more than 20 or so characters in a reasonable amount of time.

| |
\$\endgroup\$
  • \$\begingroup\$ Problem: some subsequences of legitimate answers may be pretty dangerous to the environment. You don't want to eval just everything. \$\endgroup\$ – John Dvorak Dec 23 '13 at 16:59
  • \$\begingroup\$ @JanDvorak Yes that actually is a serious problem. To what extent is it possible to fix that? \$\endgroup\$ – PhiNotPi Dec 23 '13 at 17:04
  • 1
    \$\begingroup\$ Forbidding any program with dangerous subsequences? :-) \$\endgroup\$ – John Dvorak Dec 23 '13 at 17:05
  • 1
    \$\begingroup\$ A more reasonable (but very difficult) solution would be the requirement to implement a sandbox. \$\endgroup\$ – John Dvorak Dec 23 '13 at 17:07
  • \$\begingroup\$ Even without dangerous behavior, the halting problem will be an issue: it's hard to tell whether a shortened program will terminate at all, especially for every conceivable input. \$\endgroup\$ – MvG Jan 7 '14 at 23:49
0
\$\begingroup\$

Popularity Contest: Implementation of a Hash Table

Create a class in some OOP language for a hash table that supports getting, setting, and removing values. You can't use the built in hash table/dictionary/map implementation. Highest votes in one week wins.

A key is any valid string. A value is any valid string, number, or boolean.

Example functionality:

hash.set("key","value");
hash.get("key"); // returns "value"
hash.set("key", 1234);
hash.get("key"); // returns 1234
hash.set("key2",hash.get("key"));
hash.get("key2"); // returns 1234
hash.delete("key");
hash.get("key"); // returns null/undefined/none/etc. or throws an error
hash.get("key2"); // still returns 1234

Definition of a hash table (from Wikipedia):

In computing, a hash table (also hash map) is a data structure used to implement an associative array, a structure that can map keys to values. A hash table uses a hash function to compute an index into an array of buckets or slots, from which the correct value can be found.

The hash table cannot be simply an array that is searched in linear time. It must be an actual hash table that uses a hash function to map the keys to the value.

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ Popularity contest and shortest don't mix. That aside, the spec is too vague. What is a "value"? What assumptions can be made about hashcodes? If the language makes all types nullable, should null be permitted as a key? What should the type be in languages which have co- and contravariance? And for that matter, what qualifies as a "hash table", bearing in mind that people will try to exploit any loophole? \$\endgroup\$ – Peter Taylor Jan 2 '14 at 23:16
  • \$\begingroup\$ @PeterTaylor Thank you for the feedback! Please see my edits, and let me know what you think. Could you meant about co/contravaraince? I looked at the wikipedia article about it but I'm not really sure how that has anything to do with this question. \$\endgroup\$ – hkk Jan 2 '14 at 23:37
  • \$\begingroup\$ I think it's still vulnerable to the loophole of "I have a hashtable with one bucket" (i.e. it's really a list of (key, value) pairs which I traverse in linear time). The thing about variance is to do with static typing of the elements of the map. E.g. in Java Map<String, Integer>'s get method has signature public Integer get(Object); in C#, a Dictionary<string, int>'s Get method has signature public int Get(string). The edited version makes it clear enough that the hashtable isn't expected to be genericised. \$\endgroup\$ – Peter Taylor Jan 3 '14 at 0:08
0
\$\begingroup\$

Wordlist detector

You are to write a program which, given a list of words, constructs a regular expression to match all these words but nothing else. Both your program and the constructed regular expressions are to be as short as possible.

Input and Output

Input comes on standard input and consists of one line giving n, the total number of words, followed by n lines with one word each. The number of words will be less than 1000, the length of each word less than 30. Words will consist only of lower case ASCII letters, i.e. a-z. You may choose to ignore the first line and use EOF instead to end the list.

Output shall be written to standard output. It consists of a single line, giving a POSIX extended regular expression to match these words and no others. Since input for this regex is not restricted to letters only, elements like . or [^…] won't make too much sense, which limits the language in a natural way. You may choose whether you want to terminate the line with a newline or not. Programs may choose to print multiple lines of output, in which case only the last one will be used for scoring. So you might print intermediate results and continue searching for improvements.

Test cases

Each submission may be accompanied by one regular expression. When scoring the submissions, I'll use this regular expression to reconstruct a word list from it. The code to do this reconstruction can be found at the end of this post. The reconstructed word list must fit the input specification above in terms of word count and length. It would be nice if your own program would be able to regenerate that regular expression from the word list, but that is not a strict requirement. But please don't paste bogus programs just to submit a challenging regular expression, though.

These test cases will be collected and fed to all programs for scoring.

Scoring

The final score of each program will be the program size plus the size of all its generated regular expressions for the inputs collected from submitted answers, including the example from this question. So short code which produces too long results might get beaten by longer code which generates shorter expressions.

Does this still qualify as ?

Submissions which generate an incorrect regular expression for one of the test cases will be disqualified, as will those which don't terminate in the allotted time. You can use the input reconstruction program below to check whether a produced regular expression does encode the correct word list.

Requirements

All submissions are welcome, but in order to include your submission in the tournament, it must be executable with reasonable effort on my Linux machine. It shouldn't depend on any exotic libraries, or any specialized ones which take too much work away from your own program. It must operate in reasonable time, say no more than five minutes per input. Your output must be reproducible, so if you use randomization at some point, please seed the randomizer, and please don't terminate an improove loop by a timer measuring execution time or some such.

Tournament times

I'll run the first major tournament two weeks after posting this question. I'll include a table of the results in this question. I'll try to run tournaments repeatedly as late submissions arrive, but I'll not promise any regular schedule.

Example

An very simple example application would be in Python 3 (53 chars):

print('|'.join(input() for i in range(int(input()))))

And here is a test case which could be posted along with the program, although this program obviously doesn't generate exactly this concise output:

bann?ana|ap(fel|ple)|s[ou]n|[hs](a|ou)nd

The expansion of that expression could be turned into the following example input, which need not be posted as part of an answer since it can be deduced from the regular expression:

10
banana
bannana
apfel
apple
son
sun
hand
hound
sand
sound

Regex expander program

And here is a program to turn regular expressions into word lists, again written in Python 3.

#!/bin/env python3
concat = set(('',))
altin = set(('',))
altout = set()
prev = None
stack = []
regex = iter(input())
for ch in regex:
    if ch == '(':
        stack.append((concat, altin, altout))
        altin = concat
        altout = set()
        prev = None
    elif ch == ')':
        concat.update(altout)
        prev, altin, altout = stack.pop()
    elif ch == '|':
        altout.update(concat)
        concat = altin
    elif ch == '[':
        ch = regex.__next__()
        cls = []
        while ch != ']':
            if ch == '-':
                crange = range(ord(cls[-1]), ord(regex.__next__()) + 1)
                cls.extend(map(chr, crange))
            else:
                cls.append(ch)
            ch = regex.__next__()
        prev = concat
        concat = set(w + c for w in prev for c in cls)
    elif ch == '?':
        concat.update(prev)
        prev = None
    elif ch >= 'a' and ch <= 'z':
        prev = concat
        concat = set(w + ch for w in prev)
    else:
        raise Exception("Illegal input")
if stack:
    raise Exception("Unclosed group")
concat.update(altout)
words = sorted(concat)
print(len(words))
print('\n'.join(words))

This is restricted to the part of regular expression syntax which I expect for this answer. If you have good reason to use something I did not consider, feel free to do so although I will likely have to update this code to cope with it. If you find a bug, please let me know.

| |
\$\endgroup\$
  • 1
    \$\begingroup\$ This is just Meta regex golf under the constraint that the two lists between them cover all possible words. Given that some people are tackling that existing question on that basis, this would qualify for closing as a duplicate. \$\endgroup\$ – Peter Taylor Jan 8 '14 at 8:45
0
\$\begingroup\$

Code-Golf: Write a number as an expression that's as short as possible

The goal of this code-golf is to create a program that takes a number as input (using STDIN, command line arguments, or prompting for input), and outputs that number, but written as an expression that's as short as possible. So, 10000 should become 10^4. If there is no way to write an expression that's shorter than the number, then output just the number.

Other rules

  1. No network access.
  2. You're not allowed to execute an external program.
  3. Only use the operators +, -, *, / and ^ (that's raising power, not XOR).
  4. Order of operations must be taken in account. Use parentheses if necessary.
  5. This is a code golf, so the code with the smallest amount of characters wins.
  6. The input will always be smaller than 2^32.

Test cases

500000000   -->    5*10^8     or    10^9/2
999999      -->    10^6-1
10          -->    10
4294967295  -->    2^32-1
16384       -->    2^14
| |
\$\endgroup\$
0
\$\begingroup\$

Rhymalator

(at the point, it's just something that came to me before i wake up, so it may need some adjusting, and i'd like some feedback as to if this could be fun)


The code challenge is to write a program that takes as input a calculation in Reverse Polish Notation and outputs the result. It must at least implement + - * /. It So far so easy, but to make it fun and "artistic", the following restriction applies:

  • The source code must rhyme when read. Example in PHP

    $iterator = str_split($a);
    foreach ($iterator as $key=>$value){
        if ($key > 3){
            ++$virtue;
        }
    }
    

    (the rhyme is on value-virtue)

  • Lines whitout readable characters count as whitespace (the two lines with } in the example)

| |
\$\endgroup\$
  • \$\begingroup\$ How does that example rhyme...? \$\endgroup\$ – Doorknob Jan 25 '14 at 12:54
  • \$\begingroup\$ @DoorknobofSnow well, i'm not really a poet, that's why i propose it as a challenge for others :p. if you have a better example i'll replace it \$\endgroup\$ – Einacio Jan 27 '14 at 15:58
0
\$\begingroup\$

Implement Kalah

The game of Kalah is a two-player board game in the Mancala family. Your implementation must:

  • Identify the active player ("Player 1" or "Player 2")
  • Display board state (in format specified below)
  • Accept input to allow that player to move (using index system below)
  • Announce a winner ("Player N wins")

Overview

Each player has a line of six spaces, called houses, and one additional space called a store. Each space holds seeds, which move from house to house in a counter-clockwise direction. The objective is to fill your store with seeds.

You must represent the board in the following two-row format with stores offset, where HH is a house and SS is a store:

SS HH HH HH HH HH HH
   HH HH HH HH HH HH SS

The top row represents the number of seeds in player #1's spaces, and the bottom row represents the seeds in player #2's spaces. The S in each row is the respective player's store (player #1's is top-left, #2's is bottom right). Single-digit values should include a leading space.

In this challenge, user-input will identify each house numerically. Use a left-to-right, indexed-from-one scheme for both sides:

S 1 2 3 4 5 6
  1 2 3 4 5 6 S

Note that the players' stores are not numbered, because seeds placed in the store never move out.

Rules

Wikipedia has a good summary of the game and its rules:

  1. At the beginning of the game, three seeds are placed in each house.

  2. Each player controls the six houses and their seeds on his/her side of the board. His/her score is the number of seeds in the store to his/her right. [Clarification: from our perspective, player 1's store is to the left, player 2's store is to the right.]

  3. Players take turns sowing their seeds. On a turn, the player removes all seeds from one of the houses under his/her control. Moving counter-clockwise, the player drops one seed in each house in turn, including the player's own store but not his/her opponent's.

  4. If the last sown seed lands in the player's store, the player gets an additional move. There is no limit on the number of moves a player can make in his/her turn.

  5. If the last sown seed lands in an empty house owned by the player, and the opposite house contains seeds, both the last seed and the opposite seeds are captured and placed into the player's store. [Clarification: moves that end on an opponent's empty house end normally without a capture.]

  6. When one player no longer has any seeds in any of his/her houses, the game ends. The other player moves all remaining seeds to his/her store, and the player with the most seeds in his/her store wins.

Example

(Parenthetical text should not appear in actual output.)

Player 1
 0  3  3  3  3  3  3
    3  3  3  3  3  3  0
> 2                      (prompt arrow and line break
                          are purely optional)
 Player 2
 1  1  0  3  3  3  3
    4  3  3  3  3  3  0
> 4

Player 2  (P2 gets a bonus turn from rule #4)
 1  0  3  3  3  3  3
    4  3  3  0  4  4  1
> 5

Player 1  
 1  0  3  3  3  4  4
    4  3  3  0  0  5  2
> 4

Player 1  (P1 captures P2's seeds in space 1)
 6  0  4  4  0  4  4
    0  3  3  0  0  5  2
...

Player 2
12  0  0 10  0  1  0
    0  0  0  0  0  1 13
 > 6

Player 1 wins            (because the non-finishing players gets
                          all remaining seeds on their side, it's 23-14)

Meta question: Would this be improved by removing some of the rules?

| |
\$\endgroup\$
  • \$\begingroup\$ Do the players run the game once and then take it in turns to take moves, with the process ending only when the game ends? Or do they run the program once per move? \$\endgroup\$ – Peter Taylor Jan 30 '14 at 10:06
0
\$\begingroup\$

[This is the first time I'm using the sandbox. I want to get feedback/suggestions before posting the question.]

Make a spider web (standard, orb type) that fills frame in the ratio of n:m, where n, m are input integers. You may use the example below as a model (but you don't need to use labels).

spider web

Your web should have multiple radii, at least 4 of which attach directly to the frame. The remaining radii should attach to the outer outline (perimeter) of the web. The web should have at least 15 radii. The mesh spacing should be more or less uniform spacing (although occasional weaving mistakes" or crossings are encouraged and will receive a bonus).

This is code-golf, so the shortest code (minus bonuses) wins.


Bonuses (to be removed from the number of characters in your code). Bonuses are awarded for the following features that reflect the architecture of an actual web (as opposed to a perfectly symmetric rendering). They are somewhat greater than usual as an incentive for attention to detail and realism.

-mesh spiral instead of concentric circles: 40 pts

-assymmetric web: 31 pts. (e.g. height of capture area greater than width)

-irregularly spaced radii: 42 pts

-distinct segments between radii (straight or crooked, but not the arc of a circle): 32 pts

-outer and inner outline clearly distinct from the spiral: 41 pts

-irregular outer outline: 20 pts

-2 or more easily observable reverses in spiral: 40

The accept will be awarded on Feb. 20, 2014.

| |
\$\endgroup\$
  • \$\begingroup\$ If there are bonuses then it isn't code-golf, by definition. It's not clear what output formats are acceptable. I'm not sure what you mean by "distinct segments between radii". "2 or more easily observable reverses" seems problematic: the ease of observing reverses is subjective, and might in addition depend on input and/or on the random numbers obtained. The weighting for the bonuses seems very arbitrary: is there any justification for it? \$\endgroup\$ – Peter Taylor Feb 3 '14 at 11:49
  • \$\begingroup\$ Re: bonuses, I should probably decide on the features I want included in the web, thereby eliminating bonuses altogether. Distinct segments means that there should be 2 straight mesh segments between radius n and radius n+2 (not sure whether this should be required in instructions to be updated.) Will give reverses more thought. \$\endgroup\$ – DavidC Feb 3 '14 at 12:02
0
\$\begingroup\$

Write a PHP Code Golfer

Since my currently daily programming is in PHP, I tend to try the challenges on the site using that language, but frequently I large program because of the verbosity of the language. And then I have to strip it for presentation...

But this is not a tips question, it's an eviscerating challenge.

The objective is to write a program in the language of your choice that takes a PHP file and outputs a golfed valid PHP file with the same functionality.

The scoring will be the average reduction in percent of the result of running the program with 3 selected files (not yet selected, I was thinking of some open source library)

The output file should run on at least 5.4 (so shorthand arrays, function dereference, traits are available)

Since the score is the difference between the ungolfed and golfed files, techniques beyond minifying are encouraged, such as using code subtitution, eval, compression, $$ (variable variables), dereferencing...


Scoring example: The 3 sources have 450, 1200 and 3500 chars respectively

Answer 1
results lenghts: 250, 1000, 3300
reduction: 200, 200, 200 (44%, 17%, 6%) average: 22%

Answer 2
results lenghts: 350, 1050, 3150
reduction: 100, 150, 350 (22%, 13%, 10%) average: 15%

In this case Answer 1 would win, even tough both answers got the same total reduction (-600 chars)

| |
\$\endgroup\$
  • \$\begingroup\$ It's a specialisation of codegolf.stackexchange.com/q/3652/194 , so would likely be closed as a duplicate. \$\endgroup\$ – Peter Taylor Feb 4 '14 at 22:44
  • \$\begingroup\$ @PeterTaylor I saw it. is similar, but I include an objetive goal and score. have any idea on how to make it more unique? \$\endgroup\$ – Einacio Feb 5 '14 at 2:43
  • \$\begingroup\$ "Making it shorter" is too broad, can I just delete some comments? If not, can I only shorten one variable and it's ok. It's not very interesting like this... \$\endgroup\$ – Fabinout Feb 5 '14 at 9:56
  • \$\begingroup\$ @Fabinout the objective is golfing the code. If you only remove some characters, I doubt you'll get a good score \$\endgroup\$ – Einacio Feb 5 '14 at 15:27
  • \$\begingroup\$ Alright, the criterion is the size of the output source code. good clarification. \$\endgroup\$ – Fabinout Feb 5 '14 at 15:55
  • \$\begingroup\$ Sum the bytes with the percents or separately? Also, no matter what sources you choose, make sure to paste the code into your questions; who knows when the code in the library will change? \$\endgroup\$ – Justin Feb 6 '14 at 19:11
  • \$\begingroup\$ i'll edit the bit about scoring (with examples) tomorrow (when i come back to work). I'll post the test sources as a pastebin, but I'll wait to choose them until the question is polished enough and someone consider it interesting enough \$\endgroup\$ – Einacio Feb 6 '14 at 19:34
  • \$\begingroup\$ Is there anyone more with questions? is still possible that it will be marked as a duplicate? or can i choose the sources and publish it? \$\endgroup\$ – Einacio Feb 13 '14 at 19:22
0
\$\begingroup\$

Create diagonal code

Your task is to create a program that outputs d=s*sqrt(2).

Specs:

  • Your program must be at least 4 lines long;

  • d=s*sqrt(2) cannot be hardcoded as is (so using ascii, compression, encoding, etc. is allowed and encouraged);

  • For each line of code n, pick up the nth character. The string obtained this way must be a valid program in a programming language of your choice, that must be different from the one you used for the main program. The obtained program must compile successfully, but it can throw errors, exceptions, etc.;

  • If at the nth line there is no nth character, you can consider that character as a whitespace or a newline. This cannot be done for the first 4 lines, which must be long at least n non-whitespace characters.

  • Your main program must end successfully (no errors, exceptions, etc.);

  • Internet access is forbidden;

  • Most upvoted answer in 2 weeks wins.

Happy coding!


I was unsure about making this a with several bonuses (polyglot answer, secondary program still valid, etc...).


Some bonuses for the code-challenge version:

Your valid answer starts with 0 points. You gain:

+10 if the secondary answer hides a third answer in it;
+15 for any other hidden answer;
+5 for every hidden answer that runs and ends successfully, without any problem;
+10 if your main answer is a polyglot;
+15 for every hidden answer that is a polyglot;


Which version would you prefer? Is there something you would change/improve in this question?

I personally like the one, but the KISS principle (Keep it simple, stupid!) reminds me that I may be wrong.

| |
\$\endgroup\$
  • \$\begingroup\$ It's trivial to make the diagonal program be just whitespace (many scripting languages will accept this as a program) or H (valid program in H9Q+). \$\endgroup\$ – Peter Taylor Feb 26 '14 at 9:26
  • \$\begingroup\$ Nowhere does it say that the diagonal program must output your magic string: it doesn't even have to execute correctly. Your amendment doesn't really fix things: I can now have the second line be #H, the third be #HH, etc. \$\endgroup\$ – Peter Taylor Feb 26 '14 at 9:37
  • \$\begingroup\$ You're right; Don't know why, on a second read I messed up the meaning of your comment. Anyway, I suppose this excludes code-challenge unless I/we don't find a way to avoid such trivial solutions. I guess popularity-contest would still be ok, since more interesting solutions could be found, right? \$\endgroup\$ – Vereos Feb 26 '14 at 9:41
  • \$\begingroup\$ I think my views on popularity-contest in general are well known. On further reflection, there are enough languages in which any string of bytes is a valid program that I don't think this question can work as is. If you want to save it, I think you need to look at doing something like a very difficult double-quine. \$\endgroup\$ – Peter Taylor Feb 26 '14 at 9:49
  • \$\begingroup\$ Thinking about quines and diagonals (which was the "spirit" of the question), what about a sort of mini-quine? The main program would have to display d=s*sqrt(2) only, and its diagonal must reproduce the code used to display the magic string (no comments allowed). It could be tagged code-golf or code-challenge. \$\endgroup\$ – Vereos Feb 26 '14 at 11:04
0
\$\begingroup\$

Create a Karnaugh-map calculator

Given an input of a truth table, generate a corresponding K-map.

Input:

Input will be of the form 10110001 where each bit is a row of a truth table. Count from the left to the right; so that input would be a table of:

i2i1i0 f
0 0 0|1
0 0 1|0
0 1 0|1
0 1 1|1
1 0 0|0
1 0 1|0
1 1 0|0
1 1 1|1

Max 4 variables will be inputted

K-maps (a small explanation):

K-maps are a way of simplifying boolean-algebra expressions.

Let's say we have 4 variables: a, b, c, d. Let the truth-table be 1110101001111111 (and the columns on the truth table be labeled, from left to right: a, b, c, d). Arrange the variables like so:

   cd
ab\   00 01 11 10
   00
   01
   11
   10

Note the grey-code counting scheme.

Fill in the table with the corresponding values from the truth table:

   cd
ab\   00 01 11 10
   00 1  1  0  1
   01 1  0  0  1
   11 0  1  1  1
   10 1  1  1  1

Group the values in rectangles whose dimensions are the largest possible powers of two. Note that this table signifies a torus, so wrap over the left and right edges.

enter image description here

The expression for the truth table is the ors of the and of the unchanging elements. For this, that would be:

Purple group: ¬b ∧ ¬c (for 0's, make them 1 by notting the value)
Green group: ¬a ∧ ¬d
Black group: a ∧ d
Blue group: b ∧ ¬d

Expression: (¬b ∧ ¬c) ∨ (¬a ∧ ¬d) ∨ (a ∧ d) ∨ (b ∧ ¬d)

Output:

  • Generate a 2D K-map (for more variables, add on either side) and show the grouping. K-map must be of the form I used. For less variables, remove rows or columns and change the list on the top left corner.
  • assume alphabetical ordering on the variables, that is, the first variable is a, second: b, third: c, and so on.
  • Also show the expression. Rather than use the unicode characters, the following is permissible:

    ~ instead of ¬
    * instead of ∧
    + instead of ∨
    


Edit: Possible duplicate: More fun with gates: Karnaugh simplification

| |
\$\endgroup\$
  • \$\begingroup\$ I think the grouping is not unique and therefore I might choose the most basic grouping (i.e. none). \$\endgroup\$ – Howard Feb 26 '14 at 9:02
  • 1
    \$\begingroup\$ Although @Howard's concern is partially answered by "rectangles whose dimensions are the largest possible powers of two", it's not obvious to me why you haven't also circled the entire row 10 and the bottom-right quadrant. \$\endgroup\$ – Peter Taylor Feb 26 '14 at 9:29
  • \$\begingroup\$ @PeterTaylor You're right - didn't read that line. But still my main concern is correct: it is not unique. Or as your remark shows it is not optimal if you choose all rectangles. \$\endgroup\$ – Howard Feb 26 '14 at 9:33
  • \$\begingroup\$ Also for higher number of variables you have to either go to n dimensional K-maps or you won't find all possible rectangles (they are no longer adjacent in the matrix). \$\endgroup\$ – Howard Feb 26 '14 at 9:38
  • \$\begingroup\$ @PeterTaylor In priority: Biggest rectangles, then least number. That is a big rectangle, but it is redundant with the others because every 1 in it is already circled. \$\endgroup\$ – Justin Feb 26 '14 at 16:44
  • \$\begingroup\$ @Howard Good point. I'll restrict it to 4 or less variables. \$\endgroup\$ – Justin Feb 26 '14 at 16:47
  • \$\begingroup\$ For the expression: rather than using A and V, why not * and +? That's fairly conventional use of field notation to represent GF(2). \$\endgroup\$ – Peter Taylor Feb 26 '14 at 17:11
  • \$\begingroup\$ Ahem. OR is, of course, not the same as + in GF(2). But * and + is still the conventional notation for operations over the Boolean semiring. \$\endgroup\$ – Peter Taylor Feb 28 '14 at 15:31
0
\$\begingroup\$

Title: Implement ROT-13... in ROT-13

Content:

Challenge: Implement ROT-13 in code that works as both itself and as the ROT-13 version of itself.

Scoring:

Your score is calculated as a percentage of used, ROT-13 eligible bytes in total of both versions of the program divided by total bytes (all characters) of both versions.

A used, ROT-13 eligible byte is any character that is not part of a comment or ignored by the compiler/interpreter. For example, any character in a brainfuck program that is not +-<>[],. is not considered a used byte, and any character in a C program including and after // or inside /* */ is not considered a used byte. All special symbols in APL are not considered used, as are all characters in a Whitespace program (sorry).

Example scoring:

C: 21/32 = 65.625%

main(){printf("Hello World!");}
| |
\$\endgroup\$
  • \$\begingroup\$ Originally this question was ROT-47, not ROT-13. The rules are chosen so that choice of language doesn't easily determine the winner; otherwise, whitespace would easily win. When I changed it to ROT-13 I made only [A-Za-z] count so that a language like golfscript or brainfuck would not automatically score 100%. Looking for thoughts on how to capture the idea without making it too "choice of language" dependent. \$\endgroup\$ – durron597 Mar 3 '14 at 21:13
  • \$\begingroup\$ Just saying, I have a C answer for the 47-version: qp.mniip.com/p/tz pick either of the lines \$\endgroup\$ – mniip Mar 3 '14 at 21:29
  • \$\begingroup\$ @mniip Okay I undeleted it :) \$\endgroup\$ – durron597 Mar 3 '14 at 21:48
1
49 50
51
52 53
100

You must log in to answer this question.

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