568
\$\begingroup\$

This "sandbox" is a place where Code Golf users can get feedback on prospective challenges they wish to post to main. 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.

Sandbox FAQ

Posting

To post to the sandbox, scroll to the bottom of this page 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, though you can optionally add a title at the top. 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.

Discussion

The purpose of the sandbox is to give and receive feedback on posts. If you want to, feel free to give feedback to any posts you see here. Important things to comment about can include:

  • Parts of the challenge you found unclear
  • Comments addressing specific points mentioned in the proposal
  • Problems that could make the challenge uninteresting or unfit for the site

You don't need any qualifications to review sandbox posts. The target audience of most of these challenges is code golfers like you, so anything you find unclear will probably be unclear to others.

If you think one of your posts requires more feedback, but it's been ignored, you can ask for feedback in The Nineteenth Byte. It's not only allowed, but highly recommended! Be patient and try not to nag people though, you might have to ask multiple times.

It is recommended to leave your posts in the sandbox for at least several days, and until it receives upvotes and any feedback has been addressed.

Other

Search the sandbox / Browse your pending proposals

The sandbox works best if you sort posts by active.

To add an inline tag to a proposal, use shortcut link syntax with a prefix: [tag:king-of-the-hill]. To search for posts with a certain tag, include the name in quotes: "king-of-the-hill".

\$\endgroup\$
0

4556 Answers 4556

1
25 26
27
28 29
152
3
\$\begingroup\$

Play a game of memory

\$\endgroup\$
3
  • \$\begingroup\$ Suggest test case "cbxcxvbaav", 8 \$\endgroup\$
    – math scat
    Sep 12 at 12:37
  • \$\begingroup\$ @mathscat Added, thank you. \$\endgroup\$
    – Philippos
    Sep 12 at 12:58
  • 1
    \$\begingroup\$ @bsoelch In Memory you pick the cards in order, so you can adjust the second card based on the first, so if you see the first has a match you can choose that match as the second card \$\endgroup\$ Sep 12 at 19:32
3
\$\begingroup\$

Numbers with distinct decimal digits

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

Implement Subleq

\$\endgroup\$
2
  • \$\begingroup\$ @bsoelch Fixed. \$\endgroup\$ Sep 19 at 17:40
  • \$\begingroup\$ @bsoelch That was a mistake on my part as well, I'll replace the example. \$\endgroup\$ Sep 20 at 18:38
3
\$\begingroup\$

Do you win a Numeric Mahjong?

\$\endgroup\$
5
  • \$\begingroup\$ why do we need the first rule? That would be like restricting languages made after posting this question \$\endgroup\$ Sep 19 at 12:41
  • \$\begingroup\$ @UndoneStudios Now that I think of it, fractional byte encodings seem fine. Variable length encodings (like Vyncode) are a problem, because they don't really define a mapping from a char in source to an integer. \$\endgroup\$
    – Bubbler
    Sep 19 at 23:36
  • \$\begingroup\$ This should be a question to raise in meta \$\endgroup\$ Sep 20 at 3:55
  • \$\begingroup\$ @UndoneStudios The rule is needed to define how to convert a source code to a list of integers. It totally isn't like "restricting languages made after posting this question". All languages can participate as long as they have a textual or byte representation (which practically all languages used on the site do). Only some encodings of some languages are not allowed. \$\endgroup\$
    – Bubbler
    Sep 20 at 4:19
  • \$\begingroup\$ Well, technically, I was only against variable encodings; that is cheaty \$\endgroup\$ Sep 20 at 4:21
3
\$\begingroup\$

I (rev)?(pal)? the source code, you (rev)?(pal)? the input!

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

Complete an equivalence relation

In set theory, a relation from a set \$A\$ to a set \$B\$ is a set of pairs of elements from \$A\$ and \$B\$. For example, \$\{(1, 5), (1, 6), (2, 4), (3, 5)\}\$ is a relation from the set \$\{1, 2, 3\}\$ to the set \$\{4, 5, 6\}\$.

A relation \$R\$ from a set \$A\$ to itself is an equivalence relation iff:

  • It is reflexive: For all elements of \$A\$, \$(a, a)\$ is in \$R\$.
  • It is symmetric: If a pair \$(a, b)\$ is in \$R\$, then so is \$(b, a)\$.
  • It is transitive: If the pairs \$(a, b)\$ and \$(b, c)\$ are in \$R\$, then so is \$(a, c)\$.

For example, \$\{(1, 1), (1, 2), (2, 1), (2, 2), (3, 3)\}\$ is an equivalence relation on the set \$\{1, 2, 3\}\$.

Your challenge is to, given a relation from a set to itself, add as few pairs of elements as possible to transform it into an equivalence relation.

Worked example

If we start with the relation \$\{(1, 2), (3, 2), (4, 4)\}\$, then:

Firstly, the relation must be reflexive, so all pairs of elements \$(a, a)\$ must be added, resulting in \$\{(1, 2), (3, 2), (4, 4), (1, 1), (2, 2), (3, 3)\}\$.

Next, the relation must be symmetric, so we need to add the inverses of \$(1, 2)\$ and \$(3, 2)\$, resulting in \$\{(1, 2), (3, 2), (4, 4), (1, 1), (2, 2), (3, 3), (2, 1), (2, 3)\}\$.

Finally, the relation must be transitive. Since \$(1, 2)\$ and \$(2, 3)\$ are in the relation, so must be \$(1, 3)\$, and likewise \$(3, 1)\$ must also be in the relation. Adding these results in \$\{(1, 2), (3, 2), (4, 4), (1, 1), (2, 2), (3, 3), (2, 1), (2, 3), (1, 3), (3, 1)\}\$, and this is an equivalence relation.

Input/output is can be lists of pairs of positive integers, or an adjacency matrix. You can optionally take the domain of the relation (i.e. all unique values in it). The order in which you output the pairs does not matter, and you can assume the input will be nonempty.

Testcases

{(1, 1)} -> {(1, 1)}
{(1, 2)} -> {(1, 2), (1, 1), (2, 2), (2, 1)}
{(1, 2), (3, 4)} -> {(1, 2), (1, 1), (2, 2), (2, 1), (3, 4), (3, 3), (4, 4), (4, 3)}
{(1, 2), (1, 3)} -> {(1, 2), (1, 3), (1, 1), (2, 2), (3, 3), (2, 1), (3, 1), (2, 3), (3, 2)}
{(1, 1), (2, 2), (3, 3)} -> {(1, 1), (2, 2), (3, 3)}
{(1, 1), (2, 2), (3, 4)} -> {(1, 1), (2, 2), (3, 3), (3, 4), (4, 3)}
{(1, 2), (3, 2), (4, 1)} -> {(1, 1), (2, 2), (3, 3), (4, 4), (1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)}
{(8, 19), (4, 12), (9, 31), (4, 18)} -> {(8, 8), (8, 19), (19, 8), (19, 19), (4, 4), (4, 12), (4, 18), (12, 4), (12, 12), (12, 18), (18, 4), (18, 12), (18, 18), (9, 9), (9, 31), (31, 9), (31, 31)}
{(8, 7), (2, 7), (14, 3), (3, 16)} -> {(2, 2), (2, 7), (2, 8), (7, 2), (7, 7), (7, 8), (8, 2), (8, 7), (8, 8), (3, 3), (3, 14), (3, 16), (14, 3), (14, 14), (14, 16), (16, 3), (16, 14), (16, 16)}
{(1, 1), (1, 2)} -> {(1, 1), (1, 2), (2, 1), (2, 2)}
\$\endgroup\$
8
  • \$\begingroup\$ Could output be loosened to not require outputting pairs already in the input? Although for some reason I feel iffy about going in between, i.e. allowing the output to contain some input pairs without requiring it to contain all of them... \$\endgroup\$ Sep 27 at 8:47
  • 1
    \$\begingroup\$ @UnrelatedString What exactly are you thinking of when you say that? I can't think of any reasonable approach which would necessitate that. Besides, the point of the challenge is to create the minimal superset that's an equivalence relation. \$\endgroup\$
    – emanresu A
    Sep 27 at 20:17
  • \$\begingroup\$ I was mostly inspired by the phrase "add as few pairs of elements as possible"--thinking about the interplay between symmetry and transitivity, it seems unlikely any solution would actually benefit from only outputting the added pairs, which makes me kinda curious about leaving the option open. \$\endgroup\$ Sep 28 at 3:24
  • \$\begingroup\$ Do you have to deduce the set or can you take it as input? Can you use adjacency matrices? Can you output the equivalence classes? \$\endgroup\$ Sep 28 at 9:13
  • \$\begingroup\$ Possible dupe \$\endgroup\$ Sep 28 at 9:18
  • \$\begingroup\$ @CommandMaster I'll allow taking the domain as input, and I/O as adjacency matrices. I'm not going to allow outputting the equivalence classes because I can think of several approaches that wouldn't even compute them and I want things to stay semiconsistent. I don't think this is a dupe for two reasons: one, that challenge requires outputting the number of sets to add which a lot of answers take advantage of; two, while transitivity is the hard part of this challenge, incorporating reflexivity and symmetry into an answer from there is still nontrivial. \$\endgroup\$
    – emanresu A
    Sep 29 at 1:27
  • \$\begingroup\$ are delimiters required? or can i take {(1, 2), (3, 4)} as 1 2 3 4 and output 1 2 1 1 2 2 2 1 3 4 3 3 4 4 4 3? \$\endgroup\$ Sep 29 at 2:25
  • 1
    \$\begingroup\$ @thejonymyster Since it's a list of pairs, sure, that's fine. I believe taking a flattened list is in the I/O defaults anyway \$\endgroup\$
    – emanresu A
    Sep 29 at 2:26
3
\$\begingroup\$

The multiples are missing

\$\endgroup\$
0
3
\$\begingroup\$

? ? ?

Golfy Fairy Chess Notation + Validation

Step 1:

Design an encoding for fairy chess piece movement which encodes all of the following information:

  • Where a piece can move (INCLUDING arbitrary length movement)*
  • Whether those movements are "jumping" or not
  • Whether those movements are "capturing" or not**

You don't need to handle non-moving, royalty, special case movement (such as first move double-movement), or any other special stuff like that.

Step 2:

Write a program which, when given (A):

  • a chess position***
  • a starting square
  • an ending square

all in any reasonable format of your choice, as well as (B):

  • a description of a fairy chess piece's movement capabilities in the notation you designed in step 1

will output whether the movement on the board (A) is valid for that fairy chess piece (B)

Additional spec clarification

You may assume

  • All pieces other than the piece being moved are pawns
  • The fairy chess piece is the piece that will be moved
  • The fairy chess piece movement will be defined such that it could theoretically make a move, given the right board arrangement (i.e. no 'non-movers')
  • Movement will be entirely within the board
  • Board will be square and at least 2x2 in size
  • Piece will not attempt to capture its own teammates
  • Piece will not attempt to move to its own square, and you don't need to worry about whether the notation implies it should/shouldn't be able to.

You may not assume an 8x8 board.

Scoring:****

\$(\text{bytes in program})\times(\text{average bytes to represent each piece in (list of fairy chess pieces which will be provided)})\$

Lowest score wins

Optional challenge: try and make the format human legible! :-)

META:

*I will be sure to clarify in the question body how exactly this works; but basically i want to be able to include things like rook/bishop/queen/knightrider without having to assume a maximum movement distance

**I'll also be clear that pieces can only capture at the end of their move, so no multicapture or capture and then move / en passant nonsense :P

***I don't know how to explain, but this doesnt have to include which pieces are what. just where the pieces are and whether each piece is on your team or not, or something similarly simple

****Ideally, score would be based on both short notation as well as a short decoding program, but I'm not sure the exact balance yet. feel free to tell me this is a bad idea / throw your algo of choice at me, but i'll be studying other compression challenges as well

\$\endgroup\$
2
  • \$\begingroup\$ Heads up: It looks like the bullet-point formatting in the first list under step 2 is wrong (missing newlines?). \$\endgroup\$ Oct 6 at 14:53
  • \$\begingroup\$ @SuperStormer great catch, that wouldve taken forever for me to notice lol thank you \$\endgroup\$ Oct 6 at 15:32
3
\$\begingroup\$

Find the k-th largest number

Given the string representation of three sorted lists, get the k-th largest number.

The string representation has such form:

1 3 5 7 11 120 9988
23 68 99 111
107 131 888

aka. lists are separated by newline \n and numbers in one list are separated by space.

Length of each list, length of the string and k are directly given, but access to the string costs. You can fetch from a given position. Least fetches wins.

Your solution should handle all possible inputs well, but only optimize score for average cases.

This is an example solution. It solves the problem with an awful score, but you can also use lib here. Write the lib if it's absent in your language.


Sorted lists in test cases will be generated in this way:

  • Generate 1 million (1'000'000) integers uniformly in \$\left[0, 2^{31}-1\right]\$. Duplicates will likely appear.
  • Sort them.

[Not decided yet] It's fine if your code is only optimized for three 1M length arrays and fallback to worst solution for other input.

\$\endgroup\$
2
  • \$\begingroup\$ You should clarify what "average case" means. From what distribution are the inputs taken? Additionally, can there be duplicates in the lists? \$\endgroup\$ Oct 11 at 3:35
  • \$\begingroup\$ @CommandMaster Added \$\endgroup\$
    – l4m2
    Oct 11 at 8:35
3
\$\begingroup\$

Make Code Printing X without X

The challenge is simple: write a program which takes in some string \$n\$ consisting of only uppercase and lowercase letters, and outputs the code for a program (in the same language) which takes in no input and outputs \$n\$. However, the code your program generates must not have any of the characters of \$n\$. For example, if your program was in Python, if the input was "Lit", your output could not be print("Lit"), because that contains L, i, and t. One valid output would be, for example, x=lambda:'\114\151\164'.

Some notes:

  • Uppercase and lowercase characters are treated as distinct -- e.g. if the input string contains A, your generated code can still contain the character a.
  • Your generated code follows the same restrictions as a standard code golf answer -- e.g. it can be code which defines an anonymous function returning the string, but it cannot work by saving the string into a variable.
  • Your submission is scored by the length of the generating code, not the generated code. In addition, there are no restrictions on the source of the generating program, only the generated.

Standard loopholes are forbidden. As this is , shortest program wins.

Questions

I don't know what to call this challenge.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ code-generation \$\endgroup\$
    – noodle man
    Oct 15 at 3:37
  • 1
    \$\begingroup\$ Because of the possibility that input contains all letters, all answers would likely never output letters \$\endgroup\$
    – l4m2
    Oct 16 at 0:32
  • \$\begingroup\$ @l4m2 Hm.... I somehow didn't think of that; that means this challenge isn't possible in many languages. I could add a limit on the number of distinct characters which can occur in the input, but that feels inelegant. Other thoughts? \$\endgroup\$ Oct 16 at 21:59
3
\$\begingroup\$

Is it a valid crossword grid?

In crossword terminology, the grid is the region into which the crossword answers are inserted, consisting of white and black squares. The crossword answers, called entries, are inserted into contiguous sequences of white squares in a row or column, separated by black squares.

For British (and Commonwealth) crosswords, the grids usually follow a specific set of rules:

  • They should have 180 degree rotational symmetry (if there is a black square in the xth row and yth column, there should be a black square in the xth-to-last row and y th-to-last column).
  • No entries may be exactly two squares long.
  • All white squares must be joined in a single region.
  • No row/column can be completely filled with black squares.
  • Each two-by-two square must contain at least one white square.
  • Each two-by-three rectangle must contain at least one black square.

For n=3 there is only one valid grid (I'm using . for white squares and # for black squares):

...
.#.
...

For n=4 there are no valid grids, although British crosswords usually use odd n anyway.

Here are some examples of valid grids for n=5:

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

Here are two examples of valid grids for n=6:

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

Input may be in the form of an array of any two byte-sized values and output can be any two distinct values of your choice or any of your language's truthy or falsy values respectively.

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

\$\endgroup\$
1
  • \$\begingroup\$ .................... :) \$\endgroup\$ Oct 16 at 21:57
3
\$\begingroup\$

Befunge Comment Outline Creator

\$\endgroup\$
6
  • \$\begingroup\$ Is it equivalent to a 0-1 matrix with an even sum in each row/column? Additionally, I'm assuming an all-space answer is invalid, but I don't see any rule disallowing it. Could you add one? \$\endgroup\$ Oct 20 at 6:26
  • \$\begingroup\$ @CommandMaster Almost, however having no semicolons at all would result in the IP reading in the comment as code. I could probably clarify that. \$\endgroup\$ Oct 20 at 6:36
  • \$\begingroup\$ Can I take as input w+2, h+2 instead of w, h? \$\endgroup\$ Oct 21 at 6:35
  • \$\begingroup\$ @CommandMaster Is it too expensive to add 2 to the inputs? \$\endgroup\$ Oct 21 at 7:04
  • \$\begingroup\$ I haven't tried, and w, h might be shorter, but it might be easier to use the size of the output instead of the size of the comment itself \$\endgroup\$ Oct 21 at 7:06
  • \$\begingroup\$ @CommandMaster Hm, I may consider it, it doesn't seem like it would be unfair \$\endgroup\$ Oct 21 at 7:10
3
\$\begingroup\$

Minecraft XP Orb Amounts

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

Intersections in a Circular Scrambled Word

Given a word W and a scrambled version of it S as input, you are required to return the number of intersections S will have when organized in a circular arrangement.

Example

Let W be VICTORY and S be VICYTRO. After transforming the scrambled word in its circular form and forming the original word by adding segments between the characters, we have the following diagram:

enter image description here

As we can see, for this particular example, the expected output is 2 interceptions.

Specs

  • Input will consist only of [A-Z] characters.
  • It is irrelevant how you set up the circular word (clockwise, counterclockwise, if the characters are evenly spaced from one another or not), just be consistent.
  • Input is flexible, read it however you see fit for you.
  • Standard loopholes are not allowed.

Test Cases

Format: 
W , S  --> output

VICTORY, VICYTRO --> 2
# To be added more 

This is , so shortest answers in bytes wins!

Meta

Is the challenge interesting? Is there anything unclear? I am not a native English speaker, so I welcome any corrections on the wording of the challenge.

I will later add more test cases. Also, what is the general consensus here where there are multiple correct answers? Because when I add words with repeated letters, depending on the "path" you choose when forming the circular word, it will affect the number of intersections. (I'll update the specs section as well when I introduce these special cases).

Lastly, I didn't give much thought on my second point in the specs section, maybe it's wrong... I'll observe more cases later.

Pretty much any feedback is appreciated!

\$\endgroup\$
3
  • 2
    \$\begingroup\$ Could take input as a permutation of 1..n, to get rid of worrying about repeated letter ambiguity as well as some potential for a "chameleon challenge" (i.e. determining the permutation between the two words could be highly nontrivial in some languages and overshadow the actual "core" of intersections between circle chords). If you do want solutions to have to handle repeats, then I'd recommend just allowing them to give any of the possible outputs. \$\endgroup\$ Oct 29 at 19:52
  • 1
    \$\begingroup\$ re. multiple possible outputs: challenges often specify that submissions may choose to either output all possible outputs or just one of them. \$\endgroup\$
    – noodle man
    Oct 29 at 20:10
  • \$\begingroup\$ I suggest to write W and S instead of W and S to avoid confusion, because those are just names, no data. \$\endgroup\$
    – Philippos
    Oct 31 at 12:44
3
\$\begingroup\$

Seat gangs as far as possible

\$\endgroup\$
2
  • \$\begingroup\$ @noodleman No, the gangs can be any (non-zero) size -- \$k\$ is the number of gangs. \$\endgroup\$ Oct 31 at 17:45
  • 1
    \$\begingroup\$ Suggest test case 1,2,1,2,1 -> 1,1,1,2,2 \$\endgroup\$
    – noodle man
    Oct 31 at 17:46
3
\$\begingroup\$

Calculate a struct size

In C and C++, the size of a structure depends not only on the sizes of its members but also their alignment requirements.

This problem will assume a simple case in which each structure is made up of primitive types that have a size that is a power of two and an alignment that equals their size.

Given a list of the types in a structure, please output the resulting size of the structure.

Here is an example structure:

struct {
  char c[5];
  int i, j;
  short s[3];
}

Input in any of the following formats is acceptable:

  • A list of the sizes of the individual types that make up the structure; for the above that would be [1, 1, 1, 1, 1, 4, 4, 2, 2]
  • A list giving the lengths of each array and the sizes of its elements, which for the above would be [[5, 1], [1, 4], [1, 4], [3, 2]]
  • A list giving the size and alignment of each variable, which for the above would be [[5, 1], [4, 4], [4, 4], [6, 2]]

(The third format indirectly supports nested structures but this can be emulated for the other formats by replacing them with an array of the same size and alignment.)

The size of the above structure is 24. Here is how it is calculated:

  1. Each of the 5 chars consumes 1 byte each, making 5.
  2. Each int requires an alignment of 4, so there are three bytes of padding before the first of them. The total size is now 16.
  3. Each of the 3 shorts consume 2 bytes each. The total size is now 22.
  4. The entire structure has an alignment of the largest alignment of any member, which in this case is 4, so the size must be rounded up to the next multiple of 4, which is 24.

Visually:

c[0] c[1] c[2] c[3]
c[4] ..............
i__________________
j__________________
s[0]_____ s[1]_____
s[2]_____ .........

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

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

Golf Transmission

As in, the 5 speed transmission from the original VW Golf GTI.

Print the transmission pattern in as few bytes as possible.

1  3  5
|  |  | 
|--|--|
|  |  |
2  4  R

\$\endgroup\$
1
  • 1
    \$\begingroup\$ this pun was too good to pass up \$\endgroup\$ Nov 16 at 14:50
3
\$\begingroup\$

Derive an MIU string

The MU puzzle in Douglas Hofstadter's Gödel, Escher, Bach involves a simple formal system called "MIU". It works as follows:

  • MI is an MIU-string
  • If xI is an MIU-string, then so is xIU.
  • If Mx is an MIU-string, then so is Mxx.
  • If xIIIy is an MIU-string, then so is xUy.
  • If xUUy is an MIU-string, then so is xy.

Your task, given an MIU-string, is to output a derivation of that string starting with MI and ending with the input string.

You can assume that the input is in fact a valid MIU-string and not something illegal like MCMLXVIII or (spoiler) MU.

Instead of taking input as strings of MIU, you can choose to take input as arbitrary precision integers using the digits 3 for M, 1 for I and 0 for U. In that case your output would start with 31, which represents MI.

Example:

MI
MII
MIIII
MUI
MUIU
MUIUUIU
MUIIU

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

\$\endgroup\$
4
  • \$\begingroup\$ Related. Personally a bit surprised there doesn't seem to be a dupe. \$\endgroup\$ Nov 23 at 6:03
  • \$\begingroup\$ @FryAmTheEggman Unless there's way to solve possibility using some other properties, they'd be too similar \$\endgroup\$
    – l4m2
    Nov 30 at 7:25
  • \$\begingroup\$ @l4m2 Personally, I think the guarantee of reachability makes them sufficiently different. It is possible that brute force is still the golfiest solution, but even then, not having to handle the fail case seems like a significant factor. I could certainly be wrong, though. \$\endgroup\$ 2 days ago
  • \$\begingroup\$ @FryAmTheEggman Don't a trivial upperbound exist? \$\endgroup\$
    – l4m2
    2 days ago
3
\$\begingroup\$

Classify a Coxeter group

In this challenge you will take as input a Coxeter matrix representing a Coxeter group. Your program will then classify it as one of the following:

  • Spherical
  • Euclidean
  • Compact
  • Paracompact
  • Hypercompact

Your program should output one of 5 distinct values depending on which category the input falls into.

This is . The goal is to minimize the size of your source code as measured in bytes.

Sandbox

I had this idea, but haven't had enough time to write up a specification. I'll explain what each of these are, and give the enumerations of each class.

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

Just another traffic jam!

\$\endgroup\$
2
  • 1
    \$\begingroup\$ Can you specify the zip-lock system? \$\endgroup\$
    – Seggan
    Nov 27 at 19:53
  • \$\begingroup\$ @Seggan I added that, thank you. I somehow thought this would be internationally known. \$\endgroup\$
    – Philippos
    Nov 28 at 6:49
2
\$\begingroup\$

Huffman Decoding

Write a programm which takes two strings as input and prints a text.


The first argument is a Huffman Tree, serialized in the following format:

  • every ascii character except ~ is always a leaf, if ~ is the first characater it is also a leaf.
  • <tree0><tree1>~ is a tree where <tree0> is the left subtree and <tree1> is the right subtree.

Example: ab~cde~~~ generates this tree:

 ┌─┴─┐
┌┴┐ ┌┴─┐
a b c ┌┴┐
      d e

where a would have the key 00, b 01, c 10, d 110 and e the key 111.


The second argument is a text that has been compressed with with the Huffman code that is defined by the first parameter. This bit-string can contain any bit sequence (also null-bytes and non-printable characters) and is not byte aligned, therefore it has been encoded with a variation of the standard Base64 encoding:

  • the characters used for the encoding are the standard base64 characters: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/
  • the bitstring is broken up into 6-bit chunks and mapped to this characters
  • if the last chunk is smaller than 6 bits, a character with this prefix is used, and padding characters are added to the string:
  • - : the last chunk was five bits long
  • = : the last chunk was four bits long
  • =- : the last chunk was three bits long
  • == : the last chunk was two bits long
  • ==- : the last chunk was one bit long

Example:

bits:       1 1 1 1 0 1 1 0 1 0 0 1 1 1 0 1 0 1 0 0 0 1 1 0 1
chunks:    |1 1 1 1 0 1|1 0 1 0 0 1|1 1 0 1 0 1|0 0 0 1 1 0|1[0 0 0 0 0]|
characters:       9           p           1           G           g
base64:     9p1Gg==-

Your programm has to decode the text encoded in the second parameter and print it to stdout.

You have to provide your source code encoded in the way described above. The length of your encoded source code + the length of your serialized huffman tree will be the winning criterion.

TODO: example input

\$\endgroup\$
2
  • \$\begingroup\$ It would be helpful to explicitly state the 64 characters used in the encoding. I presume they're A-Za-z0-9+/ but (especially if you're expecting people to implement that part explicitly) it's best to make the problem self-contained. \$\endgroup\$ Oct 8, 2012 at 16:23
  • \$\begingroup\$ Hello! This looks like a good but abandoned meta post, would you be willing to offer it for adoption? (If you want to, you can still post to main.) \$\endgroup\$
    – user58826
    Jun 9, 2017 at 15:30
2
\$\begingroup\$

Polygon prefixes

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

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

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

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

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

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

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

As with all code golf, shortest code wins.


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

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

Code golfing problem: Surface classification

The task: Given a surface-word reply with the classification of what surface it is.

Example 1: Input: aba'b' ----> Output: 1T

Example 2: Input: aabcb'c' ----> Output: 3P

Bounds on the problem: Since there are only 26 letters, there will never be more than that many labels. Additionally output should be in the form S,nT,mP for n,m positive integers.

Background: In the study of algebraic topology students are often presented with diagrams such as the one below. The represent instructions for how to assemble a surface. The assembly is prescribed as: if there are two edges labeled with the letter x then glue them together so that the arrows point the same direction. To make our job easy, topologists have discovered an algorithmic way to classify surfaces using 'words' assembled from these 'plane gluing-diagrams'.

enter image description here Choosing a corner arbitrarily (top right) and orientation (ccw) we read off the labels on the edges where an inverse appears wherever the arrow points against the orientation. In this case the 'word' that represents this plane model is given as abab.

A surface word is a string that contains the letters a,b,...,@ up to some letter @ and each letter is contained in it exactly twice. In the two occurrences of each letter: 0, 1, or 2 of them may be postfixed by a ' which I am considering using to represent 'inverse' (opposite orientation).

If in a surface word all letters appear twice: once without the ' and once with it (f.ex. ba'b'a) then we say that the surface the word represents is orientable. If a surface is orientable then it is necessarily the direct sum of n Tori for some non-negative integer n. If this condition doesn't hold (like in aab'b) then the surface represented is non-orientable: in this case it is the direct sum of m Projective Planes for some positive integer m.

Once you have found out if the reduced word is orientable or not, the final answer is given as follows. If orientable and number of unique letters in the reduced word is 1 then output should be S. Otherwise if the number of unique letters in an orientable word is n (it will be even) then the output should be sT where s = n/2. If the word is non-orientable then the output should be mP where m is the number of distinct letters in the reduced word.

The goal is to take as input some surface word, reduce it via reduction rules 1-6 and then classify it as a sphere, some number of connected tori, or some number of connected projective planes. Here are the 6 reduction rules where ~ represents 'reduces to':

Let M,A,B,C,D be surface words, x be a single letter, and juxtaposition represents concatenation:

  1. Cycle Rule: If M = AB then M ~ BA
  2. Flip Rule: M ~ M'
  3. Sphere Rule: Axx'B ~ AB
  4. Block Rule: ABC ~ ADC if B is a surface word and B ~ D by 1 or 2
  5. Cylinder Rule: If M = AxBCx'D, then M ~ AxCBx'D
  6. Möbius Rule: If M = AxBxC then M ~ AxxB'C ~ AB'xxC

I am looking for input on:

  • should this be code-golf or programming-challenge?
  • how would scoring work?
  • ???

If I feel satisfied with the question in a few days I'll post it to the site.

\$\endgroup\$
5
  • \$\begingroup\$ If, for each input, there is only one correct output, then it should probably be code-golf. The scoring criteria would then be source code length. \$\endgroup\$
    – PhiNotPi
    Jun 8, 2013 at 14:33
  • \$\begingroup\$ Yes, this is the case. In general however there is not a unique series of applications of the reduction rules for any given instance. \$\endgroup\$
    – Kaya
    Jun 8, 2013 at 16:21
  • \$\begingroup\$ I don't think the order of explanation is correct. You should explain reduction before talking about "the reduced word". And "reduce it via reduction rules" doesn't entirely make sense, because the rules are presented as equivalences rather than reductions, and most of them don't have a "natural" direction. \$\endgroup\$ Jun 10, 2013 at 8:49
  • \$\begingroup\$ It's also occurred to me that you haven't defined the notation M'. Does it just consist of toggling the orientation of each token, or does it also reverse the entire string? And do you have test cases which between them force implementation of all of the reduction rules? \$\endgroup\$ Jun 11, 2013 at 8:32
  • \$\begingroup\$ Good call on the string inverse, yes you have the right idea and I will make it clear. I have a lot of test cases from when I did a number of these computations by hand in a university course and (anecdotal experience) I am pretty sure that it is possible to force the use of all the reduction rules (except maybe 4 which is really just a meta-rule for convenience when doing proofs). Additionally you have alerted me to some concerns regarding the form of the proper output: it's definitely underspecified. I'll put some work into this today. \$\endgroup\$
    – Kaya
    Jun 11, 2013 at 14:04
2
\$\begingroup\$

Fastest Code: checking if interval pairs overlap

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

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

Example input 1:
interval x , interval y

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

Output:
Can be in any true false format.

false (They overlap)

reasoning:

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

Example input 2:

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

Output:

true (they do not overlap)

reasoning:

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

Scoring:

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

Business Card Ray Tracer

I have no idea how to create a good code golf question!

See this description of a ray tracer with source code that fits on a business card. The author stopped when the code size was 1337 bytes.

http://fabiensanglard.net/rayTracing_back_of_business_card/index.php

Achieving identical output, optimise for minimum code size. Execution time is not relevant.

\$\endgroup\$
6
  • 1
    \$\begingroup\$ I think what you have here is a straight ahead golf. All languages. You need only define the requirements. Do you want identical output or do you want "good output encompassing <list of features>"? \$\endgroup\$ Oct 6, 2013 at 17:22
  • 1
    \$\begingroup\$ For a minimum feature list I'd suggest something like (1) it is ray tracer (2) supports point-like lights and shadow + ambient light (3) supports mirrored (implies reflection) and matte surfaces (3) all objects are sphere and overlaps are allowed. With no requirement for (a) anti-aliasing; (2) finite sized light sources; (c) atmosphere effect or (d) depth of field; or (e) tiling and gradients. Notice however, that the example supports at least (b), (d) and (e). \$\endgroup\$ Oct 6, 2013 at 17:29
  • 1
    \$\begingroup\$ BTW--The one you linked can get a little bit more with #define Q return (R was already taken for the rand wrapper) and #define O operator. \$\endgroup\$ Oct 6, 2013 at 17:33
  • 3
    \$\begingroup\$ I suggest reading the Teapot question in the sandbox Mk IV and the comments - it's not the same question, but some of the same issues are relevant, and it might give you ideas for improvements to the spec. \$\endgroup\$ Oct 6, 2013 at 22:48
  • \$\begingroup\$ Yes. Read the teapot question for guidance. Ultimately I decided that one was too big, but we did get into some pertinent details. \$\endgroup\$ Dec 1, 2013 at 9:48
  • \$\begingroup\$ This sandbox post has had little activity in a while and little positive reception from the community. Please improve / edit it or delete it to help us clean up the sandbox. \$\endgroup\$
    – user58826
    Jun 9, 2017 at 15:32
2
\$\begingroup\$

Countdown: Federal Holidays in the United States

Inspired by this question:

Christmas Countdown

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

The following holidays must be tracked, and announced:

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

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

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

days
hours
minutes
seconds
milliseconds
until
time

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

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

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

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

Answers must include:

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

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


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

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

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

Golf a random Human Genome fragment with non-random features

A totally random genome fragment is easy enough: just spit out the letters ATCG in random order, and you're done. So let's try something a little less random and more useful to science.

Your program will:

  • Accept an argument from the user for number of base pairs (20bp-10000bp must be supported, more if you wish)

  • Accept an argument from the user for GC content. This indicates how frequently the generated sequence should contain the G and C bases as a percentage of total sequence length.

  • Include at least one complete gene in every request of 500bp or more, where a gene is defined as an otherwise random sequence that begins with a start codon triplet (ATG) and ends with the first stop codon triplet it encounters (TAG, TGA, or TAA). The distance between the start codon and the stop codon does not have to be a multiple of 3.

  • Vary gene content (the portion of the fragment that is "gene", inclusive of the gene's start and stop codons) linearly with respect to GC content (when sequence >= 500bp). At the extremes, when GC content is 0%, gene content is 10%; when GC content is 100%, gene content is 60%.

  • Output a single-strand sequence that complies with the above specs and the user's given parameters. (i.e. a single row of letters will suffice since it is trivial to deduce the complementary strand of the DNA given the sequence of one strand)

  • Calculate the actual GC content %, actual number of genes, and actual gene content % in the resulting fragment, and output a status line below the sequence conforming to the example format below. Percentages may be rounded to one decimal place. Actual values may deviate by +/- 3% from the expected outcome based on user's input.

    GC content: 42.1% | Genes: 3 | Gene content: 32.1%

Your program will not:

  • Use any Internet, library, or built-in gene sequence generation functions or databases. Roll your own.

Sufficient randomness:

  • For the purposes of this challenge, any built-in random/pseudo-random number generator function, GUID generator, well-seeded cryptographic hash function, etc. is considered an acceptable source of randomness.

What-ifs:

  • What if another start codon occurs before the stop codon? E.g. ATGXXXATGXXXXXXXXXXXXTAG. This is acceptable, but the "gene" length in this case is calculated from the most proximal start codon to the stop codon.
  • What if another stop codon occurs after a stop codon? E.g. ATGXXXXXXXXXXXXXTAGXXXXXXTAG This is also acceptable, but likewise the "gene" length is calculated from the start to the most proximal stop.
  • What if both of these things happen? E.g. ATGXXXATGXXXXXXXXXXXXTAGXXXTGA. Here again, the "most proximal" principle applies and the gene content is demarcated by the innermost start and the innermost stop.
  • Do "orphaned" start and stop codons that do not demarcate a gene count as gene content? No.

This challenge is code golf, so shortest valid code wins.

Post example output from a 500-bp request with GC content between 35% and 65%, and have fun!

\$\endgroup\$
19
  • \$\begingroup\$ "Use hardcoded fragments for anything other than the start and stop codons." - why not? Specifying criteria for what counts as enough randomness should make these useless in any case. Speaking of which, you need to specify criteria for what counts as enough randomness. \$\endgroup\$ Feb 28, 2014 at 5:54
  • \$\begingroup\$ The only partial output example given flagrantly violates the spec. If the GC content is 42.1%, the gene content should be 31.05%, not 22.0%. The definition of "gene" is also imprecise: in the sequence AUGCCAUGCCUAGCUAA, which is the gene? \$\endgroup\$ Feb 28, 2014 at 12:02
  • \$\begingroup\$ @PeterTaylor AUG starts the gene, then come the CCA, UGC, CUA and GCU triplets, none of which terminate the gene. Now if there were three C's instead of two, then UAA would be the terminating triplet and the whole sequence would form a gene. I agree the definition is imprecise, though. \$\endgroup\$ Feb 28, 2014 at 12:11
  • \$\begingroup\$ @JanDvorak, (part of) the point of that example is that there are two AUG substrings. \$\endgroup\$ Feb 28, 2014 at 12:30
  • \$\begingroup\$ Good points. I was hoping to avoid having too much text, but that came at the expense of less clarity than the challenge demands. Edit forthcoming. \$\endgroup\$ Feb 28, 2014 at 13:58
  • \$\begingroup\$ Also, I've muddied the waters with RNA encoding and DNA encoding, (U vs T), which we can chalk up to a late night. \$\endgroup\$ Feb 28, 2014 at 14:00
  • \$\begingroup\$ Revised accordingly, although I remain open to suggestions on how best to frame the standards for acceptable randomness. I want something that won't be exploited by answers making no effort at randomness, but that doesn't have the pain-in-the-butt factor of generating 10mb+ of data and running a Diehard test battery. \$\endgroup\$ Feb 28, 2014 at 17:20
  • \$\begingroup\$ " This is acceptable, but the "gene" length in this case is calculated from the most proximal start codon to the stop codon. " - wait, what? In nature, the first one is the start codon, and the rest encode methionine. Under your scheme, methionine (which is an essential amino-acid) would be impossible to include into proteins. Your scheme would also be much harder to splice. Also, what happens to AUG substrings that are not triplet-aligned to previous AUG substrings? \$\endgroup\$ Mar 1, 2014 at 9:25
  • \$\begingroup\$ In nature, the first ATG encodes the start of a protein coding region and defines a reading frame (triplet boundary), the rest encode methionine and the first triplet aligned stop codon encodes the end of the protein coding region (and no amino-acid). \$\endgroup\$ Mar 1, 2014 at 9:29
  • \$\begingroup\$ As for the randomness, I'm not worried about the source of randomness (whatever native library is available is assumed to be good enough) but rather how the source of randomness is used (can we just start the sequence with a start codon and insert an end codon at just the right spot if it doesn't occur naturally sooner, then fill in with more random codons while avoiding ATG subsequences? Your "sufficient randomness" places constraints on the RNG (useless) but no constraints on how it's used (or that it needs to be used at all) \$\endgroup\$ Mar 1, 2014 at 9:34
  • \$\begingroup\$ My true random number sequence generator was sitting there watching silently as I typed away the sequence ACACACACACACAC.... It's all okay. The TRNG was capable of producing something better - it just didn't really get to it. \$\endgroup\$ Mar 1, 2014 at 9:38
  • 1
    \$\begingroup\$ In fact, the 3% tolerance for the CG content leaves no room for randomness when there are only 20 base pairs. I can shuffle the pairs and turn some A<->T or C<->G, but that's it. In fact, if the CG content is set to zero, the task is impossible: we want a gene content of 2 base pairs (which is itself impossible), but the start codon contains a G, and a single G in a 2bp sequence means a 5% CG content, 2% than is the limit. Not including a gene means that we are 7% under the gene content lower limit. Similarly, it's not possible to start or stop a gene with nothing but Cs and Gs. \$\endgroup\$ Mar 1, 2014 at 9:45
  • \$\begingroup\$ Yeah, the 20bp starting point is a bad idea. The problem with start codons is that I considered introducing the idea of promoters and decided that would make the whole thing too complex. So in the absence of promoters there has to be some way to determine which Met is the start codon vs an amino acid and the easiest simplification is to have no Mets in the gene. Likewise, for "not triplet aligned", I'm trying to avoid having to go into explanations of frameshift mutations (even though a Frameshift% would be a cool parameter). \$\endgroup\$ Mar 1, 2014 at 14:29
  • 1
    \$\begingroup\$ I am starting to think that all of these complexities should be included (this proposal stems from me noticing that most of the extant random DNA generators are pretty weak) and this should just be a popularity contest instead of a golf. Link a couple of good articles on the structure of the genetic code and let people add as many features as they wish. Making it a golf seems to be a catch-22 between too many compromises or a too-impenetrable wall of rules and conditions that will dissuade participation. \$\endgroup\$ Mar 1, 2014 at 14:33
  • \$\begingroup\$ Perhaps a code-challenge where people earn x points for each complexity implemented? \$\endgroup\$
    – user10766
    Mar 2, 2014 at 5:52
2
\$\begingroup\$

DIM, the DIM Integer Machine

The DIM Integer Machine is an engine for producing integer sequences.

It has one major problem: To put it mildly, it's kind of...dim.

After producing a single number, it immediately forgets what sequence it was working on. The only thing it remembers is the last number it produced and the current direction of the search, either ascending or descending. (And of course, it remembers the methodology for finding numbers according to the commands it understands).

Consequently, the user is free to change their mind after each number by issuing a new command.

Suppose the DIM has just produced an integer square: 81

  • User inputs P and submits the input.
  • DIM understands that P is requesting the next prime number after 81
  • DIM computes and returns 83.
  • DIM forgets what it was doing.
  • User inputs O.
  • DIM understands that O is requesting the next odious number and returns 84.
  • DIM forgets what it was doing.

The DIM functions only for numbers between 1 and 1,000,000. If the DIM reaches either extreme while performing a search it will reverse direction and continue searching.

(For example: If searching in ascending order for a prime when the last number was 999,999, it will encounter 1,000,000 which is not a prime, then switch to descending order and continue searching for the "next" prime by moving downward - 999,999...999,998, etc.)

The DIM remembers the last number as 1 when it is first activated for a searching session.

This is the full list of commands that the DIM understands:

  • P - Next prime number
  • S - Next square number
  • F - Next Fibonacci number
  • O - Next odious number
  • W - Next wasteful number
  • U - Next undulating number
  • K - Next katadrome
  • R - Reverse direction immediately; the next command will proceed in the new direction

Because the DIM is so...dim, it absolutely DOES NOT precompute lookup tables of numbers in these sequences. It is far too forgetful for that to work. The DIM also has no Internet connection, so it is unable to consult the Online Encyclopedia of Integer Sequences or other such sites. It also has a sense of pride, so it does not make use of built-in Fibonacci functions or NextPrime / PrimeIndex / PrimeTest type functions.

Given the parameters it knows - a starting number, a search direction, the type of number to find - it simply computes the next number by some means other than mere data retrieval.

The DIM may accept input interactively, or from a newline-terminated text file, or from a pre-initialized array. You may not pack extraneous data other than the command sequence into the input - play fair!

This is a code golf, so least number of bytes wins. Submit your program with output results for the following search sessions:

  1. P O U R F O R U S O U R P R O W S
  2. W O R K F O R P O O R F O R K S K O O P S R O O K S F O U R W O W S
  3. P O O P O O P O O P P O O P P R O P S P R O W S P O R K S

It is assumed that you know what prime, square, and Fibonacci numbers are. A brief explanation of the other integer sequences follows.

Odious - a nonnegative number which has an odd number of 1s in its binary expansion. The first few odious numbers are 1, 2, 4, 7, 8, 11, 13, 14, 16, 19

Wasteful - a natural number that has fewer digits than the number of digits in its prime factorization (including the exponents). The first few are 4, 6, 8, 9, 12, 18, 20, 22

Undulating - has alternating digits of the form aba, abab, ababa, etc. Assume all U numbers are non-trivial, i.e. 3 digits or more. The first few: 101, 121, 131, 141, 151, 161, 171, 181, 191, 202, 212

Katadrome - A number whose hexadecimal digits are in strict descending order. The first few are 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 32, 33, 48, 49

\$\endgroup\$
4
  • \$\begingroup\$ When I post the question, I'll also include external links to MathWorld or OEIS for those who need more detail on the less familiar sequences, but the explanations above should be sufficient for most, I think. \$\endgroup\$ Mar 6, 2014 at 23:28
  • \$\begingroup\$ Your definition of "undulating" isn't the one I'm familiar with, which just requires that the digits alternately increase and decrease. Also, it would be better to include expected answers for the test cases, so that submitters can use them as test cases rather than them serving just for you to say "No, this is buggy". \$\endgroup\$ Mar 6, 2014 at 23:57
  • \$\begingroup\$ Yes, that's my plan, I just haven't finished double checking my results for the test cases yet. OEIS and Mathworld have the strict 2-digit definition of undulating, but I'll make sure to make the definition here more prominent so it is clear which interpretation is meant. \$\endgroup\$ Mar 7, 2014 at 0:04
  • \$\begingroup\$ Hello! This looks like a good but abandoned meta post, would you be willing to offer it for adoption? (If you want to, you can still post to main.) \$\endgroup\$
    – user58826
    Jun 9, 2017 at 16:09
2
\$\begingroup\$

Unified format patcher

Write the shortest program that will take a patch file in the unified format from stdin and apply that patch. No external tools that do the process for you can be used.

Clarifications

  • Extra documentation about the unified format can be found here
  • All file paths will be relative
  • Only one file will be modified per patch
  • Timestamps can be ignored
  • The patch file will be valid and will apply cleanly to the file specified (it will not lie about line numbers, etc..)
  • Assume all files being patched already exist, you don't need to create/delete files

Extra

  • -35 - Take an argument that allows you to unpatch a patch

Example

/test/a.cpp

#include <iostream>
using namespace std;

int main() {
    cout << "Hello world!";
    return 0;
}

patch.txt

--- a/test/a.cpp
+++ b/test/a.cpp
@@ -1,7 +1,8 @@
 #include <iostream>
+#include <vector>
 using namespace std;

 int main() {
-    cout << "Hello world!";
+    cout << "Goodbye world!";
     return 0;
 }

Run patch

patch.exe patch.txt

/test/a.cpp

#include <iostream>
#include <vector>
using namespace std;

int main() {
    cout << "Goodbye world!";
    return 0;
}
\$\endgroup\$
8
  • \$\begingroup\$ Can the program assume that the @@ lines contain the correct line numbers? \$\endgroup\$
    – ugoren
    Mar 6, 2014 at 17:52
  • \$\begingroup\$ A good explanation of the patch file format is needed. If not too long, include it in the question. Else, provide a link. \$\endgroup\$
    – ugoren
    Mar 6, 2014 at 17:53
  • \$\begingroup\$ You forgot the obvious "no external tools" disclaimer. You don't want the patch $1 answer. \$\endgroup\$
    – ugoren
    Mar 6, 2014 at 17:55
  • \$\begingroup\$ @ugoren thanks for the comments, I added some further clarifications. \$\endgroup\$
    – Danny
    Mar 6, 2014 at 18:38
  • \$\begingroup\$ Does "The patch file will be valid (it will not lie about line numbers)" also mean that it will apply cleanly? \$\endgroup\$ Mar 6, 2014 at 19:24
  • \$\begingroup\$ @PeterTaylor yes, updated question. \$\endgroup\$
    – Danny
    Mar 6, 2014 at 19:51
  • \$\begingroup\$ "The shorted program" should say "the shortest program", but other than that I think it's ready to go. Of course, no-one's actually going to do more than filter out the lines starting -, remove the first char from each line, and parse the line-numbers to work out how to splice the resulting text in. \$\endgroup\$ Mar 7, 2014 at 0:01
  • \$\begingroup\$ This sandbox post has had little activity in a while. Please improve / edit it or delete it to help us clean up the sandbox. Due to community guidelines, if you don't respond to this comment in 7 days I have permission to vote to delete this. \$\endgroup\$
    – user58826
    Jun 9, 2017 at 16:10
2
\$\begingroup\$

Efficient Testing for Armstrong Numbers

An Armstrong Number (also known by different names, including Narcissistic Number; see Wikipedia for more information) is a non-negative number (for our purposes represented in base 10) that is equal to the sum of the individual digits of the number each raised to the power of the number of digits. For example:

  1. Start with the three digit number 407.
  2. The individual digits are 4, 0, & 7.
  3. Since it is a three digit number, we raise each digit to the third power: 64 (4^3), 0 (0^3), & 343 (7^3).
  4. The sum of those values is 407 (64 + 0 + 343).
  5. Because the final sum is equal to the original number, it is an Armstrong Number.

By contrast:

  1. Start with 47.
  2. The individual digits are 4 & 7.
  3. A two digit number, so raise each digit to the second power: 16 (4^2) & 49 (7^2).
  4. The sum of those values is 65 (16 + 49).
  5. The final sum of 65 is not the original number, so it is not an Armstrong Number.

Your mission, should you decide to accept it: Write a program in any programming language (using only standard language features and libraries) implementing the most efficient algorithm possible to test the numbers from 1 through 18,446,744,073,709,551,615 (264-1) inclusive for "Armstrongness", generating a list of Armstrong Numbers, and only Armstrong Numbers, as output.

While any language is acceptable, it should be obvious that interpreted scripting languages will be at a disadvantage in the efficiency department. That being said, a superior algorithm in an interpreted scripting language can beat the pants off an inefficient algorithm in hand tuned assembly language.

Winning Criteria

The algorithm that can check all possible candidate numbers for "Armstrongness" in the least amount of time on a reference computer will be the winner. The reference computer will have the following specifications: {approximately an AMD Phenom class computer with 8 GB RAM running Windows 7 Ultimate 64 bit}

\$\endgroup\$
17
  • \$\begingroup\$ I don't know that this would belong in the (already very long, maybe too long) problem statement above, but other historical background. The class was for Fortran 77, and I was in a friendly competition with my TA to write the shortest version. I never could win that one, so I decided to write the most efficient version instead. Hence: I prefer efficiency puzzles to code golf (though code golf is fun too). \$\endgroup\$ Feb 20, 2014 at 8:30
  • 1
    \$\begingroup\$ This doesn't seem to have an objective winning criterion. You do list "criteria I'll be using to judge this", but a) it mixes specification with winning criteria; b) it combines factors without indicating their weight. \$\endgroup\$ Feb 20, 2014 at 11:51
  • \$\begingroup\$ The question also seems to be about twice as long as it needs to be. If you use the [link text](url) link notation you can shorten it slightly; you can also lose paragraphs by cutting the worked example and brute-force code (link to the existing question on narcissistic numbers instead); cutting the waffling about which languages you think have advantages; and simplifying the motivation. \$\endgroup\$ Feb 20, 2014 at 11:57
  • \$\begingroup\$ I think efficiency problems are not well suited to code-golf. The efficiency of an algorithm depends on too many factors. You could perhaps require the lowest number of power operations. \$\endgroup\$
    – ugoren
    Feb 20, 2014 at 12:43
  • \$\begingroup\$ @ugoren, 0 is easily obtained. \$\endgroup\$ Feb 20, 2014 at 12:57
  • \$\begingroup\$ @PeterTaylor, You're right. Still, trying to replace a time measurement with the number of operations of a certain type sometimes helps define the problem better. \$\endgroup\$
    – ugoren
    Feb 20, 2014 at 15:12
  • \$\begingroup\$ @PeterTaylor: I agree it is quite long, and will consider revisions to it. \$\endgroup\$ Feb 20, 2014 at 21:43
  • \$\begingroup\$ @PeterTaylor: I'm open to better phrasing of the "objective winning criteria" but really, it is pretty objective already. One, no wrong answers allowed in the winner. Two, how efficient is the algorithm (based on the range of numbers tested and time taken to test them). For example, an algorithm that tests all numbers through 9 digits in 100 seconds is faster than an algorithm that takes 20 seconds to test all numbers through 8 digits (10 times larger interval in only 5 times the time). How might you suggest integration of this with the problem statement? \$\endgroup\$ Feb 20, 2014 at 21:48
  • \$\begingroup\$ @PeterTaylor: Glad I included the disclaimer about failing eyesight, given that I searched for narcissistic numbers and came up with nothing. I either searched the wrong portion of PCG (meta) or I made a typo when spelling narcissistic. \$\endgroup\$ Feb 20, 2014 at 21:49
  • \$\begingroup\$ @ugoren: efficiency may not be suited to code golf, but my understanding was that this 'forum' was about "programming puzzles" and "code golf". I certainly would consider finding a more efficient algorithm to be like solving a puzzle, though maybe I'm alone in that, in which case no biggie. \$\endgroup\$ Feb 20, 2014 at 21:51
  • \$\begingroup\$ Edited the problem statement (which is still admittedly quite long, still considering other edits) by removing the final PPS paragraph and replacing the existing links as suggested. \$\endgroup\$ Feb 20, 2014 at 21:59
  • 1
    \$\begingroup\$ The winning criterion is still too imprecise IMO. (NB Of the judging criteria you list, the first is part of the spec, so it's an acceptability criterion rather than a winning criterion). A genuinely objective winning criterion allows me to calculate my score before I submit my answer. \$\endgroup\$ Mar 12, 2014 at 8:47
  • 1
    \$\begingroup\$ It should be much shorter in order to not discourage people from approaching your challenge. Almost all the text after the definition doesn't add anything to the challenge - beside "don't print wrong numbers" which is of course relevant. I also think that a more precise criterion should be given instead. \$\endgroup\$
    – Howard
    Mar 12, 2014 at 9:03
  • \$\begingroup\$ I've posted a "radical" update to it. I suspect the new winning criteria will not be acceptable either, since it involves a "reference computer" for final timing. Very open to suggestions on how to restate it so that a crappy algorithm on fast hardware doesn't beat an efficient algorithm on slow hardware. \$\endgroup\$ Mar 12, 2014 at 20:17
  • \$\begingroup\$ The possibility that processor architecture or available memory affects the results is a tricky issue with fastest-code questions, but there isn't really a better way of comparing speed of programs than measuring on a large test case. I can at least measure how my program compares to someone else's on my computer, and know whether it's close or not. \$\endgroup\$ Mar 12, 2014 at 21:23
1
25 26
27
28 29
152

You must log in to answer this question.

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